Skip to content

The agent that grows with you

fix(dashboard-auth): bound the password-login provider and every audit value

unsupportedpastels66fa864f1950
diff --git a/hermes_cli/dashboard_auth/audit.py b/hermes_cli/dashboard_auth/audit.py
index bcb07f56993..af63fc0648d 100644
--- a/hermes_cli/dashboard_auth/audit.py
+++ b/hermes_cli/dashboard_auth/audit.py
@@ -14,6 +14,8 @@ from typing import Any
_log = logging.getLogger(__name__)
_write_lock = threading.Lock()
+_MAX_FIELD_LENGTH = 256
+_TRUNCATION_MARKER = "...[truncated]"
# Field names that must never appear in the log raw; matching kwargs are dropped.
_REDACTED_FIELDS: frozenset = frozenset({
@@ -49,16 +51,29 @@ def _resolve_log_path() -> Path:
return get_hermes_home() / "logs" / "dashboard-auth.log"
+def _bounded_value(value: Any) -> Any:
+ """Bound strings, including nested values and non-JSON object representations."""
+ if isinstance(value, dict):
+ return {k: _bounded_value(v) for k, v in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_bounded_value(v) for v in value]
+ if not isinstance(value, (str, int, float, bool, type(None))):
+ value = repr(value)
+ if isinstance(value, str) and len(value) > _MAX_FIELD_LENGTH:
+ return value[:_MAX_FIELD_LENGTH - len(_TRUNCATION_MARKER)] + _TRUNCATION_MARKER
+ return value
+
+
def audit_log(event: AuditEvent, **fields: Any) -> None:
"""Append one event; token-like fields dropped, log dir created. Write failures are logged at
WARNING but never raise — auth must not fail because the audit logger broke."""
- entry = {
- "ts": _dt.datetime.now(_dt.timezone.utc).isoformat(),
- "event": event.value,
- **{k: v for k, v in fields.items() if k not in _REDACTED_FIELDS}}
- line = json.dumps(entry, separators=(",", ":")) + "\n"
- path = _resolve_log_path()
try:
+ entry = {
+ "ts": _dt.datetime.now(_dt.timezone.utc).isoformat(),
+ "event": event.value,
+ **{k: _bounded_value(v) for k, v in fields.items() if k not in _REDACTED_FIELDS}}
+ line = json.dumps(entry, separators=(",", ":")) + "\n"
+ path = _resolve_log_path()
path.parent.mkdir(parents=True, exist_ok=True)
with _write_lock, open(path, "a", encoding="utf-8") as f:
f.write(line)
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index 5778f5bd27e..3951904cb00 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -26,7 +26,7 @@ from urllib.parse import quote, unquote, urlencode, urlparse, urlunparse
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from starlette.concurrency import run_in_threadpool
from hermes_cli.dashboard_auth import (
@@ -390,7 +390,8 @@ def _reset_password_rate_limit() -> None:
class _PasswordLoginBody(BaseModel):
- provider: str
+ # Providers use short stable IDs, not display names or URLs.
+ provider: str = Field(max_length=128)
username: str
password: str
next: str = ""
diff --git a/tests/hermes_cli/test_dashboard_auth_audit.py b/tests/hermes_cli/test_dashboard_auth_audit.py
index d9923f476a2..97d8250f705 100644
--- a/tests/hermes_cli/test_dashboard_auth_audit.py
+++ b/tests/hermes_cli/test_dashboard_auth_audit.py
@@ -7,6 +7,7 @@ serialisation so we never leak refresh tokens or JWTs to disk.
from __future__ import annotations
import json
+from pathlib import Path
import pytest
from hermes_cli.dashboard_auth.audit import audit_log, AuditEvent
@@ -23,6 +24,28 @@ def profile_home(tmp_path, monkeypatch):
return home
[email protected]("non_native", [False, True])
+def test_audit_bounds_string_values(profile_home: Path, non_native: bool) -> None:
+ oversized = 'value"\n' * 1000
+ audit_log(
+ AuditEvent.LOGIN_FAILURE, provider=oversized,
+ details={"values": [oversized]}, extra=Path(oversized) if non_native else oversized,
+ reason="invalid_credentials", attempts=3, allowed=False,
+ access_token=oversized,
+ )
+ lines = (profile_home / "logs" / "dashboard-auth.log").read_text().splitlines()
+ assert len(lines) == 1
+ entry = json.loads(lines[0])
+ for value in (entry["provider"], entry["details"]["values"][0], entry["extra"]):
+ assert len(value) <= 256
+ assert value.endswith("...[truncated]")
+ assert oversized.startswith(entry["provider"].removesuffix("...[truncated]"))
+ assert entry["reason"] == "invalid_credentials"
+ assert entry["attempts"] == 3
+ assert entry["allowed"] is False
+ assert "access_token" not in entry
+
+
def test_audit_writes_jsonlines(profile_home):
audit_log(AuditEvent.LOGIN_START, provider="nous", ip="1.2.3.4")
audit_log(
diff --git a/tests/hermes_cli/test_dashboard_auth_password_login.py b/tests/hermes_cli/test_dashboard_auth_password_login.py
index 890f42b075f..8f83a613134 100644
--- a/tests/hermes_cli/test_dashboard_auth_password_login.py
+++ b/tests/hermes_cli/test_dashboard_auth_password_login.py
@@ -13,6 +13,7 @@ provider, flip ``app.state.auth_required = True``, drive a ``TestClient``.
from __future__ import annotations
import time
+from pathlib import Path
from typing import Any, cast
import pytest
@@ -229,6 +230,32 @@ class TestProviderListFlag:
class TestPasswordLoginRoute:
+ @pytest.mark.parametrize("rate_limited", [False, True])
+ def test_oversized_provider_rejected_without_audit(
+ self: TestPasswordLoginRoute, gated_app: TestClient,
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, rate_limited: bool,
+ ) -> None:
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ if rate_limited:
+ response = None
+ for _ in range(15):
+ response = gated_app.post(
+ "/auth/password-login",
+ json={"provider": "testpw", "username": "admin", "password": "WRONG"},
+ )
+ assert response is not None and response.status_code == 429
+ path = tmp_path / "logs" / "dashboard-auth.log"
+ before = path.read_text() if path.exists() else ""
+ provider = "p" * 129
+ response = gated_app.post(
+ "/auth/password-login",
+ json={"provider": provider, "username": "admin", "password": "WRONG"},
+ )
+ after = path.read_text() if path.exists() else ""
+ assert response.status_code == 422
+ assert provider not in after
+ assert after == before
+
def test_valid_credentials_set_session_cookies_and_return_next(
self, gated_app
):