"""Store interfaces (`fleetmesh_auth.stores.base`).
Three concerns, one object: sessions (bearer token → serialised principal),
replay state (single-use challenges and used auth event ids) and passkeys.
`AuthStore` is all three plus schema management; the engine takes one.
Every `now` / `expires_at` is a Unix timestamp in seconds. Methods are
thread-safe: the engine's HTTP server calls them from many threads.
Bearer tokens are never stored: every store keys a session by
`session_token_key(token)` (sha256 hex) and hashes the token on the way in,
so a dump of the database holds no usable credential. Admin tokens (the
separate credential an admin session gets, see `put_admin_token`) are hashed
the same way and only ever map to a session key.
"""
from __future__ import annotations
import hashlib
from abc import ABC, abstractmethod
from typing import Any, Dict, Optional, Protocol, runtime_checkable
SessionRecord = Dict[str, Any]
"""The serialised session: principal_id, did, pubkey_hex, handle,
display_name, provider, auth_method, roles, scopes, metadata, issued_at,
expires_at (JSON-compatible)."""
[docs]def session_token_key(token: str) -> str:
"""The at-rest key for a bearer token: sha256 hex (the Rust store's form)."""
return hashlib.sha256(str(token or "").encode("utf-8")).hexdigest()
[docs]@runtime_checkable
class SessionStore(Protocol):
[docs] def put(self, token: str, record: SessionRecord, expires_at: int) -> None:
"""Insert or replace the session under `token` (only its hash is stored)."""
...
[docs] def get(self, token: str, now: int, *, include_expired: bool = False) -> Optional[SessionRecord]:
"""The record for `token`, or None when unknown or expired (an expired
row is dropped on the way). `include_expired=True` returns an expired
record untouched so the caller can tell "expired" from "unknown"."""
[docs] def delete(self, token: str) -> None: ...
[docs] def sweep(self, now: int) -> int:
"""Delete sessions with expires_at < now; returns how many."""
...
[docs] def count_active(self, now: int) -> int: ...
[docs] def ping(self) -> bool:
"""True when the backend answers a trivial query (readiness)."""
...
[docs]@runtime_checkable
class ReplayStore(Protocol):
[docs] def issue_challenge(self, challenge: str, expires_at: int) -> None: ...
[docs] def consume_challenge(self, challenge: str, now: int) -> bool:
"""Consume `challenge` exactly once; False when unknown, expired or
already consumed. Concurrent callers: exactly one gets True."""
...
[docs] def consume_event_id(self, event_id: str, pubkey: str, expires_at: int, now: int) -> bool:
"""Record `event_id` as used until max(expires_at, now + 600); False
when a live record already exists (a replay). An expired record is
taken over."""
...
[docs] def sweep_replay(self, now: int) -> None:
"""Drop expired challenges and used event ids."""
...
[docs]@runtime_checkable
class PasskeyStore(Protocol):
[docs] def put_passkey(self, credential_id: str, record: Dict[str, Any]) -> None:
"""Insert or replace; `record` has pubkey_hex, did, handle,
public_key_b64 and created_at."""
...
[docs] def get_passkey(self, credential_id: str) -> Optional[Dict[str, Any]]:
"""The record with `credential_id` added, or None."""
...
[docs]class AuthStore(ABC):
"""Sessions + replay + passkeys behind one backend."""
# -- lifecycle --
[docs] @abstractmethod
def ensure_schema(self) -> None:
"""Create tables when missing; safe to call repeatedly and concurrently."""
[docs] @abstractmethod
def close(self) -> None: ...
[docs] @abstractmethod
def clear(self) -> None:
"""Forget every session, challenge, used event id and passkey (tests)."""
[docs] @abstractmethod
def clear_sessions(self) -> None: ...
[docs] @abstractmethod
def clear_replay(self) -> None: ...
# -- SessionStore --
[docs] @abstractmethod
def put(self, token: str, record: SessionRecord, expires_at: int) -> None: ...
[docs] @abstractmethod
def get(self, token: str, now: int, *, include_expired: bool = False) -> Optional[SessionRecord]: ...
[docs] @abstractmethod
def delete(self, token: str) -> None: ...
[docs] @abstractmethod
def get_session_by_key(self, session_key: str, now: int, *, include_expired: bool = False) -> Optional[SessionRecord]:
"""The record for an at-rest session key (a `session_token_key` value),
same expiry rules as `get`."""
[docs] @abstractmethod
def delete_session_by_key(self, session_key: str) -> None:
"""Delete the session (and its admin tokens) under an at-rest key."""
[docs] @abstractmethod
def put_admin_token(self, admin_token: str, session_token: str, expires_at: int) -> None:
"""Record `admin_token` as a credential for the session of
`session_token`; both are hashed, only the hashes are kept."""
[docs] @abstractmethod
def resolve_admin_token(self, admin_token: str, now: int) -> Optional[str]:
"""The at-rest session key `admin_token` stands for, or None when
unknown or expired."""
[docs] @abstractmethod
def delete_admin_token(self, admin_token: str) -> None:
"""Forget the admin credential `admin_token` (the session stays)."""
[docs] @abstractmethod
def migrate_session_tokens(self) -> int:
"""Hash any session token still stored in the clear, in place, so
sessions created by an older version keep working. Idempotent:
returns how many rows it rewrote (0 once everything is hashed)."""
[docs] @abstractmethod
def sweep(self, now: int) -> int: ...
[docs] @abstractmethod
def count_active(self, now: int) -> int: ...
[docs] @abstractmethod
def ping(self) -> bool: ...
# -- ReplayStore --
[docs] @abstractmethod
def issue_challenge(self, challenge: str, expires_at: int) -> None: ...
[docs] @abstractmethod
def consume_challenge(self, challenge: str, now: int) -> bool: ...
[docs] @abstractmethod
def consume_event_id(self, event_id: str, pubkey: str, expires_at: int, now: int) -> bool: ...
[docs] @abstractmethod
def sweep_replay(self, now: int) -> None: ...
# -- PasskeyStore --
[docs] @abstractmethod
def put_passkey(self, credential_id: str, record: Dict[str, Any]) -> None: ...
[docs] @abstractmethod
def get_passkey(self, credential_id: str) -> Optional[Dict[str, Any]]: ...
USED_EVENT_MIN_RETENTION_SEC = 600
"""A used event id is remembered at least this long past `now` (the core's
`FederatedWebAuth.consume_auth_event_id` rule, and the Rust store's)."""