Source code for fleetmesh_auth.stores.postgres

"""`PostgresAuthStore`: sessions, replay state and passkeys in Postgres via
psycopg 3, in the tables the Rust t6 `fauth` service uses (`fauth_sessions`,
`fauth_challenges`, `fauth_used_events`) plus `fauth_passkeys`. Several
fleetmesh-auth replicas on one database see each other's sessions and
challenges.

Sessions are keyed by sha256(token) (`token_key`), never the bearer token
itself; the record is the session JSON (JSONB). Admin tokens get their own
sha256 in `fauth_admin_tokens`, mapping to the session key. Every statement is
parametrised; expired rows are ignored on read and swept opportunistically
(roughly every `sweep_interval_sec`, by whichever call comes first).

`psycopg` is imported lazily so the sqlite path has no dependency on it.
Pooling: `psycopg_pool.ConnectionPool` when installed, else a small
thread-safe pool of plain connections (`max_size`).
"""
from __future__ import annotations

import contextlib
import json
import logging
import queue
import threading
import time
from typing import Any, Dict, Iterator, Optional

from fleetmesh_auth.stores.base import (
    USED_EVENT_MIN_RETENTION_SEC,
    AuthStore,
    SessionRecord,
    session_token_key,
)

log = logging.getLogger("fleetmesh_auth.stores.postgres")

__all__ = ["PostgresAuthStore", "SCHEMA_SQL", "DEFAULT_SCHEMA_LOCK_KEY", "session_token_key"]

# The Rust service's advisory key for this very schema (crates/fauth/src/schema.rs):
# Python and Rust replicas serialise CREATE TABLE IF NOT EXISTS on the same lock.
DEFAULT_SCHEMA_LOCK_KEY = 0x706F_636B_7374_0006

SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS fauth_sessions (
    token_key  TEXT PRIMARY KEY,
    record     JSONB NOT NULL,
    expires_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS fauth_sessions_expires_at_idx ON fauth_sessions (expires_at);

CREATE TABLE IF NOT EXISTS fauth_challenges (
    challenge  TEXT PRIMARY KEY,
    expires_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS fauth_challenges_expires_at_idx ON fauth_challenges (expires_at);

CREATE TABLE IF NOT EXISTS fauth_used_events (
    event_id   TEXT PRIMARY KEY,
    pubkey     TEXT NOT NULL DEFAULT '',
    expires_at BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS fauth_used_events_expires_at_idx ON fauth_used_events (expires_at);

CREATE TABLE IF NOT EXISTS fauth_passkeys (
    credential_id  TEXT PRIMARY KEY,
    pubkey_hex     TEXT NOT NULL,
    did            TEXT NOT NULL,
    handle         TEXT NOT NULL,
    public_key_b64 TEXT NOT NULL DEFAULT '',
    created_at     BIGINT NOT NULL
);

CREATE TABLE IF NOT EXISTS fauth_admin_tokens (
    admin_token_key  TEXT PRIMARY KEY,
    session_token_key TEXT NOT NULL,
    expires_at       BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS fauth_admin_tokens_expires_at_idx ON fauth_admin_tokens (expires_at);
CREATE INDEX IF NOT EXISTS fauth_admin_tokens_session_idx ON fauth_admin_tokens (session_token_key);
"""


def _import_psycopg():
    try:
        import psycopg  # noqa: WPS433 - lazy, optional dependency
    except ImportError as exc:  # pragma: no cover - depends on the environment
        raise ImportError(
            "PostgresAuthStore needs psycopg 3: pip install 'psycopg[binary]>=3.1' "
            "(or install fleetmesh-auth with the [postgres] extra)"
        ) from exc
    return psycopg


class _SimplePool:
    """A LIFO pool of autocommit psycopg connections; a connection that
    raised is closed and discarded instead of being returned."""

    def __init__(self, psycopg_mod, dsn: str, max_size: int) -> None:
        self._psycopg = psycopg_mod
        self._dsn = dsn
        self._idle: "queue.LifoQueue[Any]" = queue.LifoQueue()
        self._sem = threading.BoundedSemaphore(max_size)
        self._closed = False

    def _connect(self):
        return self._psycopg.connect(self._dsn, autocommit=True)

    @contextlib.contextmanager
    def connection(self) -> Iterator[Any]:
        if self._closed:
            raise RuntimeError("PostgresAuthStore is closed")
        self._sem.acquire()
        conn = None
        try:
            try:
                conn = self._idle.get_nowait()
            except queue.Empty:
                conn = self._connect()
            if conn.closed:
                conn = self._connect()
            try:
                yield conn
            except BaseException:
                with contextlib.suppress(Exception):
                    conn.close()
                conn = None
                raise
        finally:
            if conn is not None and not self._closed:
                self._idle.put(conn)
            elif conn is not None:
                with contextlib.suppress(Exception):
                    conn.close()
            self._sem.release()

    def close(self) -> None:
        self._closed = True
        while True:
            try:
                conn = self._idle.get_nowait()
            except queue.Empty:
                return
            with contextlib.suppress(Exception):
                conn.close()


[docs]class PostgresAuthStore(AuthStore):
[docs] def __init__( self, dsn: str, *, schema_lock_key: int = DEFAULT_SCHEMA_LOCK_KEY, max_size: int = 8, sweep_interval_sec: int = 60, ensure_schema: bool = True, ) -> None: psycopg = _import_psycopg() self.dsn = dsn self.schema_lock_key = int(schema_lock_key) self.sweep_interval_sec = int(sweep_interval_sec) self._last_sweep = 0.0 self._sweep_lock = threading.Lock() self._pool: Any self._pool_kind: str try: from psycopg_pool import ConnectionPool # noqa: WPS433 - optional except ImportError: ConnectionPool = None # noqa: N806 if ConnectionPool is not None: self._pool = ConnectionPool( dsn, min_size=1, max_size=max_size, open=True, kwargs={"autocommit": True}, name="fleetmesh-auth", ) self._pool_kind = "psycopg_pool" else: self._pool = _SimplePool(psycopg, dsn, max_size) self._pool_kind = "simple" self._schema_ready = False if ensure_schema: self.ensure_schema()
# -- plumbing -- @contextlib.contextmanager def _connection(self) -> Iterator[Any]: """An autocommit connection from the pool. Each statement is its own transaction unless wrapped in `conn.transaction()`.""" with self._pool.connection() as conn: yield conn def _maybe_sweep(self, now: int) -> None: """Opportunistic purge of expired rows, at most once per interval.""" if self.sweep_interval_sec <= 0: return wall = time.monotonic() with self._sweep_lock: if wall - self._last_sweep < self.sweep_interval_sec: return self._last_sweep = wall try: self.sweep(now) self.sweep_replay(now) except Exception as exc: # noqa: BLE001 - a sweep must not fail the request log.warning("fleetmesh-auth postgres sweep failed: %s", exc) # -- lifecycle --
[docs] def ensure_schema(self) -> None: with self._connection() as conn, conn.transaction(): conn.execute("SELECT pg_advisory_xact_lock(%s)", (self.schema_lock_key,)) conn.execute(SCHEMA_SQL) self._schema_ready = True
[docs] def close(self) -> None: self._pool.close()
[docs] def clear(self) -> None: with self._connection() as conn, conn.transaction(): conn.execute("DELETE FROM fauth_sessions") conn.execute("DELETE FROM fauth_admin_tokens") conn.execute("DELETE FROM fauth_challenges") conn.execute("DELETE FROM fauth_used_events") conn.execute("DELETE FROM fauth_passkeys")
[docs] def clear_sessions(self) -> None: with self._connection() as conn, conn.transaction(): conn.execute("DELETE FROM fauth_sessions") conn.execute("DELETE FROM fauth_admin_tokens")
[docs] def clear_replay(self) -> None: with self._connection() as conn, conn.transaction(): conn.execute("DELETE FROM fauth_challenges") conn.execute("DELETE FROM fauth_used_events")
# -- sessions --
[docs] def put(self, token: str, record: SessionRecord, expires_at: int) -> None: payload = dict(record) payload["expires_at"] = int(expires_at) with self._connection() as conn: conn.execute( """ INSERT INTO fauth_sessions (token_key, record, expires_at) VALUES (%s, %s::jsonb, %s) ON CONFLICT (token_key) DO UPDATE SET record = EXCLUDED.record, expires_at = EXCLUDED.expires_at """, (session_token_key(token), json.dumps(payload), int(expires_at)), ) self._maybe_sweep(int(record.get("issued_at") or 0) or int(time.time()))
[docs] def get(self, token: str, now: int, *, include_expired: bool = False) -> Optional[SessionRecord]: return self.get_session_by_key(session_token_key(token), now, include_expired=include_expired)
[docs] def get_session_by_key(self, session_key: str, now: int, *, include_expired: bool = False) -> Optional[SessionRecord]: key = session_key with self._connection() as conn: row = conn.execute( "SELECT record::text, expires_at FROM fauth_sessions WHERE token_key = %s", (key,) ).fetchone() if row is None: return None raw, expires_at = row if int(expires_at) < int(now): if not include_expired: conn.execute("DELETE FROM fauth_sessions WHERE token_key = %s AND expires_at < %s", (key, int(now))) return None try: record = json.loads(raw) except ValueError: log.error("fleetmesh-auth session record undecodable (token_key %s...)", key[:8]) return None if not isinstance(record, dict): return None record.setdefault("expires_at", int(expires_at)) return record
[docs] def delete(self, token: str) -> None: key = session_token_key(token) with self._connection() as conn, conn.transaction(): conn.execute("DELETE FROM fauth_sessions WHERE token_key = %s", (key,)) conn.execute("DELETE FROM fauth_admin_tokens WHERE admin_token_key = %s", (key,)) conn.execute("DELETE FROM fauth_admin_tokens WHERE session_token_key = %s", (key,))
[docs] def delete_session_by_key(self, session_key: str) -> None: with self._connection() as conn, conn.transaction(): conn.execute("DELETE FROM fauth_sessions WHERE token_key = %s", (session_key,)) conn.execute("DELETE FROM fauth_admin_tokens WHERE session_token_key = %s", (session_key,))
# -- admin tokens (a credential of their own for an admin session) --
[docs] def put_admin_token(self, admin_token: str, session_token: str, expires_at: int) -> None: with self._connection() as conn: conn.execute( """ INSERT INTO fauth_admin_tokens (admin_token_key, session_token_key, expires_at) VALUES (%s, %s, %s) ON CONFLICT (admin_token_key) DO UPDATE SET session_token_key = EXCLUDED.session_token_key, expires_at = EXCLUDED.expires_at """, (session_token_key(admin_token), session_token_key(session_token), int(expires_at)), )
[docs] def resolve_admin_token(self, admin_token: str, now: int) -> Optional[str]: if not str(admin_token or "").strip(): return None key = session_token_key(admin_token) with self._connection() as conn: row = conn.execute( "SELECT session_token_key, expires_at FROM fauth_admin_tokens WHERE admin_token_key = %s", (key,), ).fetchone() if row is None: return None session_key, expires_at = row if int(expires_at) < int(now): conn.execute( "DELETE FROM fauth_admin_tokens WHERE admin_token_key = %s AND expires_at < %s", (key, int(now)) ) return None return str(session_key)
[docs] def delete_admin_token(self, admin_token: str) -> None: with self._connection() as conn: conn.execute( "DELETE FROM fauth_admin_tokens WHERE admin_token_key = %s", (session_token_key(admin_token),) )
[docs] def migrate_session_tokens(self) -> int: """Nothing to do here: this store has always keyed sessions by sha256(token). Present for the `AuthStore` contract (the sqlite store has the plaintext rows an older version wrote). Idempotent: 0.""" return 0
[docs] def sweep(self, now: int) -> int: with self._connection() as conn, conn.transaction(): cur = conn.execute("DELETE FROM fauth_sessions WHERE expires_at < %s", (int(now),)) conn.execute("DELETE FROM fauth_admin_tokens WHERE expires_at < %s", (int(now),)) return int(cur.rowcount or 0)
[docs] def count_active(self, now: int) -> int: with self._connection() as conn: row = conn.execute("SELECT count(*) FROM fauth_sessions WHERE expires_at >= %s", (int(now),)).fetchone() return int(row[0]) if row is not None else 0
[docs] def ping(self) -> bool: try: with self._connection() as conn: conn.execute("SELECT 1 FROM fauth_sessions LIMIT 1").fetchall() return True except Exception as exc: # noqa: BLE001 - any failure means not ready log.warning("fleetmesh-auth postgres store is not answering: %s", exc) return False
# -- replay --
[docs] def issue_challenge(self, challenge: str, expires_at: int) -> None: with self._connection() as conn: conn.execute( """ INSERT INTO fauth_challenges (challenge, expires_at) VALUES (%s, %s) ON CONFLICT (challenge) DO UPDATE SET expires_at = EXCLUDED.expires_at """, (challenge, int(expires_at)), )
[docs] def consume_challenge(self, challenge: str, now: int) -> bool: if not challenge: return False # One DELETE: the row lock makes concurrent consumers serialise and # exactly one sees rows_affected == 1. with self._connection() as conn: cur = conn.execute( "DELETE FROM fauth_challenges WHERE challenge = %s AND expires_at > %s", (challenge, int(now)) ) hit = int(cur.rowcount or 0) == 1 self._maybe_sweep(int(now)) return hit
[docs] def consume_event_id(self, event_id: str, pubkey: str, expires_at: int, now: int) -> bool: if not event_id: return False keep_until = max(int(expires_at), int(now) + USED_EVENT_MIN_RETENTION_SEC) with self._connection() as conn: # Insert wins; an expired held id is taken over; a live one is a # replay and affects zero rows. cur = conn.execute( """ INSERT INTO fauth_used_events (event_id, pubkey, expires_at) VALUES (%s, %s, %s) ON CONFLICT (event_id) DO UPDATE SET pubkey = EXCLUDED.pubkey, expires_at = EXCLUDED.expires_at WHERE fauth_used_events.expires_at <= %s """, (event_id, pubkey, keep_until, int(now)), ) fresh = int(cur.rowcount or 0) == 1 self._maybe_sweep(int(now)) return fresh
[docs] def sweep_replay(self, now: int) -> None: with self._connection() as conn, conn.transaction(): conn.execute("DELETE FROM fauth_challenges WHERE expires_at <= %s", (int(now),)) conn.execute("DELETE FROM fauth_used_events WHERE expires_at <= %s", (int(now),))
# -- passkeys --
[docs] def put_passkey(self, credential_id: str, record: Dict[str, Any]) -> None: with self._connection() as conn: conn.execute( """ INSERT INTO fauth_passkeys (credential_id, pubkey_hex, did, handle, public_key_b64, created_at) VALUES (%s, %s, %s, %s, %s, %s) ON CONFLICT (credential_id) DO UPDATE SET pubkey_hex = EXCLUDED.pubkey_hex, did = EXCLUDED.did, handle = EXCLUDED.handle, public_key_b64 = EXCLUDED.public_key_b64, created_at = EXCLUDED.created_at """, ( credential_id, str(record.get("pubkey_hex", "")), str(record.get("did", "")), str(record.get("handle", "")), str(record.get("public_key_b64", "")), int(record.get("created_at", 0)), ), )
[docs] def get_passkey(self, credential_id: str) -> Optional[Dict[str, Any]]: with self._connection() as conn: row = conn.execute( "SELECT credential_id, pubkey_hex, did, handle, public_key_b64, created_at " "FROM fauth_passkeys WHERE credential_id = %s", (credential_id,), ).fetchone() if row is None: return None return { "credential_id": row[0], "pubkey_hex": row[1], "did": row[2], "handle": row[3], "public_key_b64": row[4], "created_at": int(row[5]), }