Skip to content

Commit 01ec4f4

Browse files
committed
Clean up failed host-key staging
Remove the staged machine credential on write, mode, and publication failures while preserving atomic first-writer-wins creation. Cover the non-race link failure that previously left the temporary secret behind.
1 parent 6d71b62 commit 01ec4f4

2 files changed

Lines changed: 28 additions & 6 deletions

File tree

‎skills/leaf/scripts/leaf/server.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -181,13 +181,15 @@ def host_key() -> str:
181181
path = state_home() / "access.json"
182182
if not path.exists():
183183
staged = path.with_name(f".{secrets.token_hex(8)}.tmp")
184-
staged.write_bytes(json_bytes({"token": secrets.token_urlsafe(16)}))
185-
staged.chmod(0o600)
186184
try:
187-
os.link(staged, path)
188-
except FileExistsError:
189-
pass # someone minted first; theirs is the key, read below
190-
staged.unlink()
185+
staged.write_bytes(json_bytes({"token": secrets.token_urlsafe(16)}))
186+
staged.chmod(0o600)
187+
try:
188+
os.link(staged, path)
189+
except FileExistsError:
190+
pass # someone minted first; theirs is the key, read below
191+
finally:
192+
staged.unlink(missing_ok=True)
191193
return read_json(path)["token"]
192194

193195

‎tests/test_interact_server.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2665,6 +2665,26 @@ def test_the_address_and_key_outlive_the_session_that_first_served(
26652665
assert server_model.host_key() == minted
26662666

26672667

2668+
def test_a_failed_host_key_publish_removes_its_staged_secret(monkeypatch):
2669+
"""The key is staged beside its durable file before an atomic link publishes it.
2670+
A filesystem failure other than the intentional first-writer race still leaves no
2671+
second copy of that machine credential behind."""
2672+
staged = []
2673+
2674+
def refuse(source, _target):
2675+
staged.append(source)
2676+
assert source.exists()
2677+
raise PermissionError("cannot publish access key")
2678+
2679+
monkeypatch.setattr(server_model.os, "link", refuse)
2680+
2681+
with pytest.raises(PermissionError, match="cannot publish access key"):
2682+
server_model.host_key()
2683+
2684+
assert len(staged) == 1 and not staged[0].exists()
2685+
assert not (host_model.state_home() / "access.json").exists()
2686+
2687+
26682688
def test_start_server_spawns_the_public_entrypoint(page_dir, monkeypatch):
26692689
calls = []
26702690

0 commit comments

Comments
 (0)