audit.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. """Audit log for dashboard-auth events: ``$HERMES_HOME/logs/dashboard-auth.log``, one JSON object
  2. per line. Token-like fields are stripped before serialisation so refresh tokens / JWTs never
  3. reach disk. Minimal import surface (no ``hermes_constants`` at import time) so early-loading
  4. middleware can import it."""
  5. from __future__ import annotations
  6. import datetime as _dt
  7. import enum
  8. import json
  9. import logging
  10. import os
  11. import threading
  12. from pathlib import Path
  13. from typing import Any
  14. _log = logging.getLogger(__name__)
  15. _write_lock = threading.Lock()
  16. _MAX_FIELD_LENGTH = 256
  17. _TRUNCATION_MARKER = "...[truncated]"
  18. # Size-based rotation matching hermes_logging's agent.log / errors.log convention
  19. # (maxBytes=5MB, backupCount=3, stdlib RotatingFileHandler ``.1``/``.2``/``.3`` naming).
  20. # Implemented locally (check-and-rename, stdlib only) rather than importing
  21. # hermes_logging/_ManagedRotatingFileHandler: that would pull in hermes_constants
  22. # (and lazily hermes_cli.config) and break this module's import-light guarantee —
  23. # it is imported by middleware that runs very early in startup.
  24. _MAX_BYTES = 5 * 1024 * 1024
  25. _BACKUP_COUNT = 3
  26. # Field names that must never appear in the log raw; matching kwargs are dropped.
  27. _REDACTED_FIELDS: frozenset = frozenset({
  28. "access_token", "refresh_token", "code", "code_verifier",
  29. "state", "ticket", "cookie", "Authorization", "authorization"})
  30. class AuditEvent(enum.Enum):
  31. """Event types; values are the literal ``event`` field on the JSON line."""
  32. LOGIN_START = "login_start"
  33. LOGIN_SUCCESS = "login_success"
  34. LOGIN_FAILURE = "login_failure"
  35. LOGOUT = "logout"
  36. REFRESH_SUCCESS = "refresh_success"
  37. REFRESH_FAILURE = "refresh_failure"
  38. REVOKE = "revoke"
  39. SESSION_VERIFY_FAILURE = "session_verify_failure"
  40. SESSION_REJECTED = "session_rejected"
  41. WS_TICKET_MINTED = "ws_ticket_minted"
  42. WS_TICKET_REJECTED = "ws_ticket_rejected"
  43. TOKEN_AUTH_SUCCESS = "token_auth_success"
  44. TOKEN_AUTH_FAILURE = "token_auth_failure"
  45. # RFC 8252 native-app (system-browser + loopback + PKCE) flow.
  46. NATIVE_AUTHORIZE_START = "native_authorize_start"
  47. NATIVE_CODE_ISSUED = "native_code_issued"
  48. NATIVE_TOKEN_SUCCESS = "native_token_success"
  49. NATIVE_TOKEN_FAILURE = "native_token_failure"
  50. def _resolve_log_path() -> Path:
  51. """Lazy leaf import: honours profile overrides + the native-Windows ``%LOCALAPPDATA%`` fallback."""
  52. from hermes_constants import get_hermes_home
  53. return get_hermes_home() / "logs" / "dashboard-auth.log"
  54. def _bounded_value(value: Any) -> Any:
  55. """Bound strings, including nested values and non-JSON object representations."""
  56. if isinstance(value, dict):
  57. return {k: _bounded_value(v) for k, v in value.items()}
  58. if isinstance(value, (list, tuple)):
  59. return [_bounded_value(v) for v in value]
  60. if not isinstance(value, (str, int, float, bool, type(None))):
  61. value = repr(value)
  62. if isinstance(value, str) and len(value) > _MAX_FIELD_LENGTH:
  63. return value[:_MAX_FIELD_LENGTH - len(_TRUNCATION_MARKER)] + _TRUNCATION_MARKER
  64. return value
  65. def _rotate_if_needed(path: Path, pending_bytes: int) -> None:
  66. """Rotate ``path`` to ``.1``/…/``.<_BACKUP_COUNT>`` once appending *pending_bytes* would
  67. reach ``_MAX_BYTES``. Mirrors stdlib ``RotatingFileHandler``'s naming; must be called
  68. with ``_write_lock`` held. Rotation errors must not break the write path."""
  69. try:
  70. if path.stat().st_size + pending_bytes < _MAX_BYTES:
  71. return
  72. except OSError:
  73. return # missing/vanished mid-check; the append itself surfaces real errors
  74. try:
  75. for i in range(_BACKUP_COUNT - 1, 0, -1):
  76. src = path.with_name(f"{path.name}.{i}")
  77. if src.exists():
  78. os.replace(src, path.with_name(f"{path.name}.{i + 1}"))
  79. os.replace(path, path.with_name(f"{path.name}.1"))
  80. except OSError:
  81. pass # a log that cannot be rotated is still a working (if overlong) log
  82. def audit_log(event: AuditEvent, **fields: Any) -> None:
  83. """Append one event; token-like fields dropped, log dir created, size-capped rotation
  84. (``_MAX_BYTES`` with ``_BACKUP_COUNT`` backups). Write failures are logged at WARNING
  85. but never raise — auth must not fail because the audit logger broke."""
  86. try:
  87. entry = {
  88. "ts": _dt.datetime.now(_dt.UTC).isoformat(),
  89. "event": event.value,
  90. **{k: _bounded_value(v) for k, v in fields.items() if k not in _REDACTED_FIELDS}}
  91. line = json.dumps(entry, separators=(",", ":")) + "\n"
  92. line_bytes = line.encode("utf-8")
  93. path = _resolve_log_path()
  94. path.parent.mkdir(parents=True, exist_ok=True)
  95. with _write_lock:
  96. _rotate_if_needed(path, len(line_bytes))
  97. with open(path, "ab") as f:
  98. f.write(line_bytes)
  99. except Exception as e:
  100. _log.warning("dashboard-auth audit log write failed: %s", e)