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
63 changes: 62 additions & 1 deletion pkgs/cold-store-reaper/cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,23 @@ class ColdStoreError(Exception):
pass


def _json_shape(value) -> str:
"""Human name for a parsed JSON value's shape, for error messages."""
if value is None:
return "null"
if isinstance(value, bool):
return "a boolean"
if isinstance(value, dict):
return "an object"
if isinstance(value, list):
return "a list"
if isinstance(value, str):
return "a string"
if isinstance(value, (int, float)):
return "a number"
return type(value).__name__


def utcnow_str() -> str:
"""SQLite datetime('now') compatible format (UTC, second precision)."""
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
Expand Down Expand Up @@ -444,6 +461,21 @@ def load_credentials(self) -> dict:
f"(invalid JSON: {e}) - repair or delete the file and "
"re-run `cold-store init`, then refill it from Bitwarden"
) from e
if not isinstance(creds, dict):
raise ColdStoreError(
f"credentials.json at {self.credentials_path} has an "
f"unexpected shape (expected a JSON object, got "
f"{_json_shape(creds)}) - repair or delete the file and "
"re-run `cold-store init`, then refill it from Bitwarden"
)
for key in ("client_id", "client_secret", "refresh_token"):
if key in creds and not isinstance(creds[key], str):
raise ColdStoreError(
f"credentials.json at {self.credentials_path} has a "
f"non-string {key} (got {_json_shape(creds[key])}) - "
"repair the file and refill it from Bitwarden "
"(credential values must be strings)"
)
for key in ("client_id", "client_secret"):
if not creds.get(key):
raise ColdStoreError(f"credentials.json is missing {key}")
Expand All @@ -452,13 +484,42 @@ def load_credentials(self) -> dict:
def load_state(self) -> dict:
if self.state_path.exists():
try:
return json.loads(self.state_path.read_text())
state = 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
if not isinstance(state, dict):
raise ColdStoreError(
f"state.json at {self.state_path} has an unexpected "
f"shape (expected a JSON object, got "
f"{_json_shape(state)}) - repair the file, or delete "
"it and let the next run rebuild folder state"
)
if "folders" in state:
folders = state["folders"]
if not isinstance(folders, dict):
raise ColdStoreError(
f"state.json at {self.state_path} has an "
f"unexpected shape (folders must be a JSON "
f"object mapping names to folder ids, got "
f"{_json_shape(folders)}) - repair the file, or "
"delete it and let the next run rebuild folder "
"state"
)
for name, folder_id in folders.items():
if not isinstance(folder_id, str):
raise ColdStoreError(
f"state.json at {self.state_path} has an "
f"unexpected shape (folder id for {name!r} "
f"must be a string, got "
f"{_json_shape(folder_id)}) - repair the "
"file, or delete it and let the next run "
"rebuild folder state"
)
return state
return {}

def save_state(self, state: dict) -> None:
Expand Down
57 changes: 57 additions & 0 deletions pkgs/cold-store-reaper/tests/test_cold_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,63 @@ def test_corrupt_credentials_raises_cold_store_error(self):
self.assertIn("credentials.json", str(ctx.exception))


class TestWrongShapePrivateJson(ColdStoreTestBase):
"""#6845: valid JSON of the wrong shape in credentials.json /
state.json raises ColdStoreError naming the file and the shape -
never a raw AttributeError/TypeError/ValueError, and never a
silently mistyped folder id used against Drive."""

def test_non_object_credentials_raise_cold_store_error(self):
for payload in ('[]', '[{"client_id": "x"}]', '"hello"', "123",
"null", "true"):
self.store.credentials_path.write_text(payload)
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.load_credentials()
self.assertIn("credentials.json", str(ctx.exception), payload)

def test_non_string_credential_value_raises_cold_store_error(self):
for key in ("client_id", "client_secret", "refresh_token"):
creds = {
"client_id": "fake-client-id",
"client_secret": "fake-secret",
"refresh_token": "fake-refresh-token",
}
creds[key] = 123
self.store._write_private_json(self.store.credentials_path, creds)
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.load_credentials()
self.assertIn("credentials.json", str(ctx.exception), key)
self.assertIn(key, str(ctx.exception), key)

def test_non_object_state_raises_cold_store_error(self):
for payload in ('[]', '"hello"', "123", "null", "true"):
self.store.state_path.write_text(payload)
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.load_state()
self.assertIn("state.json", str(ctx.exception), payload)

def test_non_object_folders_raises_cold_store_error(self):
for payload in ('{"folders": "abc"}', '{"folders": 123}',
'{"folders": ["root"]}', '{"folders": null}'):
self.store.state_path.write_text(payload)
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.load_state()
self.assertIn("state.json", str(ctx.exception), payload)

def test_non_string_folder_id_raises_cold_store_error(self):
self.store.state_path.write_text('{"folders": {"bundles": 123}}')
with self.assertRaises(cold_store.ColdStoreError) as ctx:
self.store.load_state()
self.assertIn("state.json", str(ctx.exception))

def test_happy_path_controls_still_pass(self):
self.assertEqual(
self.store.load_credentials()["client_id"], "fake-client-id"
)
self.store.save_state({"folders": {"a": "1"}})
self.assertEqual(self.store.load_state(), {"folders": {"a": "1"}})


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