From 82f1a208bfad87e291b0dfc2af6459d3df1b386f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 27 Sep 2026 15:07:09 +0200 Subject: [PATCH] Keep the mode of ~/.claude.json and the models file when loop-claude rewrites them --- CHANGELOG.md | 1 + bin/loop-claude | 31 +++++++++++++++++-------------- bin/test_loop_claude.py | 19 +++++++++++++++++-- todo.md | 4 ---- 4 files changed, 35 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 340f37e2..31272802 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,3 +15,4 @@ - `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone. - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. - `bin/` runs on Python 3.11 or newer. +- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop-claude b/bin/loop-claude index 05e645be..f7171a0f 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -227,6 +227,21 @@ def make_private(folder): os.umask(mask) +def replace_json(path, data, **dump): + staged = f"{path}.{os.getpid()}" + try: + mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 + with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: + os.fchmod(handle.fileno(), mode) + json.dump(data, handle, **dump) + os.replace(staged, path) + except OSError as failure: + if os.path.exists(staged): + os.remove(staged) + return failure + return None + + def model(variable, chosen): return ["--model", os.environ.get(variable) or chosen] @@ -248,14 +263,7 @@ def project_model(root): chosen = ask_model(name, saved) # Reread: another loop may have saved its project while this one waited on the human. models = {**read_models(saved), name: chosen} - staged = f"{saved}.{os.getpid()}" - try: - with open(staged, "w", encoding="utf-8") as handle: - json.dump(models, handle, indent="\t", sort_keys=True) - os.replace(staged, saved) - except OSError as failure: - if os.path.exists(staged): - os.remove(staged) + if failure := replace_json(saved, models, indent="\t", sort_keys=True): sys.exit(f"could not save the model in {saved}: {failure.strerror}") print(f"{name} runs on {chosen}", file=sys.stderr) return chosen @@ -511,12 +519,7 @@ def trust(paths): return for path in granted: projects.setdefault(path, {})["hasTrustDialogAccepted"] = True - staged = f"{config}.loop-claude" - try: - with open(staged, "w", encoding="utf-8") as handle: - json.dump(data, handle, indent=2) - os.replace(staged, config) - except OSError as failure: + if failure := replace_json(config, data, indent=2): print(f"could not write {config}: {failure.strerror}", file=sys.stderr) return print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 99de1d55..44876d00 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -30,6 +30,15 @@ def human(content): return {"type": "user", "message": {"content": content}} +@contextlib.contextmanager +def umask(mask): + previous = os.umask(mask) + try: + yield + finally: + os.umask(previous) + + class Sections(unittest.TestCase): def test_keeps_every_headed_section_with_its_bodies(self): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" @@ -147,7 +156,7 @@ class WorkerArgs(unittest.TestCase): class ProjectModel(unittest.TestCase): def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()): + with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022): for variable in ("LOOP_CLAUDE_JUDGE_MODEL", "LOOP_CLAUDE_WORKER_MODEL"): os.environ.pop(variable, None) saved = pathlib.Path(home, ".claude", "loop-claude-models.json") @@ -176,6 +185,8 @@ class ProjectModel(unittest.TestCase): self.assertIn("pick 1 to 2", sys.stderr.getvalue()) self.assertIn("srv/a runs on claude-sonnet-5", sys.stderr.getvalue()) self.assertNotIn("claude-opus-5)", sys.stderr.getvalue()) + self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o600) + saved.chmod(0o640) def saved_elsewhere_while_asking(prompt): saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"})) return "opus[1m]" @@ -192,6 +203,7 @@ class ProjectModel(unittest.TestCase): loop.project_model("/srv/c") self.assertEqual(stopped.exception.code, f"could not save the model in {saved}: Permission denied") self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"}) + self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640) self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"]) for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}): catalog.joinpath("new.json").write_text(json.dumps(shape)) @@ -284,7 +296,7 @@ class Interrupt(unittest.TestCase): class Trust(unittest.TestCase): def test_says_why_the_config_cannot_be_read_and_records_only_what_is_new(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}): + with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), umask(0o022): config = pathlib.Path(home, ".claude.json") with contextlib.redirect_stderr(io.StringIO()) as err: loop.trust(["/a"]) @@ -301,6 +313,7 @@ class Trust(unittest.TestCase): self.assertEqual(json.loads(config.read_text()), shape) data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}} config.write_text(json.dumps(data)) + config.chmod(0o600) with contextlib.redirect_stderr(io.StringIO()) as err: loop.trust(["/a"]) self.assertEqual(err.getvalue(), "") @@ -317,6 +330,8 @@ class Trust(unittest.TestCase): loop.trust(["/c"]) self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n") self.assertEqual(json.loads(config.read_text()), data) + self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600) + self.assertEqual(os.listdir(home), [".claude.json"]) class Parse(unittest.TestCase): diff --git a/todo.md b/todo.md index 0df7d6dc..2c0115db 100644 --- a/todo.md +++ b/todo.md @@ -1,9 +1,5 @@ # todo -## Security - -- Write `~/.claude.json` in `trust` and the models file in `bin/loop-claude` back with their own mode, today each staged copy takes the process umask, so a 0600 `~/.claude.json` holding the account email comes back 0644. - ## 0.1.0 Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). Ordered by the dimension each item lifts, lowest first, per the 2026-09-26 panel; each is one chunk.