Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions pkgs/cold-store-reaper/cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import sqlite3
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
Expand Down Expand Up @@ -397,10 +398,25 @@ def init(self) -> dict:
return {"home": str(self.home), "created": created}

def _write_private_json(self, path: Path, obj: dict) -> None:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(obj, f, indent=2)
f.write("\n")
# Atomic write (#3279): serialize to a temp file in the same
# directory, fsync, then os.replace onto the destination, so a
# crash at any point leaves either the old or the new complete
# document - never a torn one. Temp file is 0600 (mkstemp) and
# the destination keeps 0600 after the replace.
fd, tmp_name = tempfile.mkstemp(
dir=path.parent, prefix=path.name + ".", suffix=".tmp"
)
tmp = Path(tmp_name)
try:
with os.fdopen(fd, "w") as f:
json.dump(obj, f, indent=2)
f.write("\n")
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
except BaseException:
tmp.unlink(missing_ok=True)
raise
os.chmod(path, 0o600)

# ------------------------------------------------------------ credentials
Expand All @@ -410,15 +426,29 @@ def load_credentials(self) -> dict:
f"no credentials at {self.credentials_path} — run `cold-store init`, "
"then fill it from Bitwarden (never commit this file)"
)
creds = json.loads(self.credentials_path.read_text())
try:
creds = json.loads(self.credentials_path.read_text())
except json.JSONDecodeError as e:
raise ColdStoreError(
f"credentials.json at {self.credentials_path} is corrupt "
f"(invalid JSON: {e}) - repair or delete the file and "
"re-run `cold-store init`, then refill it from Bitwarden"
) from e
for key in ("client_id", "client_secret"):
if not creds.get(key):
raise ColdStoreError(f"credentials.json is missing {key}")
return creds

def load_state(self) -> dict:
if self.state_path.exists():
return json.loads(self.state_path.read_text())
try:
return json.loads(self.state_path.read_text())
except json.JSONDecodeError as e:
raise ColdStoreError(
f"state.json at {self.state_path} is corrupt "
f"(invalid JSON: {e}) - repair the file, or delete "
"it and let the next run rebuild folder state"
) from e
return {}

def save_state(self, state: dict) -> None:
Expand Down
48 changes: 48 additions & 0 deletions pkgs/cold-store-reaper/tests/test_cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,54 @@ def test_legacy_token_in_state_is_purged_on_save(self):
self.assertEqual(mode, 0o600)


class TestAtomicPrivateJson(ColdStoreTestBase):
"""#3279: private JSON writes are atomic; corrupt files raise
ColdStoreError, never a raw JSONDecodeError."""

@staticmethod
def _crashing_dump(obj, f, **kwargs):
# Simulate a crash mid-write: partial JSON flushed, then abort.
f.write('{"partial": ')
f.flush()
raise OSError("simulated crash mid-write")

def test_failed_write_leaves_previous_state_intact(self):
self.store.save_state({"folders": {"a": "1"}})
with mock.patch("json.dump", side_effect=self._crashing_dump):
with self.assertRaises(OSError):
self.store.save_state({"folders": {"b": "2"}})
self.assertEqual(self.store.load_state(), {"folders": {"a": "1"}})
mode = stat.S_IMODE(self.store.state_path.stat().st_mode)
self.assertEqual(mode, 0o600)
leftovers = [x.name for x in self.home.iterdir() if x.name.endswith(".tmp")]
self.assertEqual(leftovers, [])

def test_failed_write_leaves_previous_credentials_intact(self):
before = self.store.load_credentials()
with mock.patch("json.dump", side_effect=self._crashing_dump):
with self.assertRaises(OSError):
self.store._write_private_json(
self.store.credentials_path, {"client_id": "x"}
)
self.assertEqual(self.store.load_credentials(), before)
mode = stat.S_IMODE(self.store.credentials_path.stat().st_mode)
self.assertEqual(mode, 0o600)

def test_corrupt_state_raises_cold_store_error(self):
self.store.state_path.write_text('{"folders": {"a": "1"')
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.load_state()
self.assertNotIsInstance(ctx.exception, json.JSONDecodeError)
self.assertIn("state.json", str(ctx.exception))

def test_corrupt_credentials_raises_cold_store_error(self):
self.store.credentials_path.write_text('{"client_id": ')
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.load_credentials()
self.assertNotIsInstance(ctx.exception, json.JSONDecodeError)
self.assertIn("credentials.json", str(ctx.exception))


# ------------------------------------------------------------------ fake D1
class FakeD1:
"""Captures D1 REST query calls; can be told to fail.
Expand Down
Loading