credential_persistence.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. """Credential-pool disk-boundary sanitization: strip raw secrets from *borrowed*
  2. pool entries before they reach ``auth.json``. Deliberately free of
  3. ``hermes_cli.auth`` imports so the pool model and the auth-store write boundary
  4. share one policy without import cycles."""
  5. from __future__ import annotations
  6. import hashlib
  7. import re
  8. from typing import Any, Dict, Mapping
  9. # Sources Hermes owns and may persist with secrets. Any other non-empty,
  10. # non-manual source is borrowed/reference-only so new external providers fail
  11. # closed at the disk boundary.
  12. _PERSISTABLE_PROVIDER_SOURCES = frozenset({
  13. ("anthropic", "hermes_pkce"),
  14. ("minimax-oauth", "oauth"),
  15. ("nous", "device_code"),
  16. ("openai-codex", "device_code"),
  17. ("xai-oauth", "device_code"),
  18. })
  19. # Metadata keys that look secret-ish by suffix but are safe to persist.
  20. _SAFE_SECRETISH_METADATA_KEYS = frozenset({
  21. "secret_fingerprint", "secret_source", "token_type", "scope", "client_id",
  22. "agent_key_id", "agent_key_expires_at", "agent_key_expires_in",
  23. "agent_key_reused", "agent_key_obtained_at", "expires_at", "expires_at_ms",
  24. "expires_in", "last_refresh", "last_status", "last_status_at",
  25. "last_error_code", "last_error_reason", "last_error_message",
  26. "last_error_reset_at",
  27. })
  28. _SECRET_VALUE_KEYS = frozenset({
  29. "access_token", "refresh_token", "agent_key", "api_key", "apikey",
  30. "api_token", "auth_token", "authorization", "bearer_token", "client_secret",
  31. "credential", "credentials", "id_token", "oauth_token", "private_key",
  32. "secret_key", "session_token", "password", "secret", "token", "tokens",
  33. })
  34. _SECRET_VALUE_SUFFIXES = (
  35. "_api_key", "_api_token", "_access_token", "_auth_token", "_refresh_token",
  36. "_bearer_token", "_client_secret", "_id_token", "_oauth_token",
  37. "_private_key", "_session_token", "_secret_key", "_password", "_secret",
  38. "_token", "_key",
  39. )
  40. _CAMEL_CASE_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
  41. def _normalize_key(key: Any) -> str:
  42. raw = _CAMEL_CASE_BOUNDARY.sub("_", str(key or "").strip())
  43. return raw.lower().replace("-", "_").replace(".", "_")
  44. def is_borrowed_credential_source(source: Any, provider_id: Any = None) -> bool:
  45. """Return True when ``source`` points at a borrowed/reference-only secret."""
  46. normalized_source = str(source or "").strip().lower()
  47. if not normalized_source or normalized_source == "manual" or normalized_source.startswith("manual:"):
  48. return False
  49. normalized_provider = str(provider_id or "").strip().lower()
  50. return (normalized_provider, normalized_source) not in _PERSISTABLE_PROVIDER_SOURCES
  51. def _is_secret_payload_key(key: Any) -> bool:
  52. normalized = _normalize_key(key)
  53. if not normalized or normalized in _SAFE_SECRETISH_METADATA_KEYS:
  54. return False
  55. return normalized in _SECRET_VALUE_KEYS or normalized.endswith(_SECRET_VALUE_SUFFIXES)
  56. def fingerprint_secret_value(value: Any) -> str | None:
  57. """Non-reversible ``sha256:<16 hex>`` fingerprint of one secret value.
  58. Callers comparing a live secret against the ``secret_fingerprint`` left on
  59. a sanitized (borrowed) pool row need exactly the digest this module writes.
  60. """
  61. text = "" if value is None else str(value)
  62. if not text:
  63. return None
  64. digest = hashlib.sha256(text.encode("utf-8", errors="surrogatepass")).hexdigest()
  65. return f"sha256:{digest[:16]}"
  66. def _credential_secret_fingerprint(payload: Mapping[str, Any]) -> str | None:
  67. preferred = ("agent_key", "access_token", "refresh_token", "api_key", "token", "secret")
  68. candidates = [payload.get(k) for k in preferred]
  69. candidates += [v for k, v in payload.items() if _is_secret_payload_key(k)]
  70. for value in candidates:
  71. fingerprint = fingerprint_secret_value(value)
  72. if fingerprint:
  73. return fingerprint
  74. existing = payload.get("secret_fingerprint")
  75. if isinstance(existing, str) and existing.startswith("sha256:"):
  76. return existing
  77. return None
  78. def sanitize_borrowed_credential_payload(
  79. payload: Mapping[str, Any],
  80. provider_id: Any = None,
  81. ) -> dict[str, Any]:
  82. """Return a disk-safe credential-pool payload.
  83. Owned sources pass through unchanged. Borrowed sources keep labels,
  84. source refs, status/cooldown metadata, counters and a fingerprint, but
  85. every raw secret value field is removed.
  86. """
  87. result = dict(payload)
  88. if not is_borrowed_credential_source(result.get("source"), provider_id):
  89. return result
  90. fingerprint = _credential_secret_fingerprint(result)
  91. sanitized = {k: v for k, v in result.items() if not _is_secret_payload_key(k)}
  92. if fingerprint:
  93. sanitized["secret_fingerprint"] = fingerprint
  94. return sanitized