The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(backup): preserve live OAuth grants on snapshot restore
JoaoMarcos443674fcb73425
diff --git a/hermes_cli/auth_oauth_grants.py b/hermes_cli/auth_oauth_grants.pyindex 99be906b285..60c66abd2da 100644--- a/hermes_cli/auth_oauth_grants.py+++ b/hermes_cli/auth_oauth_grants.py@@ -6,8 +6,9 @@ inside each function so ``hermes_cli.auth.<name>`` patches still intercept (andfrom __future__ import annotations-import logging+import copyimport json+import loggingimport osfrom pathlib import Pathfrom typing import Any, Dict, List, Optional, Tuple@@ -62,6 +63,147 @@ def _is_oauth_pool_payload(entry: Any) -> bool:or str(entry.get("access_token") or "").startswith("sk-ant-oat"))+def merge_snapshot_auth_preserving_live_single_use_grants(+ snapshot_store: Dict[str, Any], live_store: Dict[str, Any],+) -> Dict[str, Any]:+ """Restore historical auth state without reviving spent single-use OAuth generations.++ Snapshot metadata may be restored onto a live grant only when its stable row id proves the+ lineage. Historical single-use refresh material with no live counterpart is dropped because+ there is no local evidence that it is still redeemable. Current live grants always survive.+ """+ from hermes_cli.auth import _credential_token_pair, _merge_pool_row_generation++ restored = copy.deepcopy(snapshot_store)+ snapshot_pool = restored.get("credential_pool")+ live_pool = live_store.get("credential_pool")++ for provider_id in SINGLE_USE_REFRESH_POOL_PROVIDERS:+ live_rows = live_pool.get(provider_id) if isinstance(live_pool, dict) else None+ if not isinstance(live_rows, list):+ live_rows = []+ snapshot_rows = (+ snapshot_pool.get(provider_id) if isinstance(snapshot_pool, dict) else None+ )+ if not isinstance(snapshot_rows, list):+ snapshot_rows = []++ live_grants = [+ row for row in live_rows if _is_forkable_pool_row(provider_id, row)+ ]+ snapshot_has_grants = any(+ _is_forkable_pool_row(provider_id, row) for row in snapshot_rows+ )+ if not live_grants and not snapshot_has_grants:+ continue++ if not isinstance(snapshot_pool, dict):+ snapshot_pool = restored["credential_pool"] = {}++ live_rows_by_id = {+ row.get("id"): row+ for row in live_rows+ if isinstance(row, dict)+ and isinstance(row.get("id"), str)+ and row.get("id")+ }+ live_grants_by_id = {+ row_id: row+ for row_id, row in live_rows_by_id.items()+ if _is_forkable_pool_row(provider_id, row)+ }+ live_without_id = [+ copy.deepcopy(row)+ for row in live_grants+ if not (isinstance(row.get("id"), str) and row.get("id"))+ ]+ merged_snapshot: List[Dict[str, Any]] = []+ consumed_ids: set[str] = set()++ for snapshot_row in snapshot_rows:+ row_id = snapshot_row.get("id") if isinstance(snapshot_row, dict) else None+ live_row = (+ live_rows_by_id.get(row_id)+ if isinstance(row_id, str) and row_id+ else None+ )+ live_is_grant = _is_forkable_pool_row(provider_id, live_row)+ snapshot_is_grant = _is_forkable_pool_row(provider_id, snapshot_row)++ if snapshot_is_grant:+ # A snapshot-only generation may already have spent its refresh token upstream.+ # Stable id + a current row is the only local proof of which credential identity+ # replaced it. Current non-OAuth state wins as a unit; current OAuth state keeps+ # the snapshot metadata while substituting its authoritative token generation.+ if live_row is None or row_id in consumed_ids:+ continue+ consumed_ids.add(row_id)+ if live_is_grant:+ merged_snapshot.append(+ _merge_pool_row_generation(+ snapshot_row,+ live_row,+ provider_id,+ base_pair=_credential_token_pair(snapshot_row),+ )+ )+ else:+ merged_snapshot.append(copy.deepcopy(live_row))+ continue++ if live_is_grant:+ if row_id in consumed_ids:+ continue+ consumed_ids.add(row_id)+ # The historical row changed auth shape but still claims a live OAuth row's stable+ # identity. Keep the live row as a unit rather than manufacturing two credentials.+ merged_snapshot.append(copy.deepcopy(live_row))+ else:+ # Ordinary credentials are historical state: restore the snapshot's version.+ merged_snapshot.append(snapshot_row)++ live_only = [+ copy.deepcopy(row)+ for row_id, row in live_grants_by_id.items()+ if row_id not in consumed_ids+ ]+ snapshot_pool[provider_id] = live_without_id + live_only + merged_snapshot++ snapshot_providers = restored.get("providers")+ live_providers = live_store.get("providers")+ for provider_id in _DEVICE_CODE_BLOCK_PROVIDERS:+ snapshot_block = (+ snapshot_providers.get(provider_id)+ if isinstance(snapshot_providers, dict)+ else None+ )+ live_block = (+ live_providers.get(provider_id)+ if isinstance(live_providers, dict)+ else None+ )+ snapshot_has_refresh = (+ isinstance(snapshot_block, dict)+ and bool(_block_tokens(snapshot_block).get("refresh_token"))+ )+ live_has_refresh = (+ isinstance(live_block, dict)+ and bool(_block_tokens(live_block).get("refresh_token"))+ )+ if not snapshot_has_refresh and not live_has_refresh:+ continue++ if not isinstance(snapshot_providers, dict):+ snapshot_providers = restored["providers"] = {}+ if isinstance(live_block, dict):+ snapshot_providers[provider_id] = copy.deepcopy(live_block)+ else:+ # No current generation exists. Restoring the historical refresh token would+ # resurrect a credential whose single-use token may already be spent.+ snapshot_providers.pop(provider_id, None)++ return restored+def _is_pkce_row(row: Dict[str, Any]) -> bool:return str(row.get("source") or "").endswith("hermes_pkce")diff --git a/hermes_cli/backup.py b/hermes_cli/backup.pyindex 25dad5831d9..1c75ed8fd73 100644--- a/hermes_cli/backup.py+++ b/hermes_cli/backup.py@@ -36,6 +36,7 @@ from hermes_cli.backup_restore import (_detect_prefix,_extract_member_atomically,_import_db_member,+ _restore_auth_json,_safe_restore_db,_validate_backup_zip,)@@ -1479,6 +1480,17 @@ def list_quick_snapshots(return results+def _is_trusted_root_auth_alias(path: Path, home: Path) -> bool:+ """True only for a file symlink resolving to this restore home's default-root auth store."""+ if not path.is_symlink():+ return False+ try:+ trusted = (get_default_hermes_root(home=home) / "auth.json").resolve(strict=False)+ return path.resolve(strict=False) == trusted+ except (OSError, RuntimeError):+ return False++def restore_quick_snapshot(snapshot_id: str,hermes_home: Optional[Path] = None,@@ -1530,8 +1542,12 @@ def restore_quick_snapshot(try:dst.resolve().relative_to(home.resolve())except ValueError:- logger.error("Manifest path traversal blocked: %s", rel)- continue+ # Named profiles may deliberately share the machine-root auth store via an+ # auth.json symlink. Let only that exact trusted alias reach _restore_auth_json;+ # every other manifest destination outside the profile remains a traversal.+ if rel != "auth.json" or not _is_trusted_root_auth_alias(dst, home):+ logger.error("Manifest path traversal blocked: %s", rel)+ continueif not src.exists():continue@@ -1549,6 +1565,14 @@ def restore_quick_snapshot(# dst left as it was. Count as a failure, not a restore.logger.error("Failed to restore %s: refused or source integrity check failed (see previous log)", rel)continue+ elif rel == "auth.json":+ # Refresh tokens for these OAuth providers rotate on use. A historical+ # snapshot can therefore contain a spent pair even though the current+ # auth.json has the live successor. Restore the historical auth state+ # while retaining that live single-use grant under the auth-store lock.+ if not _restore_auth_json(src, dst):+ logger.error("Failed to restore %s safely", rel)+ continueelse:shutil.copy2(src, dst)restored += 1diff --git a/hermes_cli/backup_restore.py b/hermes_cli/backup_restore.pyindex da51878f00a..e54dd44e5f5 100644--- a/hermes_cli/backup_restore.py+++ b/hermes_cli/backup_restore.py@@ -7,6 +7,7 @@ helpers used by ``hermes import`` and ``/snapshot restore``. Backupwhich composes these helpers."""+import jsonimport loggingimport osimport shutil@@ -72,6 +73,88 @@ def _foreign_db_holder_pids(db_path: Path) -> Optional[List[int]]:return pids+def _auth_restore_target(dst: Path) -> Optional[Path]:+ """Writable auth-store path whose lock and publish name the same underlying file.++ A file symlink is resolved so refresh writers and restore take the same auth.lock. A hard-linked+ auth.json cannot be atomically replaced without splitting a deliberately shared store into two+ inodes, so that topology fails closed instead of silently breaking credential sharing.+ """+ try:+ if dst.exists():+ links = dst.stat().st_nlink+ if links > 1:+ logger.error(+ "Refusing auth.json restore to %s: it has %d hard links; atomic replacement "+ "would split a shared auth store",+ dst,+ links,+ )+ return None+ return dst.resolve(strict=False) if dst.is_symlink() else dst+ except (OSError, RuntimeError) as exc:+ logger.error("Refusing auth.json restore to %s: cannot resolve store identity: %s", dst, exc)+ return None+++def _restore_auth_json(src: Path, dst: Path) -> bool:+ """Restore auth.json without rolling back a live single-use OAuth generation.++ The live read and final write share the canonical auth-store lock, so a concurrent refresh+ cannot land between preservation and publish.+ """+ try:+ snapshot_store = json.loads(src.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError, UnicodeError) as exc:+ logger.error("Refusing auth.json restore from %s: %s", src, exc)+ return False+ if not isinstance(snapshot_store, dict):+ logger.error("Refusing auth.json restore from %s: top level is not an object", src)+ return False+ if not (+ isinstance(snapshot_store.get("providers"), dict)+ or isinstance(snapshot_store.get("credential_pool"), dict)+ or isinstance(snapshot_store.get("systems"), dict)+ ):+ logger.error("Refusing auth.json restore from %s: unrecognized auth-store shape", src)+ return False+ # Legacy "systems" stores are still valid snapshot input. Mirror auth._load_auth_store's+ # migration without asking that loader to create a .corrupt sidecar inside the snapshot.+ if (+ not isinstance(snapshot_store.get("providers"), dict)+ and not isinstance(snapshot_store.get("credential_pool"), dict)+ and isinstance(snapshot_store.get("systems"), dict)+ ):+ systems = snapshot_store["systems"]+ providers = {"nous": systems["nous_portal"]} if "nous_portal" in systems else {}+ # Match auth._load_auth_store's migration shape exactly: the legacy+ # "systems" container itself is obsolete and must not be written back.+ snapshot_store = {+ "providers": providers,+ "active_provider": "nous" if providers else None,+ }++ try:+ from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store+ from hermes_cli.auth_oauth_grants import (+ merge_snapshot_auth_preserving_live_single_use_grants,+ )++ target = _auth_restore_target(dst)+ if target is None:+ return False+ with _auth_store_lock(target_path=target):+ live_store = _load_auth_store(target)+ restored = merge_snapshot_auth_preserving_live_single_use_grants(+ snapshot_store, live_store+ )+ _save_auth_store(restored, target_path=target)+ return True+ except Exception as exc:+ logger.error("Failed to restore %s safely: %s", dst, exc)+ return False++def _safe_restore_db(src: Path, dst: Path) -> bool:"""Restore a SQLite database from snapshot *src* into live *dst*.diff --git a/tests/hermes_cli/test_snapshot_restore_oauth.py b/tests/hermes_cli/test_snapshot_restore_oauth.pynew file mode 100644index 00000000000..bb2880c8a2c--- /dev/null+++ b/tests/hermes_cli/test_snapshot_restore_oauth.py@@ -0,0 +1,526 @@+"""Quick snapshot auth restore must not roll back rotated single-use OAuth grants."""++import json+import os++import pytest++from hermes_cli.auth_oauth_grants import (+ SINGLE_USE_REFRESH_POOL_PROVIDERS,+ merge_snapshot_auth_preserving_live_single_use_grants,+)+++def _oauth_row(provider, token, *, row_id="shared", priority=0):+ access = f"sk-ant-oat01-{token}" if provider == "anthropic" else f"access-{token}"+ return {+ "id": row_id,+ "label": row_id,+ "auth_type": "oauth",+ "priority": priority,+ "source": "manual",+ "access_token": access,+ "refresh_token": f"refresh-{token}",+ }++[email protected]("provider", sorted(SINGLE_USE_REFRESH_POOL_PROVIDERS))+def test_merge_preserves_rotated_pool_grant_by_stable_id(provider):+ snapshot = {+ "version": 1,+ "providers": {},+ "credential_pool": {+ provider: [+ {**_oauth_row(provider, "spent", priority=4), "label": "snapshot-label"},+ _oauth_row(provider, "independent", row_id="snapshot-only", priority=2),+ {"id": "api", "auth_type": "api_key", "priority": 3, "api_key": "snapshot-key"},+ ]+ },+ }+ live = {+ "version": 1,+ "providers": {},+ "credential_pool": {provider: [_oauth_row(provider, "rotated")]},+ }++ merged = merge_snapshot_auth_preserving_live_single_use_grants(snapshot, live)+ rows = merged["credential_pool"][provider]++ shared = next(row for row in rows if row.get("id") == "shared")+ assert shared["refresh_token"] == "refresh-rotated"+ assert shared["priority"] == 4+ assert shared["label"] == "snapshot-label"+ assert not any(+ row.get("id") == "shared" and row.get("refresh_token") == "refresh-spent"+ for row in rows+ )+ assert not any(row.get("id") == "snapshot-only" for row in rows)+ assert any(row.get("id") == "api" and row.get("api_key") == "snapshot-key" for row in rows)+++def test_live_grant_replaces_any_historical_row_with_the_same_stable_id():+ """One credential id cannot survive as both the rotated grant and an older row shape."""+ snapshot = {+ "providers": {},+ "credential_pool": {+ "openai-codex": [+ {"id": "shared", "auth_type": "api_key", "priority": 0, "api_key": "historical"},+ _oauth_row("openai-codex", "spent-duplicate", row_id="shared", priority=1),+ _oauth_row("openai-codex", "independent", row_id="snapshot-only", priority=2),+ ]+ },+ }+ live = {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "rotated", row_id="shared")]+ },+ }++ merged = merge_snapshot_auth_preserving_live_single_use_grants(snapshot, live)+ rows = merged["credential_pool"]["openai-codex"]++ assert [row.get("id") for row in rows].count("shared") == 1+ assert next(row for row in rows if row.get("id") == "shared")["refresh_token"] == "refresh-rotated"+ assert not any(row.get("id") == "snapshot-only" for row in rows)+++def test_merge_legacy_oauth_without_id_keeps_only_live_generation():+ """Rows predating stable ids must not leave the spent snapshot generation beside live."""+ spent = _oauth_row("openai-codex", "spent")+ rotated = _oauth_row("openai-codex", "rotated")+ spent.pop("id")+ rotated.pop("id")+ snapshot = {+ "providers": {},+ "credential_pool": {+ "openai-codex": [+ spent,+ {"id": "api", "auth_type": "api_key", "api_key": "snapshot-key"},+ ]+ },+ }+ live = {+ "providers": {},+ "credential_pool": {"openai-codex": [rotated]},+ }++ rows = merge_snapshot_auth_preserving_live_single_use_grants(+ snapshot, live+ )["credential_pool"]["openai-codex"]+ oauth_rows = [row for row in rows if row.get("refresh_token")]++ assert len(oauth_rows) == 1+ assert oauth_rows[0]["refresh_token"] == "refresh-rotated"+ assert any(row.get("id") == "api" and row.get("api_key") == "snapshot-key" for row in rows)++[email protected]("provider", ["openai-codex", "xai-oauth", "nous"])+def test_merge_preserves_live_device_code_refresh_block(provider):+ def block(token):+ if provider == "nous":+ return {"refresh_token": f"refresh-{token}", "access_token": f"access-{token}"}+ return {+ "tokens": {+ "refresh_token": f"refresh-{token}",+ "access_token": f"access-{token}",+ }+ }++ snapshot = {"providers": {provider: block("spent")}}+ live = {"providers": {provider: block("rotated")}}++ merged = merge_snapshot_auth_preserving_live_single_use_grants(snapshot, live)++ assert merged["providers"][provider] == live["providers"][provider]++ without_live = merge_snapshot_auth_preserving_live_single_use_grants(snapshot, {"providers": {}})+ assert provider not in without_live.get("providers", {})+++def test_quick_snapshot_restore_keeps_live_oauth_and_restores_static_auth(+ tmp_path, monkeypatch+):+ from hermes_cli.backup import restore_quick_snapshot++ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))++ live = {+ "version": 1,+ "providers": {+ "openai-codex": {+ "tokens": {+ "access_token": "access-rotated",+ "refresh_token": "refresh-rotated",+ }+ }+ },+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "rotated")],+ "openrouter": [+ {"id": "static", "auth_type": "api_key", "priority": 0, "api_key": "live-static"}+ ],+ },+ }+ (home / "auth.json").write_text(json.dumps(live), encoding="utf-8")++ snapshot = {+ "version": 1,+ "providers": {+ "openai-codex": {+ "tokens": {+ "access_token": "access-spent",+ "refresh_token": "refresh-spent",+ }+ }+ },+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "spent")],+ "openrouter": [+ {"id": "static", "auth_type": "api_key", "priority": 0, "api_key": "snapshot-static"}+ ],+ },+ }+ snap_dir = home / "state-snapshots" / "20260928-before-rotation"+ snap_dir.mkdir(parents=True)+ snap_auth = snap_dir / "auth.json"+ snap_auth.write_text(json.dumps(snapshot), encoding="utf-8")+ (snap_dir / "manifest.json").write_text(+ json.dumps({"files": {"auth.json": snap_auth.stat().st_size}}),+ encoding="utf-8",+ )++ assert restore_quick_snapshot(+ "20260928-before-rotation", hermes_home=home+ ) is True++ restored = json.loads((home / "auth.json").read_text(encoding="utf-8"))+ codex = restored["credential_pool"]["openai-codex"][0]+ assert codex["refresh_token"] == "refresh-rotated"+ assert (+ restored["providers"]["openai-codex"]["tokens"]["refresh_token"]+ == "refresh-rotated"+ )+ assert restored["credential_pool"]["openrouter"][0]["api_key"] == "snapshot-static"+ if os.name != "nt":+ assert (home / "auth.json").stat().st_mode & 0o777 == 0o600++++def test_current_non_oauth_identity_survives_historical_oauth_row():+ snapshot = {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "spent", row_id="shared")]+ },+ }+ live = {+ "providers": {},+ "credential_pool": {+ "openai-codex": [+ {+ "id": "shared",+ "auth_type": "api_key",+ "priority": 0,+ "api_key": "current-static",+ }+ ]+ },+ }++ rows = merge_snapshot_auth_preserving_live_single_use_grants(+ snapshot, live+ )["credential_pool"]["openai-codex"]++ assert rows == [+ {+ "id": "shared",+ "auth_type": "api_key",+ "priority": 0,+ "api_key": "current-static",+ }+ ]+++def test_quick_snapshot_restore_does_not_resurrect_snapshot_only_oauth(+ tmp_path, monkeypatch+):+ from hermes_cli.backup import restore_quick_snapshot++ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ (home / "auth.json").write_text(+ json.dumps({"version": 1, "providers": {}, "credential_pool": {}}),+ encoding="utf-8",+ )++ snapshot = {+ "version": 1,+ "providers": {+ "openai-codex": {+ "tokens": {+ "access_token": "access-spent",+ "refresh_token": "refresh-spent",+ }+ }+ },+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "spent", row_id="old")]+ },+ }+ snap_dir = home / "state-snapshots" / "before-refresh"+ snap_dir.mkdir(parents=True)+ snap_auth = snap_dir / "auth.json"+ snap_auth.write_text(json.dumps(snapshot), encoding="utf-8")+ (snap_dir / "manifest.json").write_text(+ json.dumps({"files": {"auth.json": snap_auth.stat().st_size}}),+ encoding="utf-8",+ )++ assert restore_quick_snapshot("before-refresh", hermes_home=home) is True++ restored = json.loads((home / "auth.json").read_text(encoding="utf-8"))+ assert not restored.get("credential_pool", {}).get("openai-codex")+ assert "openai-codex" not in restored.get("providers", {})+++def test_auth_restore_resolves_symlink_before_lock_and_publish(tmp_path, monkeypatch):+ from hermes_cli.backup_restore import _restore_auth_json++ home = tmp_path / "root"+ profile = tmp_path / "profile"+ home.mkdir()+ profile.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))++ target = home / "auth.json"+ target.write_text(+ json.dumps(+ {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "rotated")]+ },+ }+ ),+ encoding="utf-8",+ )+ alias = profile / "auth.json"+ try:+ alias.symlink_to(target)+ except (OSError, NotImplementedError) as exc:+ pytest.skip(f"symlink unavailable: {exc}")++ snapshot = tmp_path / "snapshot-auth.json"+ snapshot.write_text(+ json.dumps(+ {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "spent")],+ "openrouter": [+ {+ "id": "static",+ "auth_type": "api_key",+ "api_key": "snapshot-static",+ }+ ],+ },+ }+ ),+ encoding="utf-8",+ )++ assert _restore_auth_json(snapshot, alias) is True+ assert alias.is_symlink()+ restored = json.loads(target.read_text(encoding="utf-8"))+ assert restored["credential_pool"]["openai-codex"][0]["refresh_token"] == "refresh-rotated"+ assert restored["credential_pool"]["openrouter"][0]["api_key"] == "snapshot-static"+ assert (home / "auth.lock").exists()+ assert not (profile / "auth.lock").exists()+++def test_quick_snapshot_restore_allows_named_profile_auth_alias_to_root(+ tmp_path, monkeypatch+):+ from hermes_cli.backup import restore_quick_snapshot++ root = tmp_path / "root"+ profile = root / "profiles" / "work"+ profile.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(profile))++ target = root / "auth.json"+ target.write_text(+ json.dumps(+ {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "rotated")],+ "openrouter": [+ {+ "id": "static",+ "auth_type": "api_key",+ "api_key": "live-static",+ }+ ],+ },+ }+ ),+ encoding="utf-8",+ )+ alias = profile / "auth.json"+ try:+ alias.symlink_to(target)+ except (OSError, NotImplementedError) as exc:+ pytest.skip(f"symlink unavailable: {exc}")++ snapshot = {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "spent")],+ "openrouter": [+ {+ "id": "static",+ "auth_type": "api_key",+ "api_key": "snapshot-static",+ }+ ],+ },+ }+ snap_dir = profile / "state-snapshots" / "named-profile"+ snap_dir.mkdir(parents=True)+ snap_auth = snap_dir / "auth.json"+ snap_auth.write_text(json.dumps(snapshot), encoding="utf-8")+ (snap_dir / "manifest.json").write_text(+ json.dumps({"files": {"auth.json": snap_auth.stat().st_size}}),+ encoding="utf-8",+ )++ assert restore_quick_snapshot("named-profile", hermes_home=profile) is True+ assert alias.is_symlink()+ restored = json.loads(target.read_text(encoding="utf-8"))+ assert restored["credential_pool"]["openai-codex"][0]["refresh_token"] == "refresh-rotated"+ assert restored["credential_pool"]["openrouter"][0]["api_key"] == "snapshot-static"+ assert (root / "auth.lock").exists()+ assert not (profile / "auth.lock").exists()+++def test_quick_snapshot_restore_rejects_untrusted_auth_alias(+ tmp_path, monkeypatch+):+ from hermes_cli.backup import restore_quick_snapshot++ root = tmp_path / "root"+ profile = root / "profiles" / "work"+ external = tmp_path / "external"+ profile.mkdir(parents=True)+ external.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(profile))++ target = external / "auth.json"+ target.write_text(json.dumps({"providers": {}, "sentinel": "outside"}), encoding="utf-8")+ before = target.read_bytes()+ alias = profile / "auth.json"+ try:+ alias.symlink_to(target)+ except (OSError, NotImplementedError) as exc:+ pytest.skip(f"symlink unavailable: {exc}")++ snap_dir = profile / "state-snapshots" / "untrusted-alias"+ snap_dir.mkdir(parents=True)+ snap_auth = snap_dir / "auth.json"+ snap_auth.write_text(+ json.dumps(+ {+ "providers": {},+ "credential_pool": {+ "openrouter": [+ {"id": "static", "auth_type": "api_key", "api_key": "snapshot-static"}+ ]+ },+ }+ ),+ encoding="utf-8",+ )+ (snap_dir / "manifest.json").write_text(+ json.dumps({"files": {"auth.json": snap_auth.stat().st_size}}),+ encoding="utf-8",+ )++ assert restore_quick_snapshot("untrusted-alias", hermes_home=profile) is False+ assert alias.is_symlink()+ assert target.read_bytes() == before+++def test_auth_restore_refuses_hardlinked_store_instead_of_splitting_it(+ tmp_path, monkeypatch+):+ from hermes_cli.backup_restore import _restore_auth_json++ home = tmp_path / "root"+ twin = tmp_path / "twin"+ home.mkdir()+ twin.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))++ target = home / "auth.json"+ target.write_text(+ json.dumps(+ {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "rotated")]+ },+ }+ ),+ encoding="utf-8",+ )+ alias = twin / "auth.json"+ try:+ os.link(target, alias)+ except (OSError, NotImplementedError) as exc:+ pytest.skip(f"hardlink unavailable: {exc}")++ snapshot = tmp_path / "snapshot-auth.json"+ snapshot.write_text(+ json.dumps(+ {+ "providers": {},+ "credential_pool": {+ "openai-codex": [_oauth_row("openai-codex", "spent")]+ },+ }+ ),+ encoding="utf-8",+ )+ before = target.read_bytes()++ assert _restore_auth_json(snapshot, alias) is False+ assert alias.samefile(target)+ assert target.read_bytes() == before+ assert alias.read_bytes() == before+++def test_invalid_snapshot_auth_never_replaces_live_store(tmp_path, monkeypatch):+ from hermes_cli.backup import restore_quick_snapshot++ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ live_path = home / "auth.json"+ live_path.write_text(json.dumps({"providers": {}, "sentinel": "live"}), encoding="utf-8")+ before = live_path.read_bytes()++ snap_dir = home / "state-snapshots" / "bad"+ snap_dir.mkdir(parents=True)+ (snap_dir / "auth.json").write_bytes(b"{not-json")+ (snap_dir / "manifest.json").write_text(+ json.dumps({"files": {"auth.json": 9}}), encoding="utf-8"+ )++ assert restore_quick_snapshot("bad", hermes_home=home) is False+ assert live_path.read_bytes() == before