Source code for fleetmesh_auth.stores.sqlite

"""`SqliteAuthStore`: the engine's original sqlite persistence behind the
`AuthStore` interface. Same tables and semantics as before the stores
existed (`fleetmesh_auth_sessions`, `fleetmesh_auth_passkeys`,
`fleetmesh_auth_meta`, and the core's `auth_challenges` /
`used_auth_events` DDL), so an existing database file keeps working.

One connection (`check_same_thread=False`) guarded by one RLock, which is
what `:memory:` needs to be usable from the server's threads; `.conn` and
`.lock` are exposed for co-hosted code that shares the database.

Sessions are keyed by sha256(token) and admin tokens by their own sha256, so
the database never holds a bearer credential. A database written by an older
version (plaintext `session_token` column) is migrated in place: the tokens
are hashed where they stand, which keeps those sessions valid, and
`migrate_session_tokens()` is idempotent.
"""
from __future__ import annotations

import json
import logging
import re
import sqlite3
import threading
from typing import Any, Dict, Optional

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

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

_SESSION_COLUMNS = (
    "principal_id", "did", "pubkey_hex", "handle", "display_name",
    "provider", "auth_method", "roles_json", "scopes_json", "metadata_json",
    "issued_at", "expires_at",
)

# A stored key is exactly this; anything else in the column is a plaintext
# token left by an older version (see migrate_session_tokens).
_STORED_KEY_RE = re.compile(r"^[0-9a-f]{64}$")


[docs]class SqliteAuthStore(AuthStore): SCHEMA_SQL = """ CREATE TABLE IF NOT EXISTS fleetmesh_auth_sessions ( session_token TEXT PRIMARY KEY, principal_id TEXT NOT NULL, did TEXT NOT NULL, pubkey_hex TEXT NOT NULL, handle TEXT NOT NULL, display_name TEXT NOT NULL, provider TEXT NOT NULL, auth_method TEXT NOT NULL, roles_json TEXT NOT NULL, scopes_json TEXT NOT NULL, metadata_json TEXT NOT NULL, issued_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS fleetmesh_auth_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 INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS fleetmesh_auth_admin_tokens ( admin_token_hash TEXT PRIMARY KEY, session_token_hash TEXT NOT NULL, expires_at INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS fleetmesh_auth_admin_tokens_expires_at_idx ON fleetmesh_auth_admin_tokens (expires_at); CREATE INDEX IF NOT EXISTS fleetmesh_auth_admin_tokens_session_idx ON fleetmesh_auth_admin_tokens (session_token_hash); CREATE TABLE IF NOT EXISTS fleetmesh_auth_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL); CREATE TABLE IF NOT EXISTS auth_challenges ( challenge TEXT PRIMARY KEY, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS used_auth_events ( event_id TEXT PRIMARY KEY, pubkey TEXT NOT NULL, used_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ); """
[docs] def __init__(self, db_path: Optional[str] = None, *, conn: Optional[sqlite3.Connection] = None, lock: Optional[threading.RLock] = None) -> None: self.db_path = db_path or ":memory:" self.lock = lock if lock is not None else threading.RLock() if conn is not None: self.conn = conn else: self.conn = sqlite3.connect(self.db_path, check_same_thread=False) self.conn.row_factory = sqlite3.Row if self.db_path != ":memory:": with self.lock: self.conn.execute("PRAGMA journal_mode=WAL") self.ensure_schema()
# -- lifecycle --
[docs] def ensure_schema(self) -> None: with self.lock, self.conn: self.conn.executescript(self.SCHEMA_SQL) # Earlier versions kept a ticket-signing key here and signed users' # portable tickets with it, which logged them all in as that key. # Nothing signs with it now; a secret nobody uses is only a risk. self.conn.execute("DELETE FROM fleetmesh_auth_meta WHERE key = 'issuer_sk_hex'") # An older database holds bearer tokens in the clear; hash them where # they are so those sessions survive the upgrade. self.migrate_session_tokens()
[docs] def close(self) -> None: with self.lock: self.conn.close()
[docs] def clear(self) -> None: self.clear_sessions() self.clear_replay() with self.lock, self.conn: self.conn.execute("DELETE FROM fleetmesh_auth_passkeys")
[docs] def clear_sessions(self) -> None: with self.lock, self.conn: self.conn.execute("DELETE FROM fleetmesh_auth_sessions") self.conn.execute("DELETE FROM fleetmesh_auth_admin_tokens")
[docs] def clear_replay(self) -> None: with self.lock, self.conn: self.conn.execute("DELETE FROM auth_challenges") self.conn.execute("DELETE FROM used_auth_events")
# -- sessions --
[docs] def put(self, token: str, record: SessionRecord, expires_at: int) -> None: with self.lock, self.conn: self.conn.execute( f""" INSERT OR REPLACE INTO fleetmesh_auth_sessions (session_token, {", ".join(_SESSION_COLUMNS)}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( session_token_key(token), str(record.get("principal_id", "")), str(record.get("did", "")), str(record.get("pubkey_hex", "")), str(record.get("handle", "")), str(record.get("display_name", "")), str(record.get("provider", "")), str(record.get("auth_method", "")), json.dumps(record.get("roles") or []), json.dumps(record.get("scopes") or []), json.dumps(record.get("metadata") or {}), int(record.get("issued_at", 0)), int(expires_at), ), )
@staticmethod def _row_to_record(row: sqlite3.Row) -> SessionRecord: return { "principal_id": row["principal_id"], "did": row["did"], "pubkey_hex": row["pubkey_hex"], "handle": row["handle"], "display_name": row["display_name"], "provider": row["provider"], "auth_method": row["auth_method"], "roles": json.loads(row["roles_json"] or "[]"), "scopes": json.loads(row["scopes_json"] or "[]"), "metadata": json.loads(row["metadata_json"] or "{}"), "issued_at": int(row["issued_at"]), "expires_at": int(row["expires_at"]), } def _select_by_key(self, session_key: str) -> Optional[sqlite3.Row]: return self.conn.execute( "SELECT * FROM fleetmesh_auth_sessions WHERE session_token = ? LIMIT 1", (session_key,) ).fetchone() def _adopt_legacy_row(self, token: str) -> Optional[sqlite3.Row]: """A row keyed by the plaintext `token` (an older version's write): hash it in place and return it, so that session keeps working even if the startup migration could not run first.""" raw = str(token or "") if not raw or _STORED_KEY_RE.fullmatch(raw): return None row = self.conn.execute( "SELECT * FROM fleetmesh_auth_sessions WHERE session_token = ? LIMIT 1", (raw,) ).fetchone() if row is None: return None key = session_token_key(raw) if self._select_by_key(key) is None: self.conn.execute( "UPDATE fleetmesh_auth_sessions SET session_token = ? WHERE session_token = ?", (key, raw) ) else: self.conn.execute("DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?", (raw,)) return self._select_by_key(key) or row def _record_for_row(self, row: Optional[sqlite3.Row], session_key: str, now: int, include_expired: bool) -> Optional[SessionRecord]: if row is None: return None if int(row["expires_at"]) < int(now): if include_expired: return self._row_to_record(row) self.conn.execute("DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?", (session_key,)) return None return self._row_to_record(row)
[docs] def get(self, token: str, now: int, *, include_expired: bool = False) -> Optional[SessionRecord]: key = session_token_key(token) with self.lock, self.conn: row = self._select_by_key(key) or self._adopt_legacy_row(token) return self._record_for_row(row, key, now, include_expired)
[docs] def get_session_by_key(self, session_key: str, now: int, *, include_expired: bool = False) -> Optional[SessionRecord]: with self.lock, self.conn: return self._record_for_row(self._select_by_key(session_key), session_key, now, include_expired)
[docs] def delete(self, token: str) -> None: raw = str(token or "") key = session_token_key(raw) with self.lock, self.conn: self.conn.execute("DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?", (key,)) self.conn.execute("DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?", (raw,)) self.conn.execute("DELETE FROM fleetmesh_auth_admin_tokens WHERE admin_token_hash = ?", (key,)) self._delete_admin_tokens_for_session(key)
[docs] def delete_session_by_key(self, session_key: str) -> None: with self.lock, self.conn: self.conn.execute("DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?", (session_key,)) self._delete_admin_tokens_for_session(session_key)
def _delete_admin_tokens_for_session(self, session_key: str) -> None: self.conn.execute( "DELETE FROM fleetmesh_auth_admin_tokens WHERE session_token_hash = ?", (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.lock, self.conn: self.conn.execute( "INSERT OR REPLACE INTO fleetmesh_auth_admin_tokens " "(admin_token_hash, session_token_hash, expires_at) VALUES (?, ?, ?)", (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.lock, self.conn: row = self.conn.execute( "SELECT session_token_hash, expires_at FROM fleetmesh_auth_admin_tokens " "WHERE admin_token_hash = ? LIMIT 1", (key,), ).fetchone() if row is None: return None if int(row["expires_at"]) < int(now): self.conn.execute("DELETE FROM fleetmesh_auth_admin_tokens WHERE admin_token_hash = ?", (key,)) return None return str(row["session_token_hash"])
[docs] def delete_admin_token(self, admin_token: str) -> None: with self.lock, self.conn: self.conn.execute( "DELETE FROM fleetmesh_auth_admin_tokens WHERE admin_token_hash = ?", (session_token_key(admin_token),), )
# -- migration of an older database's plaintext tokens --
[docs] def migrate_session_tokens(self) -> int: """Hash every plaintext session token in place; returns the rows rewritten. Idempotent: a hashed row is skipped, so a second run (or a run on a fresh database) returns 0 and changes nothing.""" with self.lock, self.conn: raw_rows = [ str(r[0]) for r in self.conn.execute("SELECT session_token FROM fleetmesh_auth_sessions").fetchall() ] migrated = 0 for raw in raw_rows: if not raw or _STORED_KEY_RE.fullmatch(raw): continue key = session_token_key(raw) if self._select_by_key(key) is None: self.conn.execute( "UPDATE fleetmesh_auth_sessions SET session_token = ? WHERE session_token = ?", (key, raw), ) else: # A row for that token was already hashed (a partial run). self.conn.execute("DELETE FROM fleetmesh_auth_sessions WHERE session_token = ?", (raw,)) migrated += 1 if migrated: log.info("fleetmesh-auth sqlite: hashed %d plaintext session token(s) in place", migrated) return migrated
[docs] def sweep(self, now: int) -> int: with self.lock, self.conn: cur = self.conn.execute("DELETE FROM fleetmesh_auth_sessions WHERE expires_at < ?", (int(now),)) self.conn.execute("DELETE FROM fleetmesh_auth_admin_tokens WHERE expires_at < ?", (int(now),)) return int(cur.rowcount or 0)
[docs] def count_active(self, now: int) -> int: with self.lock: row = self.conn.execute( "SELECT COUNT(*) FROM fleetmesh_auth_sessions WHERE expires_at >= ?", (int(now),) ).fetchone() return int(row[0]) if row is not None else 0
[docs] def ping(self) -> bool: try: with self.lock: self.conn.execute("SELECT 1 FROM fleetmesh_auth_sessions LIMIT 1").fetchall() return True except Exception as exc: # noqa: BLE001 - any failure means not ready log.warning("fleetmesh-auth sqlite store is not answering: %s", exc) return False
# -- replay (the core's semantics, verbatim) --
[docs] def issue_challenge(self, challenge: str, expires_at: int) -> None: with self.lock, self.conn: self.conn.execute( "INSERT OR REPLACE INTO auth_challenges (challenge, created_at, expires_at) VALUES (?, ?, ?)", (challenge, int(expires_at), int(expires_at)), )
[docs] def consume_challenge(self, challenge: str, now: int) -> bool: if not challenge: return False with self.lock, self.conn: self.conn.execute("DELETE FROM auth_challenges WHERE expires_at <= ?", (int(now),)) cur = self.conn.execute( "DELETE FROM auth_challenges WHERE challenge = ? AND expires_at > ?", (challenge, int(now)) ) return int(cur.rowcount or 0) == 1
[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.lock, self.conn: self.conn.execute("DELETE FROM used_auth_events WHERE expires_at <= ?", (int(now),)) cur = self.conn.execute( "INSERT OR IGNORE INTO used_auth_events (event_id, pubkey, used_at, expires_at) VALUES (?, ?, ?, ?)", (event_id, pubkey, int(now), keep_until), ) return int(cur.rowcount or 0) == 1
[docs] def sweep_replay(self, now: int) -> None: with self.lock, self.conn: self.conn.execute("DELETE FROM auth_challenges WHERE expires_at <= ?", (int(now),)) self.conn.execute("DELETE FROM used_auth_events WHERE expires_at <= ?", (int(now),))
# -- passkeys --
[docs] def put_passkey(self, credential_id: str, record: Dict[str, Any]) -> None: with self.lock, self.conn: self.conn.execute( """ INSERT OR REPLACE INTO fleetmesh_auth_passkeys ( credential_id, pubkey_hex, did, handle, public_key_b64, created_at ) VALUES (?, ?, ?, ?, ?, ?) """, ( 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.lock: row = self.conn.execute( "SELECT * FROM fleetmesh_auth_passkeys WHERE credential_id = ? LIMIT 1", (credential_id,) ).fetchone() return dict(row) if row is not None else None