refactor(plugins/hermes-achievements,dashboard_auth): unify snapshot/scan_meta/result builders, drop dead evaluate_boolean + import shims, compact module docstrings, AST-neutral layout

This commit is contained in:
Teknium
2026-09-02 21:43:13 -07:00
parent e86d3fab86
commit eccfcb5f8e
7 changed files with 242 additions and 383 deletions
+19 -40
View File
@@ -1,28 +1,11 @@
"""BasicAuthProvider — username/password dashboard auth (no OAuth IDP).
Same ``DashboardAuthProvider`` framework as the OAuth providers, but login is a credential
form (``supports_password = True`` + ``complete_password_login``); cookies, verify, refresh,
ws-tickets and logout are shared. No IDP and no database: sessions are stateless
HMAC-signed tokens this provider mints and verifies. Passwords use stdlib scrypt;
``complete_password_login`` always performs a hash even for an unknown username, so the
endpoint is not a username-enumeration timing oracle. ``LAST_SKIP_REASON`` is read by
the gate's fail-closed branch when the plugin loads but declines to register.
Configuration (env wins over config.yaml when set non-empty)::
dashboard:
basic_auth:
username: admin # required
password_hash: "scrypt$..." # preferred — see hash_password()
password: "s3cret" # OR plaintext, hashed in-memory at load
secret: "<32+ random bytes, base64 or hex>" # optional signing key
session_ttl_seconds: 43200 # optional access-token lifetime (12h)
HERMES_DASHBOARD_BASIC_AUTH_USERNAME / _PASSWORD_HASH (preferred) / _PASSWORD (plaintext)
HERMES_DASHBOARD_BASIC_AUTH_SECRET / _TTL_SECONDS
Without ``secret`` a random per-process key is generated: sessions then don't
survive a restart or span multiple worker processes.
Login is a credential form (``supports_password`` + ``complete_password_login``); cookies,
verify, refresh, ws-tickets and logout are the shared framework. Sessions are stateless
HMAC-signed tokens (no IDP, no database); passwords use stdlib scrypt and login always hashes
even for an unknown username (no username-enumeration timing oracle). Config: ``dashboard.
basic_auth.{username,password_hash|password,secret,session_ttl_seconds}`` or the
``HERMES_DASHBOARD_BASIC_AUTH_*`` env vars (env wins when non-empty; see ``_settings``).
"""
from __future__ import annotations
@@ -37,7 +20,8 @@ import secrets
import time
from typing import Optional
from hermes_cli.dashboard_auth import DashboardAuthProvider, InvalidCredentialsError, LoginStart, RefreshExpiredError, Session
from hermes_cli.dashboard_auth import (
DashboardAuthProvider, InvalidCredentialsError, LoginStart, RefreshExpiredError, Session)
from plugins.dashboard_auth._shared import SkipRegistration, load_config_section, register_provider, resolve_env_or_cfg
logger = logging.getLogger(__name__)
@@ -69,8 +53,10 @@ def hash_password(password: str) -> str:
precompute ``password_hash`` for config.yaml (the plaintext then never sits at rest):
``python -c "from plugins.dashboard_auth.basic import hash_password; print(hash_password('pw'))"``."""
salt = secrets.token_bytes(_SCRYPT_SALT_BYTES)
dk = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_SCRYPT_DKLEN, maxmem=0)
return f"scrypt${_SCRYPT_N}${_SCRYPT_R}${_SCRYPT_P}${base64.b64encode(salt).decode()}${base64.b64encode(dk).decode()}"
dk = hashlib.scrypt(
password.encode("utf-8"), salt=salt, n=_SCRYPT_N, r=_SCRYPT_R, p=_SCRYPT_P, dklen=_SCRYPT_DKLEN, maxmem=0)
salt_b64, dk_b64 = base64.b64encode(salt).decode(), base64.b64encode(dk).decode()
return f"scrypt${_SCRYPT_N}${_SCRYPT_R}${_SCRYPT_P}${salt_b64}${dk_b64}"
def _verify_password(password: str, encoded: str) -> bool:
@@ -149,8 +135,7 @@ class BasicAuthProvider(DashboardAuthProvider):
def start_login(self, *, redirect_uri: str) -> LoginStart:
raise NotImplementedError(
"BasicAuthProvider is password-only; there is no OAuth redirect flow. "
"The login page POSTs to /auth/password-login instead."
)
"The login page POSTs to /auth/password-login instead.")
def complete_login(self, *, code: str, state: str, code_verifier: str, redirect_uri: str) -> Session:
raise NotImplementedError("BasicAuthProvider is password-only; use complete_password_login.")
@@ -195,14 +180,12 @@ class BasicAuthProvider(DashboardAuthProvider):
return self._session(
user_id, exp,
_sign({"sub": user_id, "kind": "access", "exp": exp}, self._secret),
_sign({"sub": user_id, "kind": "refresh", "exp": now + _REFRESH_TTL_SECONDS}, self._secret),
)
_sign({"sub": user_id, "kind": "refresh", "exp": now + _REFRESH_TTL_SECONDS}, self._secret))
def _session(self, user_id: str, exp: int, access_token: str, refresh_token: str) -> Session:
return Session(
user_id=user_id, email="", display_name=user_id, org_id="", provider=self.name,
expires_at=exp, access_token=access_token, refresh_token=refresh_token,
)
expires_at=exp, access_token=access_token, refresh_token=refresh_token)
# ---- Plugin entry point ----
@@ -221,8 +204,7 @@ def _resolve_secret(cfg_section: dict) -> bytes:
"dashboard-auth-basic: no 'secret' configured; generating a random "
"per-process signing key. Sessions will not survive a restart or span "
"multiple workers. Set dashboard.basic_auth.secret (or "
"HERMES_DASHBOARD_BASIC_AUTH_SECRET) for stable sessions."
)
"HERMES_DASHBOARD_BASIC_AUTH_SECRET) for stable sessions.")
return secrets.token_bytes(32)
for decoder in (base64.b64decode, bytes.fromhex):
try:
@@ -250,15 +232,13 @@ def _settings() -> dict:
"dashboard.basic_auth.username is not set (and HERMES_DASHBOARD_BASIC_AUTH_USERNAME "
"is empty). Set a username and a password (or password_hash) under "
"dashboard.basic_auth in config.yaml to enable username/password dashboard "
"login, or use the OAuth provider, or pass --insecure to skip the auth gate."
)
"login, or use the OAuth provider, or pass --insecure to skip the auth gate.")
if not password_hash and not plaintext:
raise SkipRegistration(
"dashboard.basic_auth.username is set but neither password_hash nor password "
"is configured. Provide one of them (password_hash is preferred — compute it "
"with plugins.dashboard_auth.basic.hash_password).",
level="warning",
)
level="warning")
# Precedence: env password (hashed in-memory) overrides any config password_hash so
# operators can rotate without editing config; a config password_hash wins over a
# config-only plaintext password (preferred at-rest form).
@@ -271,8 +251,7 @@ def _settings() -> dict:
logger.info(
"dashboard-auth-basic: hashed plaintext password in-memory. "
"For production, precompute dashboard.basic_auth.password_hash "
"and remove the plaintext password from config."
)
"and remove the plaintext password from config.")
try:
ttl = int(ttl_raw) if ttl_raw else _DEFAULT_TTL_SECONDS
except ValueError: