Source code for fleetmesh_auth.engine

"""Core authentication engine for FleetMesh Auth (`fleetmesh_auth.engine`)."""
from __future__ import annotations

import json
import logging
import sqlite3
import threading
import time
from typing import Any, Callable, Dict, List, Optional, Sequence, Union

from fleetmesh_core.identity.auth_wire import normalize_login_payload
from fleetmesh_core.identity.web_auth import AuthRefused, SecretsTokenSource, TokenSource

from fleetmesh_auth.errors import refusal
from fleetmesh_auth.stores.base import AuthStore, SessionRecord
from fleetmesh_auth.stores.sqlite import SqliteAuthStore
from fleetmesh_auth.stores.web_auth import StoreBackedWebAuth

from fleetmesh_auth.directory import UserDirectory
from fleetmesh_auth.plugins import load_plugins
from fleetmesh_auth.principal import (
    LOGIN_METHOD_CATALOG,
    AuthPrincipal,
    AuthWidgetConfig,
    normalize_method_id,
    resolve_login_options,
    resolve_widget_config,
)
from fleetmesh_auth.providers.base import (
    HANDLE_CHECK_RE,
    HANDLE_CHECK_REASONS,
    AuthContext,
    AuthProviderPlugin,
)
from fleetmesh_auth.providers.key_did import SovereignKeyBunkerProvider
from fleetmesh_auth.providers.local_operator import LocalOperatorProvider
from fleetmesh_auth.settings import (
    disabled_methods_from_env,
    disabled_providers_from_env,
    enabled_methods_from_env,
    enabled_providers_from_env,
)
from fleetmesh_auth.host_directory import HostDirectory


log = logging.getLogger("fleetmesh_auth")

# Roles that make a session an admin one and earn it a separate admin token.
ADMIN_SESSION_ROLES = ("admin", "moderator", "node_operator")
ADMIN_TOKEN_PREFIX = "fmauth_admin_"


[docs]class FleetmeshAuthEngine: """Pluggable multi-provider authentication engine for FleetMesh applications. Coordinates: - Sovereign Key / DID / NIP-46 Bunker / NIP-07 Browser Extension / Passkey auth - Provider plugins (accounts on other services, e.g. 'Sign in with Acme'; see plugins.py) - Standalone Node Operator Token auth (`LocalOperatorProvider`) - Developer/Operator modular login method & provider selection - Unified session storage (`fleetmesh_auth_sessions`) + automatic session bridging with an attached host application engine (`sessions` and `admin_sessions`) when co-hosted. """
[docs] def __init__( self, *, db_path: Optional[str] = None, host: Any = None, directory: Optional[UserDirectory] = None, domain: str = "fleetmesh.local", session_ttl_sec: int = 86400 * 7, allow_any_sovereign_key: bool = False, enabled_methods: Optional[Sequence[str]] = None, disabled_methods: Optional[Sequence[str]] = None, enabled_providers: Optional[Sequence[str]] = None, disabled_providers: Optional[Sequence[str]] = None, plugins: Union[bool, Sequence[AuthProviderPlugin]] = True, clock: Optional[Callable[[], int]] = None, token_source: Optional[TokenSource] = None, store: Optional[AuthStore] = None, ) -> None: # Every hidden input is injectable: `clock()` is "now" for challenges, # tickets, sessions and passkeys; `token_source` mints the challenge, # the ticket nonce and the session token. The defaults are the wall # clock and `secrets`, so nothing changes unless a test asks. self.clock: Callable[[], int] = clock or (lambda: int(time.time())) self.token_source: TokenSource = token_source if token_source is not None else SecretsTokenSource() # The app's users: an explicit directory, else a co-hosted host # application's. `host` itself is handed to providers too, as the host # application object. self._explicit_directory = directory self.directory: Optional[UserDirectory] = directory self.host = host self.domain = domain self.session_ttl_sec = int(session_ttl_sec) self.allow_any_sovereign_key = bool(allow_any_sovereign_key) self.enabled_methods: Optional[List[str]] = ( [str(m).strip().lower() for m in enabled_methods if str(m).strip()] if enabled_methods is not None else enabled_methods_from_env() ) self.disabled_methods: List[str] = ( [str(m).strip().lower() for m in disabled_methods if str(m).strip()] if disabled_methods is not None else list(disabled_methods_from_env()) ) self.enabled_providers: Optional[List[str]] = ( [str(p).strip().lower() for p in enabled_providers if str(p).strip()] if enabled_providers is not None else enabled_providers_from_env() ) self.disabled_providers: List[str] = ( [str(p).strip().lower() for p in disabled_providers if str(p).strip()] if disabled_providers is not None else list(disabled_providers_from_env()) ) # Persistence: `store` (sessions, replay state, passkeys; see # fleetmesh_auth.stores) or the sqlite store at `db_path`. if store is None: if db_path is None and self.directory is not None: db_path = self.directory.default_db_path() store = SqliteAuthStore(db_path or ":memory:") self.store: AuthStore = store self.db_path: str = str(getattr(store, "db_path", None) or db_path or "") # Co-hosted sqlite code (and older tests) reach the connection and # its lock through these; they are None on a non-sqlite store. self._conn: Optional[sqlite3.Connection] = getattr(store, "conn", None) self._db_lock: threading.RLock = getattr(store, "lock", None) or threading.RLock() origin_url = domain if domain.startswith(("http://", "https://")) else f"https://{domain}" # Challenges and used auth event ids live in the store too (the # replay seam, see stores/web_auth.py), so replicas sharing a store # share them. self.web_auth = StoreBackedWebAuth( self.store, origin_url=origin_url, challenge_ttl_sec=600, clock=self.clock, token_source=self.token_source, ) self.providers: Dict[str, AuthProviderPlugin] = {} # Keys and DIDs first; plugins (True: discovered, see plugins.py; a # list: exactly those; False: none) next, in order; the local # operator last, so it is the account login tried last. self._key_provider = SovereignKeyBunkerProvider() self.register_provider(self._key_provider) operator = LocalOperatorProvider() if plugins is True: found = load_plugins(reserved=(self._key_provider.provider_id, operator.provider_id)) else: found = list(plugins or []) for provider in found: self.register_provider(provider) self.register_provider(operator)
@property def host(self) -> Any: return self._host @host.setter def host(self, host: Any) -> None: """Attaching a host application engine (here or later) makes it the user directory, unless one was given explicitly.""" self._host = host if self._explicit_directory is None: self.directory = HostDirectory(host) if host is not None else None def _init_schema(self) -> None: self.store.ensure_schema() _init_db = _init_schema
[docs] def register_passkey( self, *, credential_id: str, pubkey_hex: str, did: str, handle: str, public_key_b64: str = "", ) -> None: self.store.put_passkey( credential_id, { "pubkey_hex": pubkey_hex.lower(), "did": did, "handle": handle, "public_key_b64": public_key_b64, "created_at": self.now(), }, )
[docs] def get_passkey(self, credential_id: str) -> Optional[Dict[str, Any]]: return self.store.get_passkey(credential_id)
[docs] def register_provider(self, provider: AuthProviderPlugin) -> None: self.providers[provider.provider_id] = provider
[docs] def list_providers(self) -> List[Dict[str, Any]]: return [p.describe() for p in self.providers.values()]
[docs] def set_enabled_methods( self, enabled_methods: Optional[Sequence[str]] = None, *, disabled_methods: Optional[Sequence[str]] = None, ) -> None: """Configure which login methods this engine allows.""" self.enabled_methods = ( [str(m).strip().lower() for m in enabled_methods if str(m).strip()] if enabled_methods is not None else None ) if disabled_methods is not None: self.disabled_methods = [str(m).strip().lower() for m in disabled_methods if str(m).strip()]
[docs] def set_enabled_providers( self, enabled_providers: Optional[Sequence[str]] = None, *, disabled_providers: Optional[Sequence[str]] = None, ) -> None: """Configure which authentication providers this engine allows.""" self.enabled_providers = ( [str(p).strip().lower() for p in enabled_providers if str(p).strip()] if enabled_providers is not None else None ) if disabled_providers is not None: self.disabled_providers = [str(p).strip().lower() for p in disabled_providers if str(p).strip()]
[docs] def list_login_methods(self, preset: str = "standard") -> List[Dict[str, Any]]: """Return the modular login options currently enabled on this engine.""" return self.get_widget_config(preset=preset)["login_options"]
def _effective_widget_overrides(self, overrides: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: merged: Dict[str, Any] = {} if self.enabled_methods is not None: merged["enabled_methods"] = list(self.enabled_methods) if self.disabled_methods: merged["disabled_methods"] = list(self.disabled_methods) if self.enabled_providers is not None: merged["enabled_providers"] = list(self.enabled_providers) if self.disabled_providers: merged["disabled_providers"] = list(self.disabled_providers) if overrides: merged.update(overrides) return merged
[docs] def get_widget_config( self, preset: str = "standard", overrides: Optional[Dict[str, Any]] = None, ) -> Dict[str, Any]: cfg: AuthWidgetConfig = resolve_widget_config( preset, overrides=self._effective_widget_overrides(overrides), ) # "*" in enabled_providers means every registered provider; otherwise # registered plugins are included unless explicitly restricted. if "*" in cfg.enabled_providers: cfg.enabled_providers = [pid for pid in self.providers if pid not in cfg.disabled_providers] elif self.enabled_providers is None and (not overrides or "enabled_providers" not in overrides): for pid in self.providers: if pid not in cfg.enabled_providers and pid not in cfg.disabled_providers: cfg.enabled_providers.append(pid) providers_detail = [ self.providers[pid].describe() for pid in cfg.enabled_providers if pid in self.providers and pid not in cfg.disabled_providers ] data = cfg.to_dict() data["enabled_providers"] = [pid for pid in cfg.enabled_providers if pid in self.providers and pid not in cfg.disabled_providers] data["providers_detail"] = providers_detail data["login_options"] = resolve_login_options(cfg, providers_detail=providers_detail) return data
[docs] def now(self) -> int: return int(self.clock())
[docs] def ping(self) -> bool: """True when the session store answers a trivial query (readiness).""" return bool(self.store.ping())
[docs] def count_active_sessions(self) -> int: """Unexpired sessions in the engine's own store (one COUNT query).""" return int(self.store.count_active(self.now()))
[docs] def sweep_sessions(self) -> int: """Delete expired sessions (and replay state); returns sessions removed.""" now = self.now() removed = int(self.store.sweep(now)) self.store.sweep_replay(now) return removed
[docs] def close(self) -> None: """Release the store's connections. The engine is unusable afterwards.""" self.store.close()
[docs] def reset_replay_state(self) -> None: """Forget outstanding challenges, used auth events and sessions (tests).""" self.web_auth.reset() self.store.clear_sessions()
[docs] def issue_challenge(self, domain: Optional[str] = None) -> Dict[str, Any]: ch = self.web_auth.issue_challenge(now=self.now()) return { "ok": True, "challenge_id": ch["challenge"], "challenge": ch["challenge"], "challenge_text": ch["auth_message"], "auth_message": ch["auth_message"], "auth_message_sha256": ch["auth_message_sha256"], "domain": domain or self.domain, "instance_url": ch["instance_url"], "expires_at": ch["expires_at"], }
def _infer_provider_order(self, payload: Dict[str, Any]) -> List[str]: explicit = str(payload.get("provider") or payload.get("provider_id") or "").strip().lower() if explicit: # A login that names a provider this node lacks fails as such, # rather than being tried against some other provider. return [explicit] method = str(payload.get("auth_method") or payload.get("method") or "").strip().lower() if ( method in ( "nip46_bunker", "nip07_extension", "nip07_ext", "bunker_nip07", "private_key", "schnorr_key", "did", "did_challenge", "passkey", "webauthn", ) or payload.get("bunker_uri") or payload.get("secret_key") or payload.get("private_key") or payload.get("signature_hex") or payload.get("signature") or payload.get("auth_event") or payload.get("credential_id") or payload.get("passkey_credential_id") ): return ["sovereign_key"] # A token goes to the provider that issues its prefix (fmpass_ # passes to sovereign_key, a plugin's API keys to that plugin). for field in ("portable_ticket", "ticket", "token", "api_key"): token = str(payload.get(field) or "").strip() owners = [pid for pid, p in self.providers.items() if p.claims_token(token)] if owners: return owners if method == "portable_ticket": return ["sovereign_key"] accounts = [pid for pid, p in self.providers.items() if "service_login" in p.supported_methods] if method == "operator_token" or payload.get("operator_token"): return ["local_operator"] + [pid for pid in accounts if pid != "local_operator"] if method in ("api_key", "token"): return [pid for pid, p in self.providers.items() if method in p.supported_methods] return accounts def _persist_session( self, session_token: str, principal: AuthPrincipal, now: int, expires_at: int, ) -> None: record: SessionRecord = { "principal_id": principal.principal_id, "did": principal.did, "pubkey_hex": principal.pubkey_hex, "handle": principal.handle, "display_name": principal.display_name, "provider": principal.provider, "auth_method": principal.auth_method, "roles": list(principal.roles), "scopes": list(principal.scopes), "metadata": dict(principal.metadata or {}), "issued_at": int(now), "expires_at": int(expires_at), } self.store.put(session_token, record, int(expires_at)) def _load_persisted_session(self, session_token: str, now: int) -> tuple[Optional[SessionRecord], bool]: """(record, expired): the live record, or (None, True) when the token is known but past its expiry (the row is dropped), or (None, False).""" record = self.store.get(session_token, now, include_expired=True) if record is None: return None, False if int(record.get("expires_at", 0)) < now: self.store.delete(session_token) return None, True return record, False def _load_persisted_session_by_key(self, session_key: str, now: int) -> tuple[Optional[SessionRecord], bool]: """Like `_load_persisted_session`, for an at-rest key (the value an admin token resolves to).""" record = self.store.get_session_by_key(session_key, now, include_expired=True) if record is None: return None, False if int(record.get("expires_at", 0)) < now: self.store.delete_session_by_key(session_key) return None, True return record, False @staticmethod def _is_admin_session(principal: AuthPrincipal) -> bool: """True for a session that carries an admin-ish role, which is where a separate admin token is issued.""" return any(principal.has_role(role) for role in ADMIN_SESSION_ROLES) def _new_admin_token(self) -> str: """A fresh admin token. It is drawn from the same `token_source` as session tokens (so a test can pin it) but namespaced, so the two kinds of credential are never mistaken for each other.""" raw = str(self.token_source.session_token() or "") if raw.startswith("fmauth_"): raw = raw[len("fmauth_"):] if not raw: # a token source that returned nothing must not mint "" import secrets as _secrets raw = _secrets.token_urlsafe(24) return ADMIN_TOKEN_PREFIX + raw def _issue_admin_token(self, session_token: str, expires_at: int) -> str: """Mint an admin token for `session_token`, store its hash and the mapping, and return it. The caller keeps the plaintext only in the login response; the store holds sha256 values.""" admin_token = self._new_admin_token() self.store.put_admin_token(admin_token, session_token, int(expires_at)) return admin_token def _auth_context(self, now: int, app_preset: str, domain: Optional[str] = None) -> AuthContext: return { "now": now, "web_auth": self.web_auth, "host": self.host, "directory": self.directory, "domain": domain or self.domain, "app_preset": app_preset, "allow_any_sovereign_key": self.allow_any_sovereign_key, "passkey_store": self, } def _open_session(self, principal: AuthPrincipal, now: int) -> Dict[str, Any]: """Mint a session token for `principal`, persist it and build the login response; shared by login and registration. An admin-ish principal additionally gets a *separate* admin token: a different random value, stored only as a hash, that resolves to this session. The login response carries both, so an application keeps the session credential for the API and the admin credential for its admin panel, and leaking one does not hand over the other. """ expires_at = now + self.session_ttl_sec session_token = self.token_source.session_token() # No portable ticket here. A ticket is the identity of the key that # signs it, and the server holds no user's key; the panel mints one # in the browser with the user's own key or signer extension. admin_token = "" if self._is_admin_session(principal): admin_token = self._issue_admin_token(session_token, expires_at) principal.session_token = session_token principal.admin_token = admin_token principal.issued_at = now principal.expires_at = expires_at self._link_session(session_token, principal, now, expires_at) self._persist_session(session_token, principal, now, expires_at) response = { "ok": True, "session_token": session_token, "token": session_token, "expires_at": expires_at, "principal": principal.to_dict(), } # Only an admin session carries the extra credential, so the wire # shape of an ordinary login is unchanged (the conformance vectors # pin it byte for byte). if admin_token: response["admin_token"] = admin_token return response
[docs] def authenticate( self, payload: Dict[str, Any], *, app_preset: str = "standard", required_role: Optional[str] = None, ) -> Dict[str, Any]: norm_payload = normalize_login_payload(payload) now = self.now() context = self._auth_context(now, app_preset) cfg = resolve_widget_config(app_preset, overrides=self._effective_widget_overrides()) disabled_prov = {p.lower() for p in cfg.disabled_providers} enabled_prov = {p.lower() for p in cfg.enabled_providers} if self.enabled_providers is not None else None provider_order = self._infer_provider_order(norm_payload) last_error = "authentication_failed" if provider_order else "no_provider_for_this_login" last_detail: Optional[str] = None auth_res: Optional[Dict[str, Any]] = None # No engine-wide lock here: providers may wait on the network (bunker # round-trips), and the statements they run lock for themselves. for pid in provider_order: if pid in disabled_prov or (enabled_prov is not None and "*" not in enabled_prov and pid not in enabled_prov): last_error, last_detail = "provider_not_enabled", None continue provider = self.providers.get(pid) if provider is None: last_error, last_detail = "unknown_provider", f"No provider '{pid}' on this node" continue try: res = provider.authenticate(norm_payload, context) except AuthRefused as exc: res = exc.to_dict() except Exception: # noqa: BLE001 - a plugin's bug is its login failing, not the engine's log.exception("fleetmesh-auth provider %s raised", pid) res = {"ok": False, "error": "provider_error"} if res.get("ok"): cand_principal: AuthPrincipal = res["principal"] if (self.enabled_methods is not None or self.disabled_methods) and not cfg.is_method_enabled(cand_principal.auth_method): last_error, last_detail = "method_not_enabled", None continue auth_res = res break last_error = str(res.get("error") or last_error) last_detail = res.get("detail") if not auth_res or not auth_res.get("ok"): return refusal(last_error, last_detail) principal: AuthPrincipal = auth_res["principal"] target_role = required_role or norm_payload.get("required_role") if target_role and not principal.has_role(str(target_role)): return refusal("insufficient_role", required_role=str(target_role), roles=list(principal.roles)) return self._open_session(principal, now)
def _provider_allowed(self, pid: str, cfg: AuthWidgetConfig) -> bool: if pid in {p.lower() for p in cfg.disabled_providers}: return False if self.enabled_providers is None: return True enabled = {p.lower() for p in cfg.enabled_providers} return "*" in enabled or pid in enabled
[docs] def register( self, payload: Dict[str, Any], *, domain: Optional[str] = None, app_preset: Optional[str] = None, ) -> Dict[str, Any]: """Create an account through a provider's `register` hook and open a session for it, replying exactly like a successful login. The provider is `payload["provider"]`; when none is named and exactly one registered provider supports registration, that one is used. Refusals: `provider_required`, `unknown_provider`, `registration_unsupported`, `provider_not_enabled`, `method_not_enabled`, `provider_error`, and whatever the provider returns (`handle_taken`, `invalid_handle`, `weak_password`, ...). """ preset = app_preset or "standard" body = dict(payload or {}) now = self.now() cfg = resolve_widget_config(preset, overrides=self._effective_widget_overrides()) explicit = str(body.get("provider") or body.get("provider_id") or "").strip().lower() if explicit: provider = self.providers.get(explicit) if provider is None: return refusal("unknown_provider", f"No provider '{explicit}' on this node") else: candidates = [p for p in self.providers.values() if p.supports_registration()] if not candidates: return refusal("registration_unsupported", "No provider on this node creates accounts") if len(candidates) > 1: return refusal("provider_required", "Name the provider to register with") provider = candidates[0] pid = provider.provider_id if not provider.supports_registration(): return refusal("registration_unsupported", f"Provider '{pid}' does not create accounts") if not self._provider_allowed(pid, cfg): return refusal("provider_not_enabled") # Refuse before the account exists when none of the provider's # methods (service_login for an account provider) is enabled. methods_gated = self.enabled_methods is not None or bool(self.disabled_methods) if methods_gated: provider_methods = [str(m) for m in (provider.supported_methods or ["service_login"])] if not any(cfg.is_method_enabled(m) for m in provider_methods): return refusal("method_not_enabled") context = self._auth_context(now, preset, domain) try: res = provider.register(body, context) except AuthRefused as exc: res = exc.to_dict() except Exception: # noqa: BLE001 - a plugin's bug is its sign-up failing, not the engine's log.exception("fleetmesh-auth provider %s raised in register", pid) res = {"ok": False, "error": "provider_error"} if not isinstance(res, dict) or not res.get("ok") or not isinstance(res.get("principal"), AuthPrincipal): code = str((res or {}).get("error") or "registration_failed") if isinstance(res, dict) else "provider_error" return refusal(code, res.get("detail") if isinstance(res, dict) else None) principal: AuthPrincipal = res["principal"] if not principal.auth_method: principal.auth_method = "service_login" if methods_gated and not cfg.is_method_enabled(principal.auth_method): return refusal("method_not_enabled") # The same role gate as a login: the panel sends its preset's # required_role, and a fresh account without it gets no session. target_role = body.get("required_role") if target_role and not principal.has_role(str(target_role)): return refusal("insufficient_role", required_role=str(target_role), roles=list(principal.roles)) return self._open_session(principal, now)
[docs] def check_handle( self, provider_id: Optional[str], handle: Optional[str], *, app_preset: Optional[str] = None, ) -> Dict[str, Any]: """Ask a provider whether `handle` could be registered, through its `check_handle` hook (`GET /api/fauth/register/check`). Replies `{"ok": True, "available": bool, "reason": None | "handle_taken" | "invalid_handle"}` and nothing else. The handle is trimmed, a leading `@` dropped, and anything empty, longer than `HANDLE_MAX_LEN` or outside `[A-Za-z0-9._-]` is answered `invalid_handle` before the provider sees it. Refusals: `provider_required`, `unknown_provider`, `handle_check_unsupported`, `provider_not_enabled`, `provider_error`, and whatever `ok: False` the hook returns. """ preset = app_preset or "standard" pid = str(provider_id or "").strip().lower() if not pid: return refusal("provider_required", "Name the provider to check the handle with") provider = self.providers.get(pid) if provider is None: return refusal("unknown_provider", f"No provider '{pid}' on this node") if not provider.supports_handle_check(): return refusal("handle_check_unsupported", f"Provider '{pid}' does not check handles") cfg = resolve_widget_config(preset, overrides=self._effective_widget_overrides()) if not self._provider_allowed(pid, cfg): return refusal("provider_not_enabled") clean = str(handle or "").strip() if clean.startswith("@"): clean = clean[1:] if not HANDLE_CHECK_RE.fullmatch(clean): return {"ok": True, "available": False, "reason": "invalid_handle"} try: res = provider.check_handle(clean) except AuthRefused as exc: res = exc.to_dict() except Exception: # noqa: BLE001 - a plugin's bug is its check failing, not the engine's log.exception("fleetmesh-auth provider %s raised in check_handle", pid) res = {"ok": False, "error": "provider_error"} if not isinstance(res, dict): return refusal("provider_error") if not res.get("ok"): return refusal(str(res.get("error") or "provider_error"), res.get("detail")) # A constant shape, whatever the hook put in its dict. available = bool(res.get("available")) reason = res.get("reason") if available: reason = None elif reason not in HANDLE_CHECK_REASONS: reason = "handle_taken" return {"ok": True, "available": available, "reason": reason}
def _link_session(self, token: str, principal: AuthPrincipal, issued_at: int, expires_at: int) -> None: """Carry the session into the app's own session tables, when it keeps any.""" if self.directory is None: return operator_pks = frozenset(p.lower() for p in self._key_provider.operator_pubkeys) self.directory.link_session(token, principal, issued_at, expires_at, operator_pks) def _principal_from_record( self, row: SessionRecord, *, session_token: str = "", admin_token: str = "", ) -> AuthPrincipal: """The principal a stored session record describes.""" return AuthPrincipal( principal_id=str(row.get("principal_id", "")), did=str(row.get("did", "")), pubkey=str(row.get("pubkey_hex", "")), handle=str(row.get("handle", "")), display_name=str(row.get("display_name", "")), provider_id=str(row.get("provider", "")), auth_method=str(row.get("auth_method", "")), roles=list(row.get("roles") or []), scopes=list(row.get("scopes") or []), session_token=session_token, admin_token=admin_token, issued_at=int(row.get("issued_at", 0)), expires_at=int(row.get("expires_at", 0)), metadata=dict(row.get("metadata") or {}), )
[docs] def verify_session( self, token: str, *, required_role: Optional[str] = None, ) -> Dict[str, Any]: """Resolve a bearer credential to its principal. `token` may be a session token or the separate admin token issued with an admin session; both are looked up by their sha256, never stored in the clear. The principal reports which one was presented: `session_token` for a session token, `admin_token` for an admin token. """ clean = (token or "").strip() if clean.lower().startswith("bearer "): clean = clean[7:].strip() if not clean: return refusal("missing_session_token") now = self.now() row, expired = self._load_persisted_session(clean, now) presented_admin_token = "" session_key: Optional[str] = None if row is None: # Not a session token: it may be the admin token of a session. session_key = self.store.resolve_admin_token(clean, now) if session_key is not None: row, expired = self._load_persisted_session_by_key(session_key, now) presented_admin_token = clean if expired: return refusal("expired_session_token") if row is not None: if presented_admin_token: principal = self._principal_from_record(row, admin_token=presented_admin_token) else: principal = self._principal_from_record(row, session_token=clean) if self.directory is not None and not self.directory.has_session(clean): # A session this host has not bridged yet (another replica # wrote it). Mint its own admin token before linking, so # the session credential is never handed to the admin side. if not principal.admin_token and self._is_admin_session(principal): principal.admin_token = self._issue_admin_token(clean, int(row["expires_at"])) self._link_session(clean, principal, int(row["issued_at"]), int(row["expires_at"])) if required_role and not principal.has_role(required_role): return refusal("insufficient_role", required_role=required_role, roles=principal.roles) return {"ok": True, "principal": principal.to_dict()} if self.directory is not None: app_principal = self.directory.resolve_session(clean, now, self.session_ttl_sec) if app_principal is not None: if required_role and not app_principal.has_role(required_role): return refusal("insufficient_role", required_role=required_role, roles=app_principal.roles) return {"ok": True, "principal": app_principal.to_dict()} return refusal("invalid_session_token")
[docs] def revoke_session(self, token: str) -> Dict[str, Any]: """End a session. Either credential works: a session token deletes the session and every admin token that points at it; an admin token deletes that admin credential and the session behind it.""" clean = (token or "").strip() if clean.lower().startswith("bearer "): clean = clean[7:].strip() if not clean: return refusal("missing_session_token") now = self.now() session_key = self.store.resolve_admin_token(clean, now) if session_key is not None: self.store.delete_session_by_key(session_key) self.store.delete_admin_token(clean) else: self.store.delete(clean) if self.directory is not None: self.directory.revoke_session(clean) return {"ok": True}