mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
refactor(install,subscription): share manifest parsing and warn on corrupt manifests
- install/state.py: load_manifest and list_manifests share _manifest_from_payload. list_manifests now logs a warning naming a corrupt manifest, and what to do about it, instead of skipping it silently. - subscription/client.py: _credentials_path reuses session_tracking._claude_config_dir (same CLAUDE_CONFIG_DIR or ~/.claude resolution). - Add tests that pin the deployment manifest and the subscription state file at 0600, on create and on overwrite of a 0644 file. These writers stay as they are: fsutil.write_text keeps an existing file's mode, so switching to it would leave a 0644 file readable by others. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Assisted-by: claude-code:claude-opus-5 Headline-Session: 88f3a7f6-986c-4fa8-ab24-0c064dbb438a Headline-AI-Share: 12% strict / 12% weighted
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a9815bbb5f
commit
828b107a4a
+20
-16
@@ -108,6 +108,15 @@ def _migrate_deprecated_image(image: Any) -> Any:
|
||||
return image
|
||||
|
||||
|
||||
def _manifest_from_payload(payload: dict[str, Any]) -> DeploymentManifest:
|
||||
"""Build a manifest from its decoded JSON, migrating the retired image repo."""
|
||||
payload["mutations"] = [ManagedMutation(**item) for item in payload.get("mutations", [])]
|
||||
payload["artifacts"] = [ArtifactRecord(**item) for item in payload.get("artifacts", [])]
|
||||
if "image" in payload:
|
||||
payload["image"] = _migrate_deprecated_image(payload["image"])
|
||||
return DeploymentManifest(**payload)
|
||||
|
||||
|
||||
def load_manifest(profile: str = "default") -> DeploymentManifest | None:
|
||||
"""Load a deployment manifest when present."""
|
||||
|
||||
@@ -119,12 +128,7 @@ def load_manifest(profile: str = "default") -> DeploymentManifest | None:
|
||||
# command and the auto-run `init hook ensure` route through here. Raise a
|
||||
# typed error so callers can report cleanly or degrade gracefully.
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
payload["mutations"] = [ManagedMutation(**item) for item in payload.get("mutations", [])]
|
||||
payload["artifacts"] = [ArtifactRecord(**item) for item in payload.get("artifacts", [])]
|
||||
if "image" in payload:
|
||||
payload["image"] = _migrate_deprecated_image(payload["image"])
|
||||
return DeploymentManifest(**payload)
|
||||
return _manifest_from_payload(json.loads(path.read_text(encoding="utf-8")))
|
||||
except (json.JSONDecodeError, ValueError, TypeError, OSError) as e:
|
||||
raise ManifestError(f"deployment profile '{profile}' is corrupt ({path}): {e}") from e
|
||||
|
||||
@@ -139,16 +143,16 @@ def list_manifests() -> list[DeploymentManifest]:
|
||||
manifests: list[DeploymentManifest] = []
|
||||
for candidate in sorted(root.glob("*/manifest.json")):
|
||||
try:
|
||||
payload = json.loads(candidate.read_text(encoding="utf-8"))
|
||||
payload["mutations"] = [
|
||||
ManagedMutation(**item) for item in payload.get("mutations", [])
|
||||
]
|
||||
payload["artifacts"] = [ArtifactRecord(**item) for item in payload.get("artifacts", [])]
|
||||
if "image" in payload:
|
||||
payload["image"] = _migrate_deprecated_image(payload["image"])
|
||||
manifests.append(DeploymentManifest(**payload))
|
||||
except (OSError, ValueError, TypeError):
|
||||
continue
|
||||
manifests.append(
|
||||
_manifest_from_payload(json.loads(candidate.read_text(encoding="utf-8")))
|
||||
)
|
||||
except (OSError, ValueError, TypeError) as e:
|
||||
logger.warning(
|
||||
"Skipping corrupt deployment manifest %s: %s. Fix or delete the file to "
|
||||
"restore that profile.",
|
||||
candidate,
|
||||
e,
|
||||
)
|
||||
return manifests
|
||||
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ import httpx
|
||||
|
||||
from headroom.offline import OfflineEgressBlocked, guard_egress, note_refusal
|
||||
from headroom.subscription.models import SubscriptionSnapshot
|
||||
from headroom.subscription.session_tracking import _claude_config_dir
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -32,8 +33,7 @@ _TOKEN_EXPIRY_BUFFER_S = 60
|
||||
|
||||
|
||||
def _credentials_path() -> Path:
|
||||
base = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude")
|
||||
return Path(base) / ".credentials.json"
|
||||
return _claude_config_dir() / ".credentials.json"
|
||||
|
||||
|
||||
def _load_credentials_file() -> dict[str, Any] | None:
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -90,7 +93,7 @@ def test_recovery_manifest_preserves_mutations_and_artifacts(monkeypatch, tmp_pa
|
||||
assert not recovery.exists()
|
||||
|
||||
|
||||
def test_list_manifests_ignores_invalid_payloads(monkeypatch, tmp_path: Path) -> None:
|
||||
def test_list_manifests_ignores_invalid_payloads(monkeypatch, tmp_path: Path, caplog) -> None:
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
valid = _manifest()
|
||||
save_manifest(valid)
|
||||
@@ -99,9 +102,26 @@ def test_list_manifests_ignores_invalid_payloads(monkeypatch, tmp_path: Path) ->
|
||||
broken_dir.mkdir(parents=True)
|
||||
(broken_dir / "manifest.json").write_text("{not json", encoding="utf-8")
|
||||
|
||||
manifests = list_manifests()
|
||||
with caplog.at_level(logging.WARNING, logger="headroom.install.state"):
|
||||
manifests = list_manifests()
|
||||
|
||||
assert [manifest.profile for manifest in manifests] == ["default"]
|
||||
warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
|
||||
assert any(str(broken_dir / "manifest.json") in message for message in warnings)
|
||||
assert not any(str(tmp_path / ".headroom" / "deploy" / "default") in m for m in warnings)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="mode bits decide access only on POSIX")
|
||||
def test_save_manifest_keeps_manifest_owner_only(monkeypatch, tmp_path: Path) -> None:
|
||||
monkeypatch.setattr(Path, "home", lambda: tmp_path)
|
||||
save_manifest(_manifest())
|
||||
path = tmp_path / ".headroom" / "deploy" / "default" / "manifest.json"
|
||||
assert stat.S_IMODE(path.stat().st_mode) == 0o600
|
||||
|
||||
# A manifest left group/world-readable is tightened on the next save.
|
||||
path.chmod(0o644)
|
||||
save_manifest(_manifest())
|
||||
assert stat.S_IMODE(path.stat().st_mode) == 0o600
|
||||
|
||||
|
||||
def _write_manifest_with_image(profile_dir: Path, image: str) -> None:
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import sys
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
@@ -363,6 +365,19 @@ async def test_maybe_poll_runs_transcript_scan_off_event_loop(
|
||||
assert seen["thread_id"] != loop_thread_id
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != "posix", reason="mode bits decide access only on POSIX")
|
||||
def test_persist_state_keeps_file_owner_only(tmp_path: Path) -> None:
|
||||
persist_path = tmp_path / "tracker-state.json"
|
||||
tracker = SubscriptionTracker(persist_path=persist_path)
|
||||
tracker._persist_state()
|
||||
assert stat.S_IMODE(persist_path.stat().st_mode) == 0o600
|
||||
|
||||
# A state file left group/world-readable is tightened on the next write.
|
||||
persist_path.chmod(0o644)
|
||||
tracker._persist_state()
|
||||
assert stat.S_IMODE(persist_path.stat().st_mode) == 0o600
|
||||
|
||||
|
||||
def test_persist_and_load_state_round_trip(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
persist_path = tmp_path / "tracker-state.json"
|
||||
tracker = SubscriptionTracker(persist_path=persist_path)
|
||||
|
||||
Reference in New Issue
Block a user