fix(proxy): keep settings.json mode and symlink in the cc-switch reconciler (#4844)

## Description

With `HEADROOM_CC_SWITCH_RECONCILE=1`,
`CCSwitchReconciler._atomic_write` rewrote `~/.claude/settings.json` by
writing `settings.json.<pid>.hrtmp` with `Path.write_text` and
`os.replace`-ing it over the original. The new file got umask
permissions (typically 0644) even when the original was 0600, and a
symlinked `settings.json` (dotfile managers) was replaced by a regular
file. That file holds the provider's `ANTHROPIC_AUTH_TOKEN`.

The reconciler now uses the repo's existing
`headroom.fsutil.write_text`, which writes a unique `mkstemp` (0600)
temp file, fsyncs it, copies the existing file's mode and writes through
a symlink to the real file.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `headroom/proxy/cc_switch_reconciler.py`: `_atomic_write` calls
`fsutil.write_text`.
- `tests/test_proxy/test_cc_switch_reconciler.py`: one test that a 0600
file stays 0600 under umask 022, one that a symlinked settings file
stays a symlink and the target is updated. Both use `tmp_path`, never
the real `~/.claude`.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
# new tests on origin/main (fix stashed)
$ pytest -q tests/test_proxy/test_cc_switch_reconciler.py
FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_rewrite_keeps_owner_only_mode
FAILED tests/test_proxy/test_cc_switch_reconciler.py::test_rewrite_writes_through_a_symlinked_settings_file
========================= 2 failed, 29 passed in 2.41s =========================

# with the fix
$ pytest -q tests/test_proxy/test_cc_switch_reconciler.py tests/test_fsutil.py
============================== 43 passed in 3.13s ==============================

$ ruff check / ruff format --check (0.17.3) on changed files
All checks passed!
$ mypy headroom/proxy/cc_switch_reconciler.py --ignore-missing-imports
Success: no issues found in 1 source file
```

## Real Behavior Proof

- Environment: macOS, Python 3.12, umask 022, a temp HOME (not the real
`~/.claude`).
- Exact command / steps: create `dotfiles/settings.json` (0600) with a
third-party `ANTHROPIC_BASE_URL` and a test token, symlink
`.claude/settings.json` to it, run `CCSwitchReconciler(...,
path=.claude/settings.json).tick()`, then inspect both paths.
- Observed result: on main the reconciler replaces the symlink with a
0644 file; on this branch the symlink and 0600 mode stay and the target
gets the new base URL. Per branch:
- main: `settings.json is symlink: False mode: 0o644`; the dotfiles copy
still has the old base URL.
- this branch: `settings.json is symlink: True mode: 0o600`; the
dotfiles copy now has `ANTHROPIC_BASE_URL=http://127.0.0.1:8787` and
stays 0600.
- Not tested: Windows (mode bits and symlinks are skipped there).

## Runtime Rollout Safety

- Rollout-managed feature(s): cc-switch reconciler
(`HEADROOM_CC_SWITCH_RECONCILE=1`, opt-in)
- Minimum rollout channel: n/a
- Stable/default behavior changed: only for users who opted in;
settings.json keeps its mode and symlink. The temp file name changes
from `settings.json.<pid>.hrtmp` to `.settings.json.<random>.tmp`.
- Kill switch / disable path: unset `HEADROOM_CC_SWITCH_RECONCILE`.
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

No docs change needed. Fix adapted from a proposal by HetCreep.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/4844"
target="_blank"><picture><source media="(prefers-color-scheme: dark)"
srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img
src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4"
alt="Devin Review"></picture></a>
<!-- devin-review-badge-end -->

Reported by @JoaoMarcos44. Thank you for your contribution! 🩵

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-21 16:37:14 -08:00
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent c5d8f13360
commit 3bae009c3f
3 changed files with 61 additions and 6 deletions
+1 -1
View File
@@ -231,7 +231,7 @@ jobs:
# ./tests: collecting ~10k modules on Windows took 91s and pulled in
# unrelated import failures. Add a directory here if you mark a test
# outside these paths.
run: pytest tests/test_learn tests/test_memory tests/test_memory_sync.py -m windows_newline --tb=short -q
run: pytest tests/test_learn tests/test_memory tests/test_memory_sync.py tests/test_proxy/test_cc_switch_reconciler.py -m windows_newline --tb=short -q
python-314-wheels:
# Partners on centrally managed machines cannot choose their Python, and
+5 -5
View File
@@ -52,6 +52,8 @@ from collections.abc import Callable
from pathlib import Path
from urllib.parse import urlsplit
from headroom import fsutil
logger = logging.getLogger(__name__)
_POLL_INTERVAL_S = 0.3
@@ -211,11 +213,9 @@ class CCSwitchReconciler:
return True
def _atomic_write(self, data: dict) -> None:
# Per-process temp name: multiple Headroom processes reconciling the
# same settings.json must not clobber each other's temp file.
tmp = self.path.with_name(f"{self.path.name}.{os.getpid()}.hrtmp")
tmp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
os.replace(tmp, self.path)
# fsutil.write_text: unique temp file, follows a symlinked settings.json
# and keeps the existing file's mode (the file holds the provider token).
fsutil.write_text(self.path, json.dumps(data, indent=2) + "\n")
# Skip the mtime bump caused by our own write so we don't re-process it.
try:
self._last_mtime_ns = self.path.stat().st_mtime_ns
@@ -211,6 +211,40 @@ def test_official_routed_when_opted_in(tmp_path, monkeypatch):
assert captured[-1] == DEFAULT
_THIRD_PARTY = {
"env": {
"ANTHROPIC_BASE_URL": "https://api.deepseek.com/anthropic",
"ANTHROPIC_AUTH_TOKEN": "sk-x",
}
}
@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits")
def test_rewrite_keeps_owner_only_mode(tmp_path):
old_umask = os.umask(0o022)
try:
r, sf, _ = _make(tmp_path)
_write(sf, _THIRD_PARTY)
sf.chmod(0o600)
assert r.tick() is True
assert json.loads(sf.read_text())["env"]["ANTHROPIC_BASE_URL"] == PROXY
assert (sf.stat().st_mode & 0o777) == 0o600
finally:
os.umask(old_umask)
@pytest.mark.skipif(os.name == "nt", reason="symlinks need privileges on Windows")
def test_rewrite_writes_through_a_symlinked_settings_file(tmp_path):
r, sf, _ = _make(tmp_path)
real = tmp_path / "dotfiles" / "settings.json"
real.parent.mkdir()
_write(real, _THIRD_PARTY)
sf.symlink_to(real)
assert r.tick() is True
assert sf.is_symlink()
assert json.loads(real.read_text())["env"]["ANTHROPIC_BASE_URL"] == PROXY
def test_missing_file_is_noop(tmp_path):
r, _, _ = _make(tmp_path) # path does not exist yet
assert r.tick() is False
@@ -249,3 +283,24 @@ def test_enabled_flag(monkeypatch, val, expected):
monkeypatch.setenv("HEADROOM_CC_SWITCH_RECONCILE", val)
assert reconciler_enabled() is expected
@pytest.mark.windows_newline
def test_rewrite_pins_lf_newlines(tmp_path, monkeypatch):
import headroom.fsutil as fsutil
calls: list[dict] = []
real_fdopen = fsutil.os.fdopen
def fdopen(fd, *args, **kwargs):
calls.append(kwargs)
return real_fdopen(fd, *args, **kwargs)
monkeypatch.setattr(fsutil.os, "fdopen", fdopen)
r, sf, _ = _make(tmp_path)
_write(sf, _THIRD_PARTY)
assert r.tick() is True
assert [call.get("newline") for call in calls] == [""]
raw = sf.read_bytes()
assert b"\r" not in raw
assert raw.endswith(b"\n")