Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

feat(auth): add WebSocket ticket data plane

Mafifrizi886f11b290de
diff --git a/ares/db/database.py b/ares/db/database.py
index 8fe47ed..6d61ea5 100644
--- a/ares/db/database.py
+++ b/ares/db/database.py
@@ -6,16 +6,33 @@ from __future__ import annotations
import asyncio
import json
+import re
import secrets
import uuid
+from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import datetime, timezone, timedelta
from pathlib import Path
-from typing import Any, Awaitable
+from typing import Any, Awaitable, TypeVar
from urllib.parse import unquote
import aiosqlite
from ares.core.logger import get_logger
+from ares.db.websocket_tickets import (
+ ApiKeyTicketSource,
+ BearerTicketSource,
+ ConsumedWebSocketTicket,
+ WebSocketTicketCredentialKind,
+ WebSocketTicketPrincipal,
+ WEBSOCKET_TICKET_TTL_SECONDS,
+ format_sqlite_utc,
+ generate_websocket_ticket,
+ hash_websocket_ticket,
+ is_canonical_websocket_ticket,
+ is_valid_websocket_principal_role,
+ normalize_api_key_scopes,
+ parse_sqlite_utc,
+)
logger = get_logger("ares.db")
@@ -23,6 +40,324 @@ from ares.core.campaign import Campaign, Finding
from ares.core.security import DataEncryptor, hash_password, verify_password
from ares.db.schema import CREATE_TABLES, SCHEMA_VERSION
+_TicketResultT = TypeVar("_TicketResultT")
+
+_WEBSOCKET_TICKET_COLUMNS = (
+ (0, "ticket_hash", "TEXT", 1, None, 1, 0),
+ (1, "campaign_id", "TEXT", 1, None, 0, 0),
+ (2, "user_id", "TEXT", 1, None, 0, 0),
+ (3, "credential_kind", "TEXT", 1, None, 0, 0),
+ (4, "bearer_subject", "TEXT", 0, None, 0, 0),
+ (5, "bearer_jti", "TEXT", 0, None, 0, 0),
+ (6, "bearer_expires_at", "TEXT", 0, None, 0, 0),
+ (7, "api_key_id", "TEXT", 0, None, 0, 0),
+ (8, "required_scope", "TEXT", 0, None, 0, 0),
+ (9, "created_at", "TEXT", 1, None, 0, 0),
+ (10, "expires_at", "TEXT", 1, None, 0, 0),
+ (11, "consumed_at", "TEXT", 0, None, 0, 0),
+)
+_WEBSOCKET_TICKET_FOREIGN_KEYS = (
+ (0, "api_key_id", "api_keys", "id", "NO ACTION", "CASCADE", "NONE"),
+ (0, "campaign_id", "campaigns", "id", "NO ACTION", "CASCADE", "NONE"),
+ (0, "user_id", "users", "id", "NO ACTION", "CASCADE", "NONE"),
+)
+_WEBSOCKET_TICKET_CHECKS = {
+ "ck_ws_ticket_hash": """
+ length(ticket_hash)=64
+ AND ticket_hash NOT GLOB '*[^0-9a-f]*'
+ """,
+ "ck_ws_ticket_kind": """
+ credential_kind IN ('bearer', 'api_key')
+ """,
+ "ck_ws_ticket_created_at": """
+ strftime('%Y-%m-%dT%H:%M:%fZ', created_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ', created_at)=created_at
+ """,
+ "ck_ws_ticket_expires_at": """
+ strftime('%Y-%m-%dT%H:%M:%fZ', expires_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ', expires_at)=expires_at
+ """,
+ "ck_ws_ticket_consumed_at": """
+ consumed_at IS NULL OR (
+ strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at)=consumed_at
+ )
+ """,
+ "ck_ws_ticket_time_order": """
+ julianday(expires_at) > julianday(created_at)
+ AND (
+ consumed_at IS NULL
+ OR julianday(consumed_at) < julianday(expires_at)
+ )
+ """,
+ "ck_ws_ticket_source_shape": """
+ (
+ credential_kind='bearer'
+ AND bearer_subject IS NOT NULL
+ AND length(trim(bearer_subject)) > 0
+ AND bearer_subject=trim(bearer_subject)
+ AND bearer_jti IS NOT NULL
+ AND length(trim(bearer_jti)) > 0
+ AND bearer_jti=trim(bearer_jti)
+ AND bearer_expires_at IS NOT NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
+ ) IS NOT NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
+ )=bearer_expires_at
+ AND api_key_id IS NULL
+ AND required_scope IS NULL
+ )
+ OR
+ (
+ credential_kind='api_key'
+ AND bearer_subject IS NULL
+ AND bearer_jti IS NULL
+ AND bearer_expires_at IS NULL
+ AND api_key_id IS NOT NULL
+ AND length(trim(api_key_id)) > 0
+ AND api_key_id=trim(api_key_id)
+ AND required_scope='read'
+ )
+ """,
+}
+_WEBSOCKET_TICKET_FOREIGN_KEY_NAMES = {
+ "fk_ws_ticket_campaign",
+ "fk_ws_ticket_user",
+ "fk_ws_ticket_api_key",
+}
+_WEBSOCKET_TICKET_NAMED_FOREIGN_KEYS = {
+ "fk_ws_ticket_campaign": (
+ "campaign_id",
+ "campaigns",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ ),
+ "fk_ws_ticket_user": (
+ "user_id",
+ "users",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ ),
+ "fk_ws_ticket_api_key": (
+ "api_key_id",
+ "api_keys",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ ),
+}
+
+
+def _normalize_sql_fragment(fragment: str) -> str:
+ """Normalize formatting while preserving quoted SQL literal contents."""
+ normalized: list[str] = []
+ quote: str | None = None
+ index = 0
+ while index < len(fragment):
+ character = fragment[index]
+ if quote is not None:
+ normalized.append(character)
+ if character == quote:
+ if index + 1 < len(fragment) and fragment[index + 1] == quote:
+ normalized.append(fragment[index + 1])
+ index += 1
+ else:
+ quote = None
+ elif character in ("'", '"', "`"):
+ quote = character
+ normalized.append(character)
+ elif character == "[":
+ quote = "]"
+ normalized.append(character)
+ elif not character.isspace():
+ normalized.append(character.lower())
+ index += 1
+ return "".join(normalized)
+
+
+def _extract_named_checks(table_sql: str) -> tuple[dict[str, str], int]:
+ pattern = re.compile(
+ r"""\bconstraint\s+
+ (?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))
+ \s+check\s*\(
+ """,
+ re.IGNORECASE | re.VERBOSE,
+ )
+ checks: dict[str, str] = {}
+ check_count = len(re.findall(r"\bcheck\s*\(", table_sql, re.IGNORECASE))
+ for match in pattern.finditer(table_sql):
+ name = next(group for group in match.groups() if group is not None)
+ depth = 1
+ quote: str | None = None
+ index = match.end()
+ expression_start = index
+ while index < len(table_sql):
+ character = table_sql[index]
+ if quote is not None:
+ if character == quote:
+ if (
+ index + 1 < len(table_sql)
+ and table_sql[index + 1] == quote
+ ):
+ index += 1
+ else:
+ quote = None
+ elif character in ("'", '"', "`"):
+ quote = character
+ elif character == "[":
+ quote = "]"
+ elif character == "(":
+ depth += 1
+ elif character == ")":
+ depth -= 1
+ if depth == 0:
+ break
+ index += 1
+ if depth != 0 or name in checks:
+ return {}, check_count
+ checks[name] = _normalize_sql_fragment(
+ table_sql[expression_start:index]
+ )
+ return checks, check_count
+
+
+def _extract_named_constraints(table_sql: str) -> tuple[str, ...]:
+ pattern = re.compile(
+ r"""\bconstraint\s+
+ (?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|([A-Za-z_][A-Za-z0-9_]*))
+ """,
+ re.IGNORECASE | re.VERBOSE,
+ )
+ return tuple(
+ next(group for group in match.groups() if group is not None)
+ for match in pattern.finditer(table_sql)
+ )
+
+
+def _split_sql_list(body: str) -> tuple[str, ...]:
+ parts: list[str] = []
+ start = 0
+ depth = 0
+ quote: str | None = None
+ index = 0
+ while index < len(body):
+ character = body[index]
+ if quote is not None:
+ if character == quote:
+ if index + 1 < len(body) and body[index + 1] == quote:
+ index += 1
+ else:
+ quote = None
+ elif character in ("'", '"', "`"):
+ quote = character
+ elif character == "[":
+ quote = "]"
+ elif character == "(":
+ depth += 1
+ elif character == ")":
+ depth -= 1
+ elif character == "," and depth == 0:
+ parts.append(body[start:index])
+ start = index + 1
+ index += 1
+ parts.append(body[start:])
+ return tuple(parts)
+
+
+def _foreign_key_action(fragment: str, action: str) -> str:
+ match = re.search(
+ rf"on{action}(noaction|restrict|cascade|setnull|setdefault)",
+ fragment,
+ )
+ if match is None:
+ return "NO ACTION"
+ return {
+ "noaction": "NO ACTION",
+ "restrict": "RESTRICT",
+ "cascade": "CASCADE",
+ "setnull": "SET NULL",
+ "setdefault": "SET DEFAULT",
+ }[match.group(1)]
+
+
+def _extract_named_foreign_keys(
+ table_sql: str,
+) -> dict[str, tuple[str, str, str, str, str]]:
+ opening = table_sql.find("(")
+ closing = table_sql.rfind(")")
+ if opening < 0 or closing <= opening:
+ return {}
+ foreign_keys: dict[str, tuple[str, str, str, str, str]] = {}
+ for raw_fragment in _split_sql_list(table_sql[opening + 1:closing]):
+ fragment = _normalize_sql_fragment(raw_fragment)
+ fragment = (
+ fragment.replace('"', "")
+ .replace("`", "")
+ .replace("[", "")
+ .replace("]", "")
+ )
+ name_match = re.search(
+ r"""\bconstraint\s+
+ (?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|
+ ([A-Za-z_][A-Za-z0-9_]*))
+ """,
+ raw_fragment,
+ re.IGNORECASE | re.VERBOSE,
+ )
+ if name_match is None:
+ continue
+ name = next(
+ group
+ for group in name_match.groups()
+ if group is not None
+ ).lower()
+ if name not in _WEBSOCKET_TICKET_FOREIGN_KEY_NAMES:
+ continue
+ table_level = re.search(
+ r"foreignkey\(([a-z_][a-z0-9_]*)\)"
+ r"references([a-z_][a-z0-9_]*)"
+ r"\(([a-z_][a-z0-9_]*)\)",
+ fragment,
+ )
+ if table_level is not None:
+ local_column, target_table, target_column = table_level.groups()
+ else:
+ local_match = re.match(
+ r"""\s*
+ (?:"([^"]+)"|`([^`]+)`|\[([^\]]+)\]|
+ ([A-Za-z_][A-Za-z0-9_]*))
+ """,
+ raw_fragment,
+ re.VERBOSE,
+ )
+ reference_match = re.search(
+ r"references([a-z_][a-z0-9_]*)"
+ r"\(([a-z_][a-z0-9_]*)\)",
+ fragment,
+ )
+ if local_match is None or reference_match is None:
+ return {}
+ local_column = next(
+ group
+ for group in local_match.groups()
+ if group is not None
+ ).lower()
+ target_table, target_column = reference_match.groups()
+ if name in foreign_keys:
+ return {}
+ foreign_keys[name] = (
+ local_column,
+ target_table,
+ target_column,
+ _foreign_key_action(fragment, "update"),
+ _foreign_key_action(fragment, "delete"),
+ )
+ return foreign_keys
+
async def _await_task_completion(
task: asyncio.Future[Any],
@@ -358,11 +693,34 @@ class AresDatabase:
return await db.connect()
async def _init_schema(self) -> None:
+ async with self._conn.execute(
+ "SELECT 1 FROM sqlite_master "
+ "WHERE type='table' AND name='websocket_tickets'"
+ ) as cursor:
+ ticket_table_exists = await cursor.fetchone() is not None
+ if ticket_table_exists:
+ await self._validate_websocket_ticket_schema()
+
alembic_applied = await self._run_alembic_migrations()
if not alembic_applied:
- await self._conn.executescript(CREATE_TABLES)
- await self._conn.commit()
+ schema_body_marker = "PRAGMA foreign_keys = ON;"
+ if CREATE_TABLES.count(schema_body_marker) != 1:
+ raise RuntimeError("SQLite schema bootstrap is unavailable")
+ schema_body = CREATE_TABLES.split(
+ schema_body_marker,
+ maxsplit=1,
+ )[1]
+ try:
+ await self._conn.executescript(
+ f"BEGIN IMMEDIATE;\n{schema_body}"
+ )
+ await self._validate_websocket_ticket_schema()
+ await self._conn.commit()
+ except BaseException:
+ await self._conn.rollback()
+ raise
await self._reconcile_sqlite_schema()
+ await self._validate_websocket_ticket_schema()
logger.info(
"db_ready",
database=self._database_label,
@@ -411,11 +769,300 @@ class AresDatabase:
)
await self._conn.commit()
+ async def _validate_websocket_ticket_schema(self) -> None:
+ """Reject a partially present ticket table instead of using it silently."""
+ connection = self._conn
+ if connection is None:
+ raise RuntimeError("Database not connected")
+
+ async with connection.execute(
+ "PRAGMA index_list(websocket_tickets)"
+ ) as cursor:
+ index_rows = await cursor.fetchall()
+ primary_index_rows = tuple(
+ row
+ for row in index_rows
+ if str(row["origin"]).lower() == "pk"
+ )
+ if len(primary_index_rows) != 1:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ primary_index_row = primary_index_rows[0]
+ if (
+ int(primary_index_row["unique"]) != 1
+ or int(primary_index_row["partial"]) != 0
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ primary_index_name = str(primary_index_row["name"])
+ if not primary_index_name:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ async with connection.execute(
+ """
+ SELECT type, name, tbl_name, sql
+ FROM sqlite_schema
+ WHERE tbl_name='websocket_tickets'
+ ORDER BY type, name
+ """
+ ) as cursor:
+ attached_objects = await cursor.fetchall()
+ expected_index_definitions = {
+ "idx_ws_tickets_api_key": frozenset(
+ {
+ "createindexidx_ws_tickets_api_key"
+ "onwebsocket_tickets(api_key_id)",
+ "createindexifnotexistsidx_ws_tickets_api_key"
+ "onwebsocket_tickets(api_key_id)",
+ }
+ ),
+ "idx_ws_tickets_campaign": frozenset(
+ {
+ "createindexidx_ws_tickets_campaign"
+ "onwebsocket_tickets(campaign_id)",
+ "createindexifnotexistsidx_ws_tickets_campaign"
+ "onwebsocket_tickets(campaign_id)",
+ }
+ ),
+ "idx_ws_tickets_expires": frozenset(
+ {
+ "createindexidx_ws_tickets_expires"
+ "onwebsocket_tickets(expires_at)",
+ "createindexifnotexistsidx_ws_tickets_expires"
+ "onwebsocket_tickets(expires_at)",
+ }
+ ),
+ "idx_ws_tickets_user": frozenset(
+ {
+ "createindexidx_ws_tickets_user"
+ "onwebsocket_tickets(user_id)",
+ "createindexifnotexistsidx_ws_tickets_user"
+ "onwebsocket_tickets(user_id)",
+ }
+ ),
+ }
+ if primary_index_name in expected_index_definitions:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ if len(attached_objects) != len(expected_index_definitions) + 2:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ table_count = 0
+ primary_index_count = 0
+ explicit_index_names: set[str] = set()
+ for row in attached_objects:
+ object_type = str(row["type"])
+ object_name = str(row["name"])
+ table_name = str(row["tbl_name"])
+ definition = row["sql"]
+ if (
+ object_type == "table"
+ and object_name == "websocket_tickets"
+ and table_name == "websocket_tickets"
+ and definition is not None
+ ):
+ table_count += 1
+ elif (
+ object_type == "index"
+ and object_name == primary_index_name
+ and table_name == "websocket_tickets"
+ and definition is None
+ ):
+ primary_index_count += 1
+ elif (
+ object_type == "index"
+ and object_name in expected_index_definitions
+ and table_name == "websocket_tickets"
+ and definition is not None
+ and _normalize_sql_fragment(str(definition))
+ in expected_index_definitions[object_name]
+ ):
+ explicit_index_names.add(object_name)
+ else:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ if (
+ table_count != 1
+ or primary_index_count != 1
+ or explicit_index_names != set(expected_index_definitions)
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ async with connection.execute(
+ "PRAGMA table_xinfo(websocket_tickets)"
+ ) as cursor:
+ columns = await cursor.fetchall()
+ actual_columns = tuple(
+ (
+ int(row["cid"]),
+ str(row["name"]),
+ str(row["type"]).upper(),
+ int(row["notnull"]),
+ row["dflt_value"],
+ int(row["pk"]),
+ int(row["hidden"]),
+ )
+ for row in columns
+ )
+ if actual_columns != _WEBSOCKET_TICKET_COLUMNS:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ async with connection.execute(
+ "PRAGMA foreign_key_list(websocket_tickets)"
+ ) as cursor:
+ foreign_keys = tuple(
+ sorted(
+ (
+ int(row["seq"]),
+ str(row["from"]),
+ str(row["table"]),
+ str(row["to"]),
+ str(row["on_update"]).upper(),
+ str(row["on_delete"]).upper(),
+ str(row["match"]).upper(),
+ )
+ for row in await cursor.fetchall()
+ )
+ )
+ if foreign_keys != _WEBSOCKET_TICKET_FOREIGN_KEYS:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ actual_indexes: dict[
+ str,
+ tuple[int, str, int, tuple[tuple[Any, ...], ...]],
+ ] = {}
+ for row in index_rows:
+ index_name = str(row["name"])
+ quoted_name = index_name.replace('"', '""')
+ async with connection.execute(
+ f'PRAGMA index_xinfo("{quoted_name}")'
+ ) as cursor:
+ index_columns = tuple(
+ (
+ int(index_row["seqno"]),
+ int(index_row["cid"]),
+ index_row["name"],
+ int(index_row["desc"]),
+ str(index_row["coll"]).upper(),
+ int(index_row["key"]),
+ )
+ for index_row in await cursor.fetchall()
+ )
+ actual_indexes[index_name] = (
+ int(row["unique"]),
+ str(row["origin"]).lower(),
+ int(row["partial"]),
+ index_columns,
+ )
+ if len(actual_indexes) != len(index_rows):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ primary_index = actual_indexes.pop(primary_index_name, None)
+ expected_primary_index = (
+ 1,
+ "pk",
+ 0,
+ (
+ (0, 0, "ticket_hash", 0, "BINARY", 1),
+ (1, -1, None, 0, "BINARY", 0),
+ ),
+ )
+ expected_indexes = {
+ "idx_ws_tickets_expires": (
+ 0,
+ "c",
+ 0,
+ (
+ (0, 10, "expires_at", 0, "BINARY", 1),
+ (1, -1, None, 0, "BINARY", 0),
+ ),
+ ),
+ "idx_ws_tickets_user": (
+ 0,
+ "c",
+ 0,
+ (
+ (0, 2, "user_id", 0, "BINARY", 1),
+ (1, -1, None, 0, "BINARY", 0),
+ ),
+ ),
+ "idx_ws_tickets_campaign": (
+ 0,
+ "c",
+ 0,
+ (
+ (0, 1, "campaign_id", 0, "BINARY", 1),
+ (1, -1, None, 0, "BINARY", 0),
+ ),
+ ),
+ "idx_ws_tickets_api_key": (
+ 0,
+ "c",
+ 0,
+ (
+ (0, 7, "api_key_id", 0, "BINARY", 1),
+ (1, -1, None, 0, "BINARY", 0),
+ ),
+ ),
+ }
+ if (
+ primary_index != expected_primary_index
+ or actual_indexes != expected_indexes
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ async with connection.execute(
+ "SELECT sql FROM sqlite_master "
+ "WHERE type='table' AND name='websocket_tickets'"
+ ) as cursor:
+ table_row = await cursor.fetchone()
+ table_sql = str(table_row["sql"] if table_row else "")
+ normalized_table_sql = _normalize_sql_fragment(table_sql)
+ if (
+ not normalized_table_sql.startswith(
+ "createtablewebsocket_tickets("
+ )
+ and not normalized_table_sql.startswith(
+ "createtableifnotexistswebsocket_tickets("
+ )
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ if (
+ "withoutrowid" in normalized_table_sql
+ or "strict" in normalized_table_sql
+ or "collate" in normalized_table_sql
+ or "onconflict" in normalized_table_sql
+ or "deferrable" in normalized_table_sql
+ or "initiallydeferred" in normalized_table_sql
+ or "initiallyimmediate" in normalized_table_sql
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ named_checks, check_count = _extract_named_checks(table_sql)
+ expected_checks = {
+ name: _normalize_sql_fragment(expression)
+ for name, expression in _WEBSOCKET_TICKET_CHECKS.items()
+ }
+ if named_checks != expected_checks or check_count != len(
+ expected_checks
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ expected_constraint_names = tuple(
+ sorted(
+ set(expected_checks)
+ | _WEBSOCKET_TICKET_FOREIGN_KEY_NAMES
+ )
+ )
+ if tuple(sorted(_extract_named_constraints(table_sql))) != (
+ expected_constraint_names
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ if (
+ _extract_named_foreign_keys(table_sql)
+ != _WEBSOCKET_TICKET_NAMED_FOREIGN_KEYS
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
async def _run_alembic_migrations(self) -> bool:
if self._is_sqlite_uri:
logger.debug(
"alembic_skipped_for_sqlite_uri",
- database=self._database_label,
)
return False
@@ -1199,6 +1846,494 @@ class AresDatabase:
await self._conn.commit()
return changed > 0
+ async def _open_websocket_ticket_connection(self) -> aiosqlite.Connection:
+ return await aiosqlite.connect(
+ self._db_path,
+ uri=self._is_sqlite_uri,
+ timeout=30.0,
+ )
+
+ async def _commit_websocket_ticket_operation(
+ self,
+ connection: aiosqlite.Connection,
+ ) -> None:
+ await connection.commit()
+
+ async def _finish_websocket_ticket_cleanup(
+ self,
+ operation: Awaitable[Any],
+ action: str,
+ *,
+ cancellation_baseline: int,
+ caught_cancellations: list[int],
+ ) -> None:
+ cleanup_task = asyncio.ensure_future(operation)
+ self._name_owned_task(
+ cleanup_task,
+ f"ares-sqlite-websocket-ticket-{action}",
+ )
+ try:
+ await _await_task_completion(
+ cleanup_task,
+ cancellation_baseline=cancellation_baseline,
+ caught_cancellations=caught_cancellations,
+ )
+ except asyncio.CancelledError:
+ raise
+ except Exception as cleanup_error:
+ logger.warning(
+ "websocket_ticket_cleanup_failed",
+ action=action,
+ error_type=type(cleanup_error).__name__,
+ )
+
+ async def _run_websocket_ticket_transaction(
+ self,
+ operation: Callable[
+ [aiosqlite.Connection],
+ Awaitable[_TicketResultT],
+ ],
+ ) -> _TicketResultT:
+ async with self._lifecycle_lock:
+ self._require_connected()
+ connection: aiosqlite.Connection | None = None
+ transaction_started = False
+ commit_started = False
+ committed = False
+ commit_cancellation_baseline = 0
+ commit_cancellations = [0]
+ noncommit_close_cancellations = [0]
+ try:
+ open_cancellation_baseline = _cancel_count()
+ open_cancellations = [0]
+ open_task = asyncio.ensure_future(
+ self._open_websocket_ticket_connection()
+ )
+ self._name_owned_task(
+ open_task,
+ "ares-sqlite-websocket-ticket-connect",
+ )
+ connection = await _await_task_completion(
+ open_task,
+ cancellation_baseline=open_cancellation_baseline,
+ caught_cancellations=open_cancellations,
+ )
+ if open_cancellations[0]:
+ await self._finish_websocket_ticket_cleanup(
+ connection.close(),
+ "cancelled-connect-close",
+ cancellation_baseline=open_cancellation_baseline,
+ caught_cancellations=open_cancellations,
+ )
+ connection = None
+ raise asyncio.CancelledError
+
+ connection.row_factory = aiosqlite.Row
+ await connection.execute("PRAGMA foreign_keys = ON")
+ await connection.execute("BEGIN IMMEDIATE")
+ transaction_started = True
+ result = await operation(connection)
+
+ commit_started = True
+ commit_cancellation_baseline = _cancel_count()
+ commit_task = asyncio.create_task(
+ self._commit_websocket_ticket_operation(connection),
+ name="ares-sqlite-websocket-ticket-commit",
+ )
+ await _await_task_completion(
+ commit_task,
+ cancellation_baseline=commit_cancellation_baseline,
+ caught_cancellations=commit_cancellations,
+ )
+ committed = True
+ transaction_started = False
+ except BaseException:
+ if (
+ connection is not None
+ and transaction_started
+ and not committed
+ ):
+ cleanup_cancellation_baseline = _cancel_count()
+ cleanup_cancellations = [0]
+ cleanup_action = (
+ "rollback-after-commit-failure"
+ if commit_started
+ else "rollback-before-commit"
+ )
+ await self._finish_websocket_ticket_cleanup(
+ connection.rollback(),
+ cleanup_action,
+ cancellation_baseline=cleanup_cancellation_baseline,
+ caught_cancellations=cleanup_cancellations,
+ )
+ raise
+ finally:
+ if connection is not None:
+ close_cancellation_baseline = (
+ commit_cancellation_baseline
+ if committed
+ else _cancel_count()
+ )
+ close_cancellations = (
+ commit_cancellations
+ if committed
+ else noncommit_close_cancellations
+ )
+ await self._finish_websocket_ticket_cleanup(
+ connection.close(),
+ "close",
+ cancellation_baseline=close_cancellation_baseline,
+ caught_cancellations=close_cancellations,
+ )
+
+ if committed:
+ _remove_suppressed_cancellations(
+ cancellation_baseline=commit_cancellation_baseline,
+ caught_cancellations=commit_cancellations[0],
+ )
+ elif noncommit_close_cancellations[0]:
+ raise asyncio.CancelledError
+ return result
+
+ @staticmethod
+ async def _purge_websocket_ticket_rows(
+ connection: aiosqlite.Connection,
+ ) -> int:
+ async with connection.execute(
+ "DELETE FROM websocket_tickets "
+ "WHERE expires_at <= strftime('%Y-%m-%dT%H:%M:%fZ', 'now')"
+ ) as cursor:
+ canonical_count = max(0, cursor.rowcount)
+ async with connection.execute(
+ """DELETE FROM websocket_tickets
+ WHERE strftime(
+ '%Y-%m-%dT%H:%M:%fZ', expires_at
+ ) IS NULL
+ OR strftime(
+ '%Y-%m-%dT%H:%M:%fZ', expires_at
+ ) != expires_at"""
+ ) as cursor:
+ malformed_count = max(0, cursor.rowcount)
+ return canonical_count + malformed_count
+
+ async def issue_websocket_ticket(
+ self,
+ campaign_id: str,
+ source: BearerTicketSource | ApiKeyTicketSource,
+ ) -> tuple[str, int] | None:
+ raw_ticket = generate_websocket_ticket()
+ ticket_hash = hash_websocket_ticket(raw_ticket)
+
+ async def _issue(
+ connection: aiosqlite.Connection,
+ ) -> tuple[str, int] | None:
+ await self._purge_websocket_ticket_rows(connection)
+ if isinstance(source, BearerTicketSource):
+ source_expiry = format_sqlite_utc(source.expires_at)
+ async with connection.execute(
+ """
+ INSERT INTO websocket_tickets (
+ ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope, created_at, expires_at,
+ consumed_at
+ )
+ SELECT ?, c.id, u.id, 'bearer', u.username, ?, ?,
+ NULL, NULL,
+ strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),
+ strftime(
+ '%Y-%m-%dT%H:%M:%fZ',
+ 'now',
+ '+30 seconds'
+ ),
+ NULL
+ FROM users AS u
+ JOIN campaigns AS c ON c.id=?
+ WHERE u.id=?
+ AND u.username=?
+ AND u.is_active=1
+ AND u.role IN (
+ 'team_lead', 'operator', 'recon', 'reporter'
+ )
+ AND julianday(?) > julianday('now')
+ AND NOT EXISTS (
+ SELECT 1
+ FROM revoked_access_tokens AS rat
+ WHERE rat.jti=?
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ """,
+ (
+ ticket_hash,
+ source.jti,
+ source_expiry,
+ campaign_id,
+ source.user_id,
+ source.subject,
+ source_expiry,
+ source.jti,
+ ),
+ ) as cursor:
+ changed = cursor.rowcount
+ elif isinstance(source, ApiKeyTicketSource):
+ async with connection.execute(
+ """
+ INSERT INTO websocket_tickets (
+ ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope, created_at, expires_at,
+ consumed_at
+ )
+ SELECT ?, c.id, u.id, 'api_key', NULL, NULL, NULL,
+ ak.id, 'read',
+ strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),
+ strftime(
+ '%Y-%m-%dT%H:%M:%fZ',
+ 'now',
+ '+30 seconds'
+ ),
+ NULL
+ FROM api_keys AS ak
+ JOIN users AS u ON u.id=ak.user_id
+ JOIN campaigns AS c ON c.id=?
+ WHERE ak.id=?
+ AND u.id=?
+ AND ak.is_active=1
+ AND u.is_active=1
+ AND u.role IN (
+ 'team_lead', 'operator', 'recon', 'reporter'
+ )
+ AND (
+ ak.expires_at IS NULL
+ OR (
+ julianday(ak.expires_at) IS NOT NULL
+ AND julianday(ak.expires_at) > julianday('now')
+ )
+ )
+ AND (
+ (' ' || replace(ak.scopes, ',', ' ') || ' ')
+ LIKE '% read %'
+ OR (' ' || replace(ak.scopes, ',', ' ') || ' ')
+ LIKE '% write %'
+ OR (' ' || replace(ak.scopes, ',', ' ') || ' ')
+ LIKE '% admin %'
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ """,
+ (
+ ticket_hash,
+ campaign_id,
+ source.api_key_id,
+ source.user_id,
+ ),
+ ) as cursor:
+ changed = cursor.rowcount
+ else:
+ raise TypeError("Unsupported WebSocket ticket source")
+ if changed != 1:
+ return None
+ return raw_ticket, WEBSOCKET_TICKET_TTL_SECONDS
+
+ return await self._run_websocket_ticket_transaction(_issue)
+
+ async def consume_websocket_ticket(
+ self,
+ raw_ticket: str,
+ campaign_id: str,
+ ) -> ConsumedWebSocketTicket | None:
+ if not is_canonical_websocket_ticket(raw_ticket):
+ return None
+ ticket_hash = hash_websocket_ticket(raw_ticket)
+
+ async def _consume(
+ connection: aiosqlite.Connection,
+ ) -> ConsumedWebSocketTicket | None:
+ async with connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET consumed_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
+ WHERE ticket_hash=?
+ AND campaign_id=?
+ AND consumed_at IS NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', expires_at
+ ) IS NOT NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', expires_at
+ )=expires_at
+ AND julianday(expires_at) > julianday('now')
+ """,
+ (ticket_hash, campaign_id),
+ ) as cursor:
+ changed = cursor.rowcount
+ if changed != 1:
+ return None
+ async with connection.execute(
+ """
+ SELECT campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope
+ FROM websocket_tickets
+ WHERE ticket_hash=?
+ """,
+ (ticket_hash,),
+ ) as cursor:
+ row = await cursor.fetchone()
+ if row is None:
+ raise RuntimeError("Consumed WebSocket ticket row is missing")
+ kind = WebSocketTicketCredentialKind(row["credential_kind"])
+ bearer_expiry = (
+ parse_sqlite_utc(row["bearer_expires_at"])
+ if row["bearer_expires_at"] is not None
+ else None
+ )
+ return ConsumedWebSocketTicket(
+ campaign_id=row["campaign_id"],
+ user_id=row["user_id"],
+ credential_kind=kind,
+ bearer_subject=row["bearer_subject"],
+ bearer_jti=row["bearer_jti"],
+ bearer_expires_at=bearer_expiry,
+ api_key_id=row["api_key_id"],
+ required_scope=row["required_scope"],
+ )
+
+ return await self._run_websocket_ticket_transaction(_consume)
+
+ async def resolve_websocket_ticket_principal(
+ self,
+ handle: ConsumedWebSocketTicket,
+ ) -> WebSocketTicketPrincipal | None:
+ async with self._lifecycle_lock:
+ connection = self._require_connected()
+ if handle.credential_kind is WebSocketTicketCredentialKind.BEARER:
+ if (
+ handle.bearer_subject is None
+ or handle.bearer_jti is None
+ or handle.bearer_expires_at is None
+ ):
+ return None
+ source_expiry = format_sqlite_utc(
+ handle.bearer_expires_at
+ )
+ async with connection.execute(
+ """
+ SELECT u.id, u.username, u.role
+ FROM users AS u
+ JOIN campaigns AS c ON c.id=?
+ WHERE u.id=?
+ AND u.username=?
+ AND u.is_active=1
+ AND u.role IN (
+ 'team_lead', 'operator', 'recon', 'reporter'
+ )
+ AND julianday(?) > julianday('now')
+ AND NOT EXISTS (
+ SELECT 1
+ FROM revoked_access_tokens AS rat
+ WHERE rat.jti=?
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ """,
+ (
+ handle.campaign_id,
+ handle.user_id,
+ handle.bearer_subject,
+ source_expiry,
+ handle.bearer_jti,
+ ),
+ ) as cursor:
+ row = await cursor.fetchone()
+ if row is None or not is_valid_websocket_principal_role(
+ row["role"]
+ ):
+ return None
+ return WebSocketTicketPrincipal(
+ user_id=row["id"],
+ username=row["username"],
+ role=row["role"],
+ credential_kind=WebSocketTicketCredentialKind.BEARER,
+ )
+
+ if (
+ handle.credential_kind
+ is not WebSocketTicketCredentialKind.API_KEY
+ or handle.api_key_id is None
+ or handle.required_scope != "read"
+ ):
+ return None
+ async with connection.execute(
+ """
+ SELECT u.id, u.username, u.role, ak.id AS api_key_id,
+ ak.scopes
+ FROM api_keys AS ak
+ JOIN users AS u ON u.id=ak.user_id
+ JOIN campaigns AS c ON c.id=?
+ WHERE ak.id=?
+ AND u.id=?
+ AND ak.is_active=1
+ AND u.is_active=1
+ AND u.role IN (
+ 'team_lead', 'operator', 'recon', 'reporter'
+ )
+ AND (
+ ak.expires_at IS NULL
+ OR (
+ julianday(ak.expires_at) IS NOT NULL
+ AND julianday(ak.expires_at) > julianday('now')
+ )
+ )
+ AND (
+ (' ' || replace(ak.scopes, ',', ' ') || ' ')
+ LIKE '% read %'
+ OR (' ' || replace(ak.scopes, ',', ' ') || ' ')
+ LIKE '% write %'
+ OR (' ' || replace(ak.scopes, ',', ' ') || ' ')
+ LIKE '% admin %'
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ """,
+ (
+ handle.campaign_id,
+ handle.api_key_id,
+ handle.user_id,
+ ),
+ ) as cursor:
+ row = await cursor.fetchone()
+ if row is None or not is_valid_websocket_principal_role(
+ row["role"]
+ ):
+ return None
+ scopes = normalize_api_key_scopes(row["scopes"])
+ if not set(scopes).intersection({"read", "write", "admin"}):
+ return None
+ return WebSocketTicketPrincipal(
+ user_id=row["id"],
+ username=row["username"],
+ role=row["role"],
+ credential_kind=WebSocketTicketCredentialKind.API_KEY,
+ api_key_id=row["api_key_id"],
+ api_key_scopes=scopes,
+ )
+
+ async def purge_expired_websocket_tickets(self) -> int:
+ async def _purge(connection: aiosqlite.Connection) -> int:
+ return await self._purge_websocket_ticket_rows(connection)
+
+ return await self._run_websocket_ticket_transaction(_purge)
+
# ── Refresh Tokens (v5) ───────────────────────────────────────────────────
async def create_refresh_token(
@@ -1540,6 +2675,7 @@ class AresDatabase:
) as cur:
n = cur.rowcount
await self._conn.commit()
+ await self.purge_expired_websocket_tickets()
return n
# Backward-compat alias
diff --git a/ares/db/postgres.py b/ares/db/postgres.py
index 67700c1..fc5292e 100644
--- a/ares/db/postgres.py
+++ b/ares/db/postgres.py
@@ -27,6 +27,7 @@ Production checklist:
"""
from __future__ import annotations
+import asyncio
import hashlib
import json
import secrets
@@ -36,6 +37,19 @@ from typing import Any
from ares.core.logger import get_logger
from ares.core.security import DataEncryptor, hash_password, verify_password
+from ares.db.websocket_tickets import (
+ ApiKeyTicketSource,
+ BearerTicketSource,
+ ConsumedWebSocketTicket,
+ WebSocketTicketCredentialKind,
+ WebSocketTicketPrincipal,
+ WEBSOCKET_TICKET_TTL_SECONDS,
+ generate_websocket_ticket,
+ hash_websocket_ticket,
+ is_canonical_websocket_ticket,
+ is_valid_websocket_principal_role,
+ normalize_api_key_scopes,
+)
logger = get_logger("ares.db.postgres")
@@ -228,6 +242,83 @@ CREATE TABLE IF NOT EXISTS revoked_access_tokens (
expires_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_pg_rat_expires ON revoked_access_tokens(expires_at);
+
+CREATE TABLE IF NOT EXISTS websocket_tickets (
+ ticket_hash TEXT NOT NULL PRIMARY KEY
+ CONSTRAINT ck_ws_ticket_hash CHECK (
+ ticket_hash ~ '^[0-9a-f]{64}$'
+ ),
+ campaign_id TEXT NOT NULL
+ CONSTRAINT fk_ws_ticket_campaign
+ REFERENCES campaigns(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL
+ CONSTRAINT fk_ws_ticket_user
+ REFERENCES users(id) ON DELETE CASCADE,
+ credential_kind TEXT NOT NULL
+ CONSTRAINT ck_ws_ticket_kind CHECK (
+ credential_kind IN ('bearer', 'api_key')
+ ),
+ bearer_subject TEXT,
+ bearer_jti TEXT,
+ bearer_expires_at TIMESTAMPTZ,
+ api_key_id TEXT
+ CONSTRAINT fk_ws_ticket_api_key
+ REFERENCES api_keys(id) ON DELETE CASCADE,
+ required_scope TEXT,
+ created_at TIMESTAMPTZ NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ consumed_at TIMESTAMPTZ,
+ CONSTRAINT ck_ws_ticket_created_at CHECK (created_at < expires_at),
+ CONSTRAINT ck_ws_ticket_expires_at CHECK (expires_at > created_at),
+ CONSTRAINT ck_ws_ticket_consumed_at CHECK (
+ consumed_at IS NULL OR consumed_at < expires_at
+ ),
+ CONSTRAINT ck_ws_ticket_bearer_expires_finite CHECK (
+ bearer_expires_at IS NULL OR isfinite(bearer_expires_at)
+ ),
+ CONSTRAINT ck_ws_ticket_created_finite CHECK (isfinite(created_at)),
+ CONSTRAINT ck_ws_ticket_expires_finite CHECK (isfinite(expires_at)),
+ CONSTRAINT ck_ws_ticket_consumed_finite CHECK (
+ consumed_at IS NULL OR isfinite(consumed_at)
+ ),
+ CONSTRAINT ck_ws_ticket_time_order CHECK (
+ expires_at > created_at
+ AND (consumed_at IS NULL OR consumed_at < expires_at)
+ ),
+ CONSTRAINT ck_ws_ticket_source_shape CHECK (
+ (
+ credential_kind='bearer'
+ AND bearer_subject IS NOT NULL
+ AND length(btrim(bearer_subject)) > 0
+ AND bearer_subject=btrim(bearer_subject)
+ AND bearer_jti IS NOT NULL
+ AND length(btrim(bearer_jti)) > 0
+ AND bearer_jti=btrim(bearer_jti)
+ AND bearer_expires_at IS NOT NULL
+ AND api_key_id IS NULL
+ AND required_scope IS NULL
+ )
+ OR
+ (
+ credential_kind='api_key'
+ AND bearer_subject IS NULL
+ AND bearer_jti IS NULL
+ AND bearer_expires_at IS NULL
+ AND api_key_id IS NOT NULL
+ AND length(btrim(api_key_id)) > 0
+ AND api_key_id=btrim(api_key_id)
+ AND required_scope='read'
+ )
+ )
+);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_expires
+ ON websocket_tickets(expires_at);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_user
+ ON websocket_tickets(user_id);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_campaign
+ ON websocket_tickets(campaign_id);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_api_key
+ ON websocket_tickets(api_key_id);
"""
@@ -272,16 +363,40 @@ class PostgresDatabase:
"asyncpg is required for PostgreSQL support. "
"Install: pip install ares-redteam[postgres]"
) from exc
- self._pool = await asyncpg.create_pool(
+ pool = await asyncpg.create_pool(
self._dsn,
min_size=self._pool_min,
max_size=self._pool_max,
command_timeout=30,
)
- await self._init_schema()
- logger.info("pg_db_ready", dsn=self._dsn[:40] + "…")
+ self._pool = pool
+ try:
+ await self._init_schema()
+ except Exception as primary:
+ await self._close_failed_startup_pool(pool, primary)
+ raise
+ except asyncio.CancelledError as primary:
+ await self._close_failed_startup_pool(pool, primary)
+ raise
+ logger.info("pg_db_ready")
return self
+ async def _close_failed_startup_pool(
+ self,
+ pool: Any,
+ primary: BaseException,
+ ) -> None:
+ try:
+ await pool.close()
+ except Exception as cleanup_error:
+ primary.add_note(
+ "PostgreSQL startup cleanup failure "
+ f"[pool-close: {type(cleanup_error).__name__}]"
+ )
+ finally:
+ if self._pool is pool:
+ self._pool = None
+
async def __aenter__(self) -> "PostgresDatabase":
return await self.connect()
@@ -303,9 +418,578 @@ class PostgresDatabase:
async def _init_schema(self) -> None:
async with self._pool.acquire() as conn:
- await conn.execute(_PG_CREATE_TABLES)
+ async with conn.transaction():
+ ticket_table_exists = bool(
+ await conn.fetchval(
+ """
+ SELECT EXISTS(
+ SELECT 1
+ FROM pg_class AS rel
+ JOIN pg_namespace AS nsp
+ ON nsp.oid=rel.relnamespace
+ WHERE nsp.nspname=current_schema()
+ AND rel.relname='websocket_tickets'
+ )
+ """
+ )
+ )
+ if ticket_table_exists:
+ await self._validate_websocket_ticket_schema(conn)
+ await conn.execute(_PG_CREATE_TABLES)
+ await self._validate_websocket_ticket_schema(conn)
logger.info("pg_schema_ready")
+ @staticmethod
+ async def _validate_websocket_ticket_schema(connection: Any) -> None:
+ """Reject any ticket catalog that differs from the owned schema."""
+ relation = await connection.fetchrow(
+ """
+ SELECT rel.oid::bigint AS table_oid,
+ nsp.oid::bigint AS schema_oid,
+ nsp.nspname AS schema_name,
+ rel.relkind,
+ rel.relpersistence,
+ rel.relispartition,
+ rel.relrowsecurity,
+ rel.relforcerowsecurity,
+ (
+ SELECT COUNT(*)
+ FROM pg_inherits AS inherited
+ WHERE inherited.inhrelid=rel.oid
+ ) AS parent_count,
+ (
+ SELECT COUNT(*)
+ FROM pg_inherits AS inherited
+ WHERE inherited.inhparent=rel.oid
+ ) AS child_count,
+ (
+ SELECT COUNT(*)
+ FROM pg_policy AS policy
+ WHERE policy.polrelid=rel.oid
+ ) AS policy_count,
+ (
+ SELECT COUNT(*)
+ FROM pg_trigger AS trg
+ WHERE trg.tgrelid=rel.oid
+ AND NOT trg.tgisinternal
+ ) AS user_trigger_count,
+ (
+ SELECT COUNT(*)
+ FROM pg_rewrite AS rewrite
+ WHERE rewrite.ev_class=rel.oid
+ ) AS user_rule_count
+ FROM pg_class AS rel
+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace
+ WHERE nsp.nspname=current_schema()
+ AND rel.relname='websocket_tickets'
+ """
+ )
+ if relation is None:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ table_oid = int(relation["table_oid"])
+ schema_oid = int(relation["schema_oid"])
+ schema_name = str(relation["schema_name"])
+ relation_contract = (
+ str(relation["relkind"]),
+ str(relation["relpersistence"]),
+ bool(relation["relispartition"]),
+ bool(relation["relrowsecurity"]),
+ bool(relation["relforcerowsecurity"]),
+ int(relation["parent_count"]),
+ int(relation["child_count"]),
+ int(relation["policy_count"]),
+ int(relation["user_trigger_count"]),
+ int(relation["user_rule_count"]),
+ )
+ if relation_contract != (
+ "r",
+ "p",
+ False,
+ False,
+ False,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ rows = await connection.fetch(
+ """
+ SELECT att.attname AS column_name,
+ pg_catalog.format_type(att.atttypid, att.atttypmod) AS data_type,
+ att.attnotnull,
+ att.attidentity,
+ att.attgenerated,
+ att.attcollation=typ.typcollation AS collation_is_default,
+ pg_get_expr(def.adbin, def.adrelid) AS column_default
+ FROM pg_attribute AS att
+ JOIN pg_type AS typ ON typ.oid=att.atttypid
+ LEFT JOIN pg_attrdef AS def
+ ON def.adrelid=att.attrelid AND def.adnum=att.attnum
+ WHERE att.attrelid=$1::oid
+ AND att.attnum > 0
+ AND NOT att.attisdropped
+ ORDER BY att.attnum
+ """,
+ table_oid,
+ )
+ actual_columns = [
+ (
+ str(row["column_name"]),
+ str(row["data_type"]),
+ bool(row["attnotnull"]),
+ str(row["attidentity"]),
+ str(row["attgenerated"]),
+ bool(row["collation_is_default"]),
+ None if row["column_default"] is None else str(row["column_default"]),
+ )
+ for row in rows
+ ]
+ expected_columns = [
+ ("ticket_hash", "text", True, "", "", True, None),
+ ("campaign_id", "text", True, "", "", True, None),
+ ("user_id", "text", True, "", "", True, None),
+ ("credential_kind", "text", True, "", "", True, None),
+ ("bearer_subject", "text", False, "", "", True, None),
+ ("bearer_jti", "text", False, "", "", True, None),
+ (
+ "bearer_expires_at",
+ "timestamp with time zone",
+ False,
+ "",
+ "",
+ True,
+ None,
+ ),
+ ("api_key_id", "text", False, "", "", True, None),
+ ("required_scope", "text", False, "", "", True, None),
+ (
+ "created_at",
+ "timestamp with time zone",
+ True,
+ "",
+ "",
+ True,
+ None,
+ ),
+ (
+ "expires_at",
+ "timestamp with time zone",
+ True,
+ "",
+ "",
+ True,
+ None,
+ ),
+ (
+ "consumed_at",
+ "timestamp with time zone",
+ False,
+ "",
+ "",
+ True,
+ None,
+ ),
+ ]
+ if actual_columns != expected_columns:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ constraint_rows = await connection.fetch(
+ """
+ SELECT con.conname, con.contype,
+ con.conrelid::bigint AS table_oid,
+ con.confrelid::bigint AS referenced_oid,
+ con.conindid::bigint AS constraint_index_oid,
+ con.convalidated,
+ con.condeferrable, con.condeferred,
+ pg_get_constraintdef(con.oid, true) AS definition,
+ ref_nsp.oid::bigint AS referenced_schema_oid,
+ ref_nsp.nspname AS referenced_schema,
+ ref_rel.relname AS referenced_table,
+ ARRAY(
+ SELECT local_att.attname
+ FROM unnest(con.conkey) WITH ORDINALITY AS key(attnum, ordinality)
+ JOIN pg_attribute AS local_att
+ ON local_att.attrelid=con.conrelid
+ AND local_att.attnum=key.attnum
+ ORDER BY key.ordinality
+ ) AS local_columns,
+ ARRAY(
+ SELECT remote_att.attname
+ FROM unnest(con.confkey) WITH ORDINALITY AS key(attnum, ordinality)
+ JOIN pg_attribute AS remote_att
+ ON remote_att.attrelid=con.confrelid
+ AND remote_att.attnum=key.attnum
+ ORDER BY key.ordinality
+ ) AS remote_columns,
+ con.confupdtype, con.confdeltype
+ FROM pg_constraint AS con
+ LEFT JOIN pg_class AS ref_rel ON ref_rel.oid=con.confrelid
+ LEFT JOIN pg_namespace AS ref_nsp ON ref_nsp.oid=ref_rel.relnamespace
+ WHERE con.conrelid=$1::oid
+ ORDER BY con.conname
+ """,
+ table_oid,
+ )
+ actual_constraints = {
+ str(row["conname"]): row
+ for row in constraint_rows
+ }
+ expected_constraint_names = {
+ "ck_ws_ticket_bearer_expires_finite",
+ "ck_ws_ticket_consumed_at",
+ "ck_ws_ticket_consumed_finite",
+ "ck_ws_ticket_created_at",
+ "ck_ws_ticket_created_finite",
+ "ck_ws_ticket_expires_at",
+ "ck_ws_ticket_expires_finite",
+ "ck_ws_ticket_hash",
+ "ck_ws_ticket_kind",
+ "ck_ws_ticket_source_shape",
+ "ck_ws_ticket_time_order",
+ "fk_ws_ticket_api_key",
+ "fk_ws_ticket_campaign",
+ "fk_ws_ticket_user",
+ "websocket_tickets_pkey",
+ }
+ if set(actual_constraints) != expected_constraint_names:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ index_rows = await connection.fetch(
+ """
+ SELECT ind.indrelid::bigint AS table_oid,
+ ind.indexrelid::bigint AS index_oid,
+ idx.relnamespace::bigint AS index_schema_oid,
+ idx_nsp.nspname AS index_schema,
+ idx.relname AS index_name,
+ idx.relkind AS index_relkind,
+ idx.relpersistence AS index_relpersistence,
+ idx.relispartition AS index_is_partition,
+ am.amname AS access_method,
+ ind.indisunique,
+ ind.indisprimary,
+ ind.indisvalid,
+ ind.indisready,
+ ind.indislive,
+ ind.indnkeyatts,
+ ind.indnatts,
+ ARRAY(
+ SELECT CASE
+ WHEN key.attnum=0 THEN NULL
+ ELSE att.attname
+ END
+ FROM unnest(ind.indkey) WITH ORDINALITY AS key(attnum, ordinality)
+ LEFT JOIN pg_attribute AS att
+ ON att.attrelid=ind.indrelid
+ AND att.attnum=key.attnum
+ ORDER BY key.ordinality
+ ) AS columns,
+ ARRAY(
+ SELECT option
+ FROM unnest(ind.indoption) WITH ORDINALITY AS item(option, ordinality)
+ ORDER BY item.ordinality
+ ) AS column_options,
+ ARRAY(
+ SELECT opc.opcname
+ FROM unnest(ind.indclass) WITH ORDINALITY AS item(opclass, ordinality)
+ JOIN pg_opclass AS opc ON opc.oid=item.opclass
+ ORDER BY item.ordinality
+ ) AS operator_classes,
+ ARRAY(
+ SELECT opc.oid::bigint
+ FROM unnest(ind.indclass) WITH ORDINALITY AS item(opclass, ordinality)
+ JOIN pg_opclass AS opc ON opc.oid=item.opclass
+ ORDER BY item.ordinality
+ ) AS operator_class_oids,
+ ARRAY(
+ SELECT opc_nsp.nspname
+ FROM unnest(ind.indclass) WITH ORDINALITY AS item(opclass, ordinality)
+ JOIN pg_opclass AS opc ON opc.oid=item.opclass
+ JOIN pg_namespace AS opc_nsp
+ ON opc_nsp.oid=opc.opcnamespace
+ ORDER BY item.ordinality
+ ) AS operator_class_namespaces,
+ ARRAY(
+ SELECT item.collation=att.attcollation
+ FROM unnest(ind.indcollation) WITH ORDINALITY
+ AS item(collation, ordinality)
+ JOIN unnest(ind.indkey) WITH ORDINALITY
+ AS key(attnum, ordinality)
+ ON key.ordinality=item.ordinality
+ LEFT JOIN pg_attribute AS att
+ ON att.attrelid=ind.indrelid
+ AND att.attnum=key.attnum
+ ORDER BY item.ordinality
+ ) AS column_collations_match,
+ pg_get_expr(ind.indexprs, ind.indrelid) AS expressions,
+ pg_get_expr(ind.indpred, ind.indrelid) AS predicate,
+ pg_get_indexdef(ind.indexrelid) AS definition
+ FROM pg_index AS ind
+ JOIN pg_class AS idx ON idx.oid=ind.indexrelid
+ JOIN pg_namespace AS idx_nsp ON idx_nsp.oid=idx.relnamespace
+ JOIN pg_am AS am ON am.oid=idx.relam
+ WHERE ind.indrelid=$1::oid
+ ORDER BY idx.relname
+ """,
+ table_oid,
+ )
+ canonical_opclass_rows = await connection.fetch(
+ """
+ SELECT opc.opcname, opc.oid::bigint AS opclass_oid
+ FROM pg_opclass AS opc
+ JOIN pg_namespace AS nsp ON nsp.oid=opc.opcnamespace
+ JOIN pg_am AS am ON am.oid=opc.opcmethod
+ WHERE nsp.nspname='pg_catalog'
+ AND am.amname='btree'
+ AND opc.opcname=ANY($1::text[])
+ """,
+ ["text_ops", "timestamptz_ops"],
+ )
+ canonical_opclasses = {
+ str(row["opcname"]): int(row["opclass_oid"])
+ for row in canonical_opclass_rows
+ }
+ if set(canonical_opclasses) != {"text_ops", "timestamptz_ops"}:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ index_oids: set[int] = set()
+ for row in index_rows:
+ operator_classes = tuple(
+ str(opclass) for opclass in row["operator_classes"]
+ )
+ operator_class_oids = tuple(
+ int(opclass_oid) for opclass_oid in row["operator_class_oids"]
+ )
+ canonical_oids = tuple(
+ canonical_opclasses.get(opclass, -1)
+ for opclass in operator_classes
+ )
+ index_oid = int(row["index_oid"])
+ identity_is_exact = (
+ int(row["table_oid"]) == table_oid
+ and int(row["index_schema_oid"]) == schema_oid
+ and str(row["index_schema"]) == schema_name
+ and str(row["index_relkind"]) == "i"
+ and str(row["index_relpersistence"]) == "p"
+ and not bool(row["index_is_partition"])
+ and tuple(
+ str(namespace)
+ for namespace in row["operator_class_namespaces"]
+ )
+ == ("pg_catalog",) * len(operator_classes)
+ and operator_class_oids == canonical_oids
+ and index_oid > 0
+ and index_oid not in index_oids
+ )
+ if not identity_is_exact:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+ index_oids.add(index_oid)
+
+ actual_indexes = {
+ str(row["index_name"]): (
+ str(row["access_method"]),
+ bool(row["indisunique"]),
+ bool(row["indisprimary"]),
+ bool(row["indisvalid"]),
+ bool(row["indisready"]),
+ bool(row["indislive"]),
+ int(row["indnkeyatts"]),
+ int(row["indnatts"]),
+ tuple(
+ None if column is None else str(column)
+ for column in row["columns"]
+ ),
+ tuple(int(option) for option in row["column_options"]),
+ tuple(str(opclass) for opclass in row["operator_classes"]),
+ tuple(bool(value) for value in row["column_collations_match"]),
+ None if row["expressions"] is None else str(row["expressions"]),
+ None if row["predicate"] is None else str(row["predicate"]),
+ )
+ for row in index_rows
+ }
+ expected_indexes = {
+ "idx_ws_tickets_api_key": (
+ "btree", False, False, True, True, True,
+ 1, 1, ("api_key_id",), (0,), ("text_ops",), (True,), None, None,
+ ),
+ "idx_ws_tickets_campaign": (
+ "btree", False, False, True, True, True,
+ 1, 1, ("campaign_id",), (0,), ("text_ops",), (True,), None, None,
+ ),
+ "idx_ws_tickets_expires": (
+ "btree", False, False, True, True, True,
+ 1, 1, ("expires_at",), (0,), ("timestamptz_ops",), (True,),
+ None, None,
+ ),
+ "idx_ws_tickets_user": (
+ "btree", False, False, True, True, True,
+ 1, 1, ("user_id",), (0,), ("text_ops",), (True,), None, None,
+ ),
+ "websocket_tickets_pkey": (
+ "btree", True, True, True, True, True,
+ 1, 1, ("ticket_hash",), (0,), ("text_ops",), (True,), None, None,
+ ),
+ }
+ if actual_indexes != expected_indexes:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ expected_constraint_fragments = {
+ "websocket_tickets_pkey": ("p", "PRIMARY KEY (ticket_hash)"),
+ "fk_ws_ticket_campaign": (
+ "f",
+ "FOREIGN KEY (campaign_id) REFERENCES campaigns(id) ON DELETE CASCADE",
+ ),
+ "fk_ws_ticket_user": (
+ "f",
+ "FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE",
+ ),
+ "fk_ws_ticket_api_key": (
+ "f",
+ "FOREIGN KEY (api_key_id) REFERENCES api_keys(id) ON DELETE CASCADE",
+ ),
+ }
+ for name, definition in expected_constraint_fragments.items():
+ row = actual_constraints[name]
+ if (
+ str(row["contype"]) != definition[0]
+ or not bool(row["convalidated"])
+ or bool(row["condeferrable"])
+ or bool(row["condeferred"])
+ or " ".join(str(row["definition"]).split()) != definition[1]
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ referenced_schema = str(await connection.fetchval("SELECT current_schema()"))
+ expected_foreign_keys = {
+ "fk_ws_ticket_campaign": (
+ ("campaign_id",), referenced_schema, "campaigns", ("id",), "a", "c",
+ ),
+ "fk_ws_ticket_user": (
+ ("user_id",), referenced_schema, "users", ("id",), "a", "c",
+ ),
+ "fk_ws_ticket_api_key": (
+ ("api_key_id",), referenced_schema, "api_keys", ("id",), "a", "c",
+ ),
+ }
+ referenced_rows = await connection.fetch(
+ """
+ SELECT rel.relname, rel.oid::bigint AS relation_oid
+ FROM pg_class AS rel
+ WHERE rel.relnamespace=$1::oid
+ AND rel.relname=ANY($2::text[])
+ """,
+ schema_oid,
+ ["api_keys", "campaigns", "users"],
+ )
+ referenced_oids = {
+ str(row["relname"]): int(row["relation_oid"])
+ for row in referenced_rows
+ }
+ if set(referenced_oids) != {"api_keys", "campaigns", "users"}:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ if any(
+ int(row["table_oid"]) != table_oid
+ for row in actual_constraints.values()
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ for name, expected in expected_foreign_keys.items():
+ row = actual_constraints[name]
+ actual = (
+ tuple(str(column) for column in row["local_columns"]),
+ str(row["referenced_schema"]),
+ str(row["referenced_table"]),
+ tuple(str(column) for column in row["remote_columns"]),
+ str(row["confupdtype"]),
+ str(row["confdeltype"]),
+ )
+ reference_identity_is_exact = (
+ row["referenced_schema_oid"] is not None
+ and int(row["referenced_schema_oid"]) == schema_oid
+ and int(row["referenced_oid"])
+ == referenced_oids[expected[2]]
+ )
+ if actual != expected or not reference_identity_is_exact:
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ primary = actual_constraints["websocket_tickets_pkey"]
+ if (
+ tuple(str(column) for column in primary["local_columns"])
+ != ("ticket_hash",)
+ or tuple(primary["remote_columns"])
+ or primary["referenced_schema"] is not None
+ or primary["referenced_table"] is not None
+ or int(primary["constraint_index_oid"])
+ != next(
+ int(row["index_oid"])
+ for row in index_rows
+ if str(row["index_name"]) == "websocket_tickets_pkey"
+ )
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
+ expected_check_definitions = {
+ "ck_ws_ticket_hash": (
+ "CHECK (ticket_hash ~ '^[0-9a-f]{64}$'::text)"
+ ),
+ "ck_ws_ticket_kind": (
+ "CHECK (credential_kind = ANY "
+ "(ARRAY['bearer'::text, 'api_key'::text]))"
+ ),
+ "ck_ws_ticket_created_at": "CHECK (created_at < expires_at)",
+ "ck_ws_ticket_expires_at": "CHECK (expires_at > created_at)",
+ "ck_ws_ticket_consumed_at": (
+ "CHECK (consumed_at IS NULL OR consumed_at < expires_at)"
+ ),
+ "ck_ws_ticket_bearer_expires_finite": (
+ "CHECK (bearer_expires_at IS NULL "
+ "OR isfinite(bearer_expires_at))"
+ ),
+ "ck_ws_ticket_created_finite": "CHECK (isfinite(created_at))",
+ "ck_ws_ticket_expires_finite": "CHECK (isfinite(expires_at))",
+ "ck_ws_ticket_consumed_finite": (
+ "CHECK (consumed_at IS NULL OR isfinite(consumed_at))"
+ ),
+ "ck_ws_ticket_time_order": (
+ "CHECK (expires_at > created_at AND "
+ "(consumed_at IS NULL OR consumed_at < expires_at))"
+ ),
+ "ck_ws_ticket_source_shape": (
+ "CHECK (credential_kind = 'bearer'::text "
+ "AND bearer_subject IS NOT NULL "
+ "AND length(btrim(bearer_subject)) > 0 "
+ "AND bearer_subject = btrim(bearer_subject) "
+ "AND bearer_jti IS NOT NULL "
+ "AND length(btrim(bearer_jti)) > 0 "
+ "AND bearer_jti = btrim(bearer_jti) "
+ "AND bearer_expires_at IS NOT NULL "
+ "AND api_key_id IS NULL "
+ "AND required_scope IS NULL "
+ "OR credential_kind = 'api_key'::text "
+ "AND bearer_subject IS NULL "
+ "AND bearer_jti IS NULL "
+ "AND bearer_expires_at IS NULL "
+ "AND api_key_id IS NOT NULL "
+ "AND length(btrim(api_key_id)) > 0 "
+ "AND api_key_id = btrim(api_key_id) "
+ "AND required_scope = 'read'::text)"
+ ),
+ }
+ for name, expected_definition in expected_check_definitions.items():
+ row = actual_constraints[name]
+ if (
+ str(row["contype"]) != "c"
+ or not bool(row["convalidated"])
+ or bool(row["condeferrable"])
+ or bool(row["condeferred"])
+ or " ".join(str(row["definition"]).split())
+ != expected_definition
+ ):
+ raise RuntimeError("Incompatible WebSocket ticket schema")
+
# ── Helpers ────────────────────────────────────────────────────────────────
def _enc_val(self, v: str | None) -> str | None:
@@ -937,6 +1621,253 @@ class PostgresDatabase:
# ── Refresh Tokens ─────────────────────────────────────────────────────────
+ # ── One-time WebSocket tickets ───────────────────────────────────────────
+
+ def _require_websocket_ticket_pool(self) -> Any:
+ if self._pool is None:
+ raise RuntimeError("PostgreSQL database is not connected")
+ return self._pool
+
+ @staticmethod
+ async def _purge_websocket_ticket_rows(connection: Any) -> None:
+ await connection.execute(
+ "DELETE FROM websocket_tickets WHERE expires_at <= now()"
+ )
+
+ async def issue_websocket_ticket(
+ self,
+ campaign_id: str,
+ source: BearerTicketSource | ApiKeyTicketSource,
+ ) -> tuple[str, int] | None:
+ raw_ticket = generate_websocket_ticket()
+ ticket_hash = hash_websocket_ticket(raw_ticket)
+ pool = self._require_websocket_ticket_pool()
+ issued = False
+
+ async with pool.acquire() as connection:
+ async with connection.transaction():
+ await self._purge_websocket_ticket_rows(connection)
+ if isinstance(source, BearerTicketSource):
+ row = await connection.fetchrow(
+ """
+ INSERT INTO websocket_tickets(
+ ticket_hash, campaign_id, user_id,
+ credential_kind, bearer_subject, bearer_jti,
+ bearer_expires_at, created_at, expires_at
+ )
+ SELECT $1, c.id, u.id, 'bearer', $4, $5, $6,
+ now(), now() + interval '30 seconds'
+ FROM users AS u
+ JOIN campaigns AS c ON c.id=$2
+ WHERE u.id=$3
+ AND u.username=$4
+ AND u.is_active=1
+ AND u.role IN ('team_lead','operator','recon','reporter')
+ AND $6 > now()
+ AND NOT EXISTS (
+ SELECT 1 FROM revoked_access_tokens AS rat
+ WHERE rat.jti=$5
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ RETURNING ticket_hash
+ """,
+ ticket_hash,
+ campaign_id,
+ source.user_id,
+ source.subject,
+ source.jti,
+ source.expires_at,
+ )
+ else:
+ row = await connection.fetchrow(
+ """
+ INSERT INTO websocket_tickets(
+ ticket_hash, campaign_id, user_id,
+ credential_kind, api_key_id, required_scope,
+ created_at, expires_at
+ )
+ SELECT $1, c.id, u.id, 'api_key', ak.id, 'read',
+ now(), now() + interval '30 seconds'
+ FROM api_keys AS ak
+ JOIN users AS u ON u.id=ak.user_id
+ JOIN campaigns AS c ON c.id=$2
+ WHERE ak.id=$4
+ AND ak.user_id=$3
+ AND ak.is_active=1
+ AND (ak.expires_at IS NULL OR ak.expires_at > now())
+ AND u.is_active=1
+ AND u.role IN ('team_lead','operator','recon','reporter')
+ AND (
+ regexp_split_to_array(
+ btrim(COALESCE(ak.scopes, '')),
+ '[[:space:],]+'
+ ) && ARRAY['read','write','admin']
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ RETURNING ticket_hash
+ """,
+ ticket_hash,
+ campaign_id,
+ source.user_id,
+ source.api_key_id,
+ )
+ issued = row is not None
+
+ if not issued:
+ return None
+ return raw_ticket, WEBSOCKET_TICKET_TTL_SECONDS
+
+ async def consume_websocket_ticket(
+ self,
+ raw_ticket: str,
+ campaign_id: str,
+ ) -> ConsumedWebSocketTicket | None:
+ if not is_canonical_websocket_ticket(raw_ticket):
+ return None
+
+ ticket_hash = hash_websocket_ticket(raw_ticket)
+ pool = self._require_websocket_ticket_pool()
+ consumed: ConsumedWebSocketTicket | None = None
+
+ async with pool.acquire() as connection:
+ async with connection.transaction():
+ row = await connection.fetchrow(
+ """
+ UPDATE websocket_tickets
+ SET consumed_at=now()
+ WHERE ticket_hash=$1
+ AND campaign_id=$2
+ AND consumed_at IS NULL
+ AND expires_at > now()
+ RETURNING campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti,
+ bearer_expires_at, api_key_id,
+ required_scope
+ """,
+ ticket_hash,
+ campaign_id,
+ )
+ if row is not None:
+ consumed = ConsumedWebSocketTicket(
+ campaign_id=row["campaign_id"],
+ user_id=row["user_id"],
+ credential_kind=WebSocketTicketCredentialKind(
+ row["credential_kind"]
+ ),
+ bearer_subject=row["bearer_subject"],
+ bearer_jti=row["bearer_jti"],
+ bearer_expires_at=row["bearer_expires_at"],
+ api_key_id=row["api_key_id"],
+ required_scope=row["required_scope"],
+ )
+
+ return consumed
+
+ async def resolve_websocket_ticket_principal(
+ self,
+ consumed: ConsumedWebSocketTicket,
+ ) -> WebSocketTicketPrincipal | None:
+ pool = self._require_websocket_ticket_pool()
+ async with pool.acquire() as connection:
+ if consumed.credential_kind is WebSocketTicketCredentialKind.BEARER:
+ row = await connection.fetchrow(
+ """
+ SELECT u.id, u.username, u.role
+ FROM users AS u
+ JOIN campaigns AS c ON c.id=$1
+ WHERE u.id=$2
+ AND u.username=$3
+ AND u.is_active=1
+ AND u.role IN ('team_lead','operator','recon','reporter')
+ AND $4 > now()
+ AND NOT EXISTS (
+ SELECT 1 FROM revoked_access_tokens AS rat
+ WHERE rat.jti=$5
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ """,
+ consumed.campaign_id,
+ consumed.user_id,
+ consumed.bearer_subject,
+ consumed.bearer_expires_at,
+ consumed.bearer_jti,
+ )
+ else:
+ row = await connection.fetchrow(
+ """
+ SELECT u.id, u.username, u.role, ak.id AS api_key_id,
+ ak.scopes
+ FROM api_keys AS ak
+ JOIN users AS u ON u.id=ak.user_id
+ JOIN campaigns AS c ON c.id=$1
+ WHERE ak.id=$3
+ AND ak.user_id=$2
+ AND ak.is_active=1
+ AND (ak.expires_at IS NULL OR ak.expires_at > now())
+ AND u.is_active=1
+ AND u.role IN ('team_lead','operator','recon','reporter')
+ AND (
+ regexp_split_to_array(
+ btrim(COALESCE(ak.scopes, '')),
+ '[[:space:],]+'
+ ) && ARRAY['read','write','admin']
+ )
+ AND (
+ u.role='team_lead'
+ OR c.operator=u.username
+ )
+ """,
+ consumed.campaign_id,
+ consumed.user_id,
+ consumed.api_key_id,
+ )
+
+ if row is None:
+ return None
+ if not is_valid_websocket_principal_role(row["role"]):
+ return None
+ if consumed.credential_kind is WebSocketTicketCredentialKind.BEARER:
+ return WebSocketTicketPrincipal(
+ user_id=row["id"],
+ username=row["username"],
+ role=row["role"],
+ credential_kind=WebSocketTicketCredentialKind.BEARER,
+ )
+ scopes = normalize_api_key_scopes(row["scopes"])
+ if not set(scopes).intersection({"read", "write", "admin"}):
+ return None
+ return WebSocketTicketPrincipal(
+ user_id=row["id"],
+ username=row["username"],
+ role=row["role"],
+ credential_kind=WebSocketTicketCredentialKind.API_KEY,
+ api_key_id=row["api_key_id"],
+ api_key_scopes=scopes,
+ )
+
+ async def purge_expired_websocket_tickets(self) -> int:
+ pool = self._require_websocket_ticket_pool()
+ async with pool.acquire() as connection:
+ async with connection.transaction():
+ result = await connection.execute(
+ "DELETE FROM websocket_tickets WHERE expires_at <= now()"
+ )
+ try:
+ return int(result.split()[-1])
+ except (ValueError, IndexError):
+ return 0
+
+ # ── Refresh tokens ───────────────────────────────────────────────────────
+
async def create_refresh_token(self, user_id: str, expires_days: int = 30) -> str:
raw_token = secrets.token_urlsafe(48) # returned to client
token_hash = hashlib.sha256(raw_token.encode()).hexdigest() # stored in DB
@@ -1028,6 +1959,7 @@ class PostgresDatabase:
result = await conn.execute(
"DELETE FROM refresh_tokens WHERE is_revoked=1 OR expires_at < now() - interval '7 days'"
)
+ await self.purge_expired_websocket_tickets()
# asyncpg returns "DELETE N" as a string
try:
return int(result.split()[-1])
diff --git a/ares/db/schema.py b/ares/db/schema.py
index 80c0368..4bb6a6f 100644
--- a/ares/db/schema.py
+++ b/ares/db/schema.py
@@ -16,7 +16,7 @@ Tables (v5 additions marked ★):
"""
from __future__ import annotations
-SCHEMA_VERSION = 6
+SCHEMA_VERSION = 7
CREATE_TABLES = """
PRAGMA journal_mode = WAL;
@@ -216,6 +216,95 @@ CREATE TABLE IF NOT EXISTS revoked_access_tokens (
expires_at TEXT NOT NULL -- auto-cleaned when past expiry
);
CREATE INDEX IF NOT EXISTS idx_rat_expires ON revoked_access_tokens(expires_at);
+
+-- One-time, campaign-bound WebSocket handshake tickets.
+CREATE TABLE IF NOT EXISTS websocket_tickets (
+ ticket_hash TEXT NOT NULL PRIMARY KEY
+ CONSTRAINT ck_ws_ticket_hash CHECK (
+ length(ticket_hash)=64
+ AND ticket_hash NOT GLOB '*[^0-9a-f]*'
+ ),
+ campaign_id TEXT NOT NULL
+ CONSTRAINT fk_ws_ticket_campaign
+ REFERENCES campaigns(id) ON DELETE CASCADE,
+ user_id TEXT NOT NULL
+ CONSTRAINT fk_ws_ticket_user
+ REFERENCES users(id) ON DELETE CASCADE,
+ credential_kind TEXT NOT NULL
+ CONSTRAINT ck_ws_ticket_kind CHECK (
+ credential_kind IN ('bearer', 'api_key')
+ ),
+ bearer_subject TEXT,
+ bearer_jti TEXT,
+ bearer_expires_at TEXT,
+ api_key_id TEXT
+ CONSTRAINT fk_ws_ticket_api_key
+ REFERENCES api_keys(id) ON DELETE CASCADE,
+ required_scope TEXT,
+ created_at TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ consumed_at TEXT,
+ CONSTRAINT ck_ws_ticket_created_at CHECK (
+ strftime('%Y-%m-%dT%H:%M:%fZ', created_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ', created_at)=created_at
+ ),
+ CONSTRAINT ck_ws_ticket_expires_at CHECK (
+ strftime('%Y-%m-%dT%H:%M:%fZ', expires_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ', expires_at)=expires_at
+ ),
+ CONSTRAINT ck_ws_ticket_consumed_at CHECK (
+ consumed_at IS NULL OR (
+ strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at)=consumed_at
+ )
+ ),
+ CONSTRAINT ck_ws_ticket_time_order CHECK (
+ julianday(expires_at) > julianday(created_at)
+ AND (
+ consumed_at IS NULL
+ OR julianday(consumed_at) < julianday(expires_at)
+ )
+ ),
+ CONSTRAINT ck_ws_ticket_source_shape CHECK (
+ (
+ credential_kind='bearer'
+ AND bearer_subject IS NOT NULL
+ AND length(trim(bearer_subject)) > 0
+ AND bearer_subject=trim(bearer_subject)
+ AND bearer_jti IS NOT NULL
+ AND length(trim(bearer_jti)) > 0
+ AND bearer_jti=trim(bearer_jti)
+ AND bearer_expires_at IS NOT NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
+ ) IS NOT NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
+ )=bearer_expires_at
+ AND api_key_id IS NULL
+ AND required_scope IS NULL
+ )
+ OR
+ (
+ credential_kind='api_key'
+ AND bearer_subject IS NULL
+ AND bearer_jti IS NULL
+ AND bearer_expires_at IS NULL
+ AND api_key_id IS NOT NULL
+ AND length(trim(api_key_id)) > 0
+ AND api_key_id=trim(api_key_id)
+ AND required_scope='read'
+ )
+ )
+);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_expires
+ ON websocket_tickets(expires_at);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_user
+ ON websocket_tickets(user_id);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_campaign
+ ON websocket_tickets(campaign_id);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_api_key
+ ON websocket_tickets(api_key_id);
"""
# ── Migration: v4 → v5 ────────────────────────────────────────────────────────
diff --git a/ares/db/websocket_tickets.py b/ares/db/websocket_tickets.py
new file mode 100644
index 0000000..5d065b0
--- /dev/null
+++ b/ares/db/websocket_tickets.py
@@ -0,0 +1,238 @@
+"""Transport-neutral contracts for one-time WebSocket tickets."""
+from __future__ import annotations
+
+import hashlib
+import re
+import secrets
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from enum import Enum
+
+WEBSOCKET_TICKET_TTL_SECONDS = 30
+WEBSOCKET_TICKET_ENTROPY_BYTES = 32
+WEBSOCKET_TICKET_PATTERN = re.compile(r"^[A-Za-z0-9_-]{43}$")
+
+_VALID_PRINCIPAL_ROLES = frozenset(
+ {"team_lead", "operator", "recon", "reporter"}
+)
+
+
+class WebSocketTicketCredentialKind(str, Enum):
+ BEARER = "bearer"
+ API_KEY = "api_key"
+
+
+def _canonical_identifier(value: str, field_name: str) -> str:
+ if not isinstance(value, str) or not value or value != value.strip():
+ raise ValueError(f"{field_name} must be a non-empty canonical string")
+ return value
+
+
+def normalize_utc_datetime(value: datetime) -> datetime:
+ """Return an aware UTC datetime without accepting an ambiguous naive value."""
+ if not isinstance(value, datetime) or value.tzinfo is None:
+ raise ValueError("timestamp must be timezone-aware")
+ offset = value.utcoffset()
+ if offset is None:
+ raise ValueError("timestamp must have a UTC offset")
+ return value.astimezone(timezone.utc)
+
+
+def format_sqlite_utc(value: datetime) -> str:
+ """Format a timestamp using the canonical millisecond UTC SQLite contract."""
+ return (
+ normalize_utc_datetime(value)
+ .isoformat(timespec="milliseconds")
+ .replace("+00:00", "Z")
+ )
+
+
+def parse_sqlite_utc(value: str) -> datetime:
+ """Parse only the canonical UTC representation emitted by this module."""
+ if not isinstance(value, str) or not value.endswith("Z"):
+ raise ValueError("timestamp must use canonical UTC format")
+ parsed = datetime.fromisoformat(value[:-1] + "+00:00")
+ normalized = normalize_utc_datetime(parsed)
+ if format_sqlite_utc(normalized) != value:
+ raise ValueError("timestamp must use canonical UTC format")
+ return normalized
+
+
+def generate_websocket_ticket() -> str:
+ raw_ticket = secrets.token_urlsafe(WEBSOCKET_TICKET_ENTROPY_BYTES)
+ if WEBSOCKET_TICKET_PATTERN.fullmatch(raw_ticket) is None:
+ raise RuntimeError("ticket generator returned a non-canonical value")
+ return raw_ticket
+
+
+def is_canonical_websocket_ticket(raw_ticket: object) -> bool:
+ return (
+ isinstance(raw_ticket, str)
+ and WEBSOCKET_TICKET_PATTERN.fullmatch(raw_ticket) is not None
+ )
+
+
+def hash_websocket_ticket(raw_ticket: str) -> str:
+ if not is_canonical_websocket_ticket(raw_ticket):
+ raise ValueError("ticket must use canonical format")
+ return hashlib.sha256(raw_ticket.encode("ascii")).hexdigest()
+
+
+def normalize_api_key_scopes(raw_scopes: object) -> tuple[str, ...]:
+ if not isinstance(raw_scopes, str):
+ return ()
+ return tuple(
+ scope
+ for scope in raw_scopes.replace(",", " ").split()
+ if scope
+ )
+
+
+def is_valid_websocket_principal_role(role: object) -> bool:
+ return isinstance(role, str) and role in _VALID_PRINCIPAL_ROLES
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class BearerTicketSource:
+ user_id: str = field(repr=False)
+ subject: str = field(repr=False)
+ jti: str = field(repr=False)
+ expires_at: datetime = field(repr=False)
+
+ def __post_init__(self) -> None:
+ object.__setattr__(
+ self, "user_id", _canonical_identifier(self.user_id, "user_id")
+ )
+ object.__setattr__(
+ self, "subject", _canonical_identifier(self.subject, "subject")
+ )
+ object.__setattr__(self, "jti", _canonical_identifier(self.jti, "jti"))
+ object.__setattr__(
+ self, "expires_at", normalize_utc_datetime(self.expires_at)
+ )
+
+ @property
+ def credential_kind(self) -> WebSocketTicketCredentialKind:
+ return WebSocketTicketCredentialKind.BEARER
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class ApiKeyTicketSource:
+ user_id: str = field(repr=False)
+ api_key_id: str = field(repr=False)
+
+ def __post_init__(self) -> None:
+ object.__setattr__(
+ self, "user_id", _canonical_identifier(self.user_id, "user_id")
+ )
+ object.__setattr__(
+ self,
+ "api_key_id",
+ _canonical_identifier(self.api_key_id, "api_key_id"),
+ )
+
+ @property
+ def credential_kind(self) -> WebSocketTicketCredentialKind:
+ return WebSocketTicketCredentialKind.API_KEY
+
+ @property
+ def required_scope(self) -> str:
+ return "read"
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class ConsumedWebSocketTicket:
+ campaign_id: str = field(repr=False)
+ user_id: str = field(repr=False)
+ credential_kind: WebSocketTicketCredentialKind
+ bearer_subject: str | None = field(default=None, repr=False)
+ bearer_jti: str | None = field(default=None, repr=False)
+ bearer_expires_at: datetime | None = field(default=None, repr=False)
+ api_key_id: str | None = field(default=None, repr=False)
+ required_scope: str | None = field(default=None, repr=False)
+
+ def __post_init__(self) -> None:
+ object.__setattr__(
+ self,
+ "campaign_id",
+ _canonical_identifier(self.campaign_id, "campaign_id"),
+ )
+ object.__setattr__(
+ self, "user_id", _canonical_identifier(self.user_id, "user_id")
+ )
+ if self.credential_kind is WebSocketTicketCredentialKind.BEARER:
+ if (
+ self.bearer_subject is None
+ or self.bearer_jti is None
+ or self.bearer_expires_at is None
+ or self.api_key_id is not None
+ or self.required_scope is not None
+ ):
+ raise ValueError("invalid bearer ticket handle")
+ object.__setattr__(
+ self,
+ "bearer_subject",
+ _canonical_identifier(self.bearer_subject, "bearer_subject"),
+ )
+ object.__setattr__(
+ self,
+ "bearer_jti",
+ _canonical_identifier(self.bearer_jti, "bearer_jti"),
+ )
+ object.__setattr__(
+ self,
+ "bearer_expires_at",
+ normalize_utc_datetime(self.bearer_expires_at),
+ )
+ elif self.credential_kind is WebSocketTicketCredentialKind.API_KEY:
+ if (
+ self.api_key_id is None
+ or self.required_scope != "read"
+ or self.bearer_subject is not None
+ or self.bearer_jti is not None
+ or self.bearer_expires_at is not None
+ ):
+ raise ValueError("invalid API-key ticket handle")
+ object.__setattr__(
+ self,
+ "api_key_id",
+ _canonical_identifier(self.api_key_id, "api_key_id"),
+ )
+ else:
+ raise ValueError("invalid ticket credential kind")
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class WebSocketTicketPrincipal:
+ user_id: str = field(repr=False)
+ username: str = field(repr=False)
+ role: str
+ credential_kind: WebSocketTicketCredentialKind
+ api_key_id: str | None = field(default=None, repr=False)
+ api_key_scopes: tuple[str, ...] = field(default=(), repr=False)
+
+ def __post_init__(self) -> None:
+ object.__setattr__(
+ self, "user_id", _canonical_identifier(self.user_id, "user_id")
+ )
+ object.__setattr__(
+ self, "username", _canonical_identifier(self.username, "username")
+ )
+ if not is_valid_websocket_principal_role(self.role):
+ raise ValueError("invalid principal role")
+ if self.credential_kind is WebSocketTicketCredentialKind.BEARER:
+ if self.api_key_id is not None or self.api_key_scopes:
+ raise ValueError("bearer principal cannot contain API-key state")
+ elif self.credential_kind is WebSocketTicketCredentialKind.API_KEY:
+ if self.api_key_id is None:
+ raise ValueError("API-key principal requires a key identifier")
+ object.__setattr__(
+ self,
+ "api_key_id",
+ _canonical_identifier(self.api_key_id, "api_key_id"),
+ )
+ object.__setattr__(
+ self, "api_key_scopes", tuple(self.api_key_scopes)
+ )
+ else:
+ raise ValueError("invalid principal credential kind")
diff --git a/migrations/versions/0007_add_websocket_tickets.py b/migrations/versions/0007_add_websocket_tickets.py
new file mode 100644
index 0000000..7ae2d0c
--- /dev/null
+++ b/migrations/versions/0007_add_websocket_tickets.py
@@ -0,0 +1,213 @@
+"""Add one-time WebSocket ticket storage.
+
+Revision ID: 0007
+Revises: 0006
+Create Date: 2026-07-28 00:00:00
+"""
+from __future__ import annotations
+
+import sqlalchemy as sa
+from alembic import op
+
+revision: str = "0007"
+down_revision: str | None = "0006"
+branch_labels: str | None = None
+depends_on: str | None = None
+
+
+def _timestamp_type(dialect: str) -> sa.types.TypeEngine:
+ if dialect == "postgresql":
+ return sa.DateTime(timezone=True)
+ if dialect == "sqlite":
+ return sa.Text()
+ raise RuntimeError("Unsupported WebSocket ticket migration dialect")
+
+
+def upgrade() -> None:
+ dialect = op.get_bind().dialect.name
+ timestamp_type = _timestamp_type(dialect)
+ is_postgresql = dialect == "postgresql"
+ hash_check = (
+ "ticket_hash ~ '^[0-9a-f]{64}$'"
+ if is_postgresql
+ else (
+ "length(ticket_hash)=64 "
+ "AND ticket_hash NOT GLOB '*[^0-9a-f]*'"
+ )
+ )
+ created_check = (
+ "created_at < expires_at"
+ if is_postgresql
+ else (
+ "strftime('%Y-%m-%dT%H:%M:%fZ', created_at) IS NOT NULL "
+ "AND strftime('%Y-%m-%dT%H:%M:%fZ', created_at)=created_at"
+ )
+ )
+ expires_check = (
+ "expires_at > created_at"
+ if is_postgresql
+ else (
+ "strftime('%Y-%m-%dT%H:%M:%fZ', expires_at) IS NOT NULL "
+ "AND strftime('%Y-%m-%dT%H:%M:%fZ', expires_at)=expires_at"
+ )
+ )
+ consumed_check = (
+ "consumed_at IS NULL OR consumed_at < expires_at"
+ if is_postgresql
+ else (
+ "consumed_at IS NULL OR ("
+ "strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at) IS NOT NULL "
+ "AND strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at)=consumed_at)"
+ )
+ )
+ bearer_timestamp_check = (
+ ""
+ if is_postgresql
+ else (
+ "AND "
+ "strftime("
+ "'%Y-%m-%dT%H:%M:%fZ', bearer_expires_at"
+ ") IS NOT NULL "
+ "AND strftime("
+ "'%Y-%m-%dT%H:%M:%fZ', bearer_expires_at"
+ ")=bearer_expires_at"
+ )
+ )
+ time_order_check = (
+ "expires_at > created_at "
+ "AND (consumed_at IS NULL OR consumed_at < expires_at)"
+ if is_postgresql
+ else (
+ "julianday(expires_at) > julianday(created_at) "
+ "AND (consumed_at IS NULL "
+ "OR julianday(consumed_at) < julianday(expires_at))"
+ )
+ )
+ trim_function = "btrim" if is_postgresql else "trim"
+ source_shape = f"""
+ (
+ credential_kind='bearer'
+ AND bearer_subject IS NOT NULL
+ AND length({trim_function}(bearer_subject)) > 0
+ AND bearer_subject={trim_function}(bearer_subject)
+ AND bearer_jti IS NOT NULL
+ AND length({trim_function}(bearer_jti)) > 0
+ AND bearer_jti={trim_function}(bearer_jti)
+ AND bearer_expires_at IS NOT NULL
+ {bearer_timestamp_check}
+ AND api_key_id IS NULL
+ AND required_scope IS NULL
+ )
+ OR
+ (
+ credential_kind='api_key'
+ AND bearer_subject IS NULL
+ AND bearer_jti IS NULL
+ AND bearer_expires_at IS NULL
+ AND api_key_id IS NOT NULL
+ AND length({trim_function}(api_key_id)) > 0
+ AND api_key_id={trim_function}(api_key_id)
+ AND required_scope='read'
+ )
+ """
+ finite_constraints = (
+ (
+ sa.CheckConstraint(
+ "bearer_expires_at IS NULL "
+ "OR isfinite(bearer_expires_at)",
+ name="ck_ws_ticket_bearer_expires_finite",
+ ),
+ sa.CheckConstraint(
+ "isfinite(created_at)",
+ name="ck_ws_ticket_created_finite",
+ ),
+ sa.CheckConstraint(
+ "isfinite(expires_at)",
+ name="ck_ws_ticket_expires_finite",
+ ),
+ sa.CheckConstraint(
+ "consumed_at IS NULL OR isfinite(consumed_at)",
+ name="ck_ws_ticket_consumed_finite",
+ ),
+ )
+ if is_postgresql
+ else ()
+ )
+
+ op.create_table(
+ "websocket_tickets",
+ sa.Column(
+ "ticket_hash", sa.Text(), primary_key=True, nullable=False
+ ),
+ sa.Column(
+ "campaign_id",
+ sa.Text(),
+ sa.ForeignKey(
+ "campaigns.id",
+ name="fk_ws_ticket_campaign",
+ ondelete="CASCADE",
+ ),
+ nullable=False,
+ ),
+ sa.Column(
+ "user_id",
+ sa.Text(),
+ sa.ForeignKey(
+ "users.id",
+ name="fk_ws_ticket_user",
+ ondelete="CASCADE",
+ ),
+ nullable=False,
+ ),
+ sa.Column("credential_kind", sa.Text(), nullable=False),
+ sa.Column("bearer_subject", sa.Text()),
+ sa.Column("bearer_jti", sa.Text()),
+ sa.Column("bearer_expires_at", timestamp_type),
+ sa.Column(
+ "api_key_id",
+ sa.Text(),
+ sa.ForeignKey(
+ "api_keys.id",
+ name="fk_ws_ticket_api_key",
+ ondelete="CASCADE",
+ ),
+ ),
+ sa.Column("required_scope", sa.Text()),
+ sa.Column("created_at", timestamp_type, nullable=False),
+ sa.Column("expires_at", timestamp_type, nullable=False),
+ sa.Column("consumed_at", timestamp_type),
+ sa.CheckConstraint(hash_check, name="ck_ws_ticket_hash"),
+ sa.CheckConstraint(
+ "credential_kind IN ('bearer', 'api_key')",
+ name="ck_ws_ticket_kind",
+ ),
+ sa.CheckConstraint(created_check, name="ck_ws_ticket_created_at"),
+ sa.CheckConstraint(expires_check, name="ck_ws_ticket_expires_at"),
+ sa.CheckConstraint(consumed_check, name="ck_ws_ticket_consumed_at"),
+ sa.CheckConstraint(
+ time_order_check,
+ name="ck_ws_ticket_time_order",
+ ),
+ sa.CheckConstraint(source_shape, name="ck_ws_ticket_source_shape"),
+ *finite_constraints,
+ )
+ op.create_index(
+ "idx_ws_tickets_expires", "websocket_tickets", ["expires_at"]
+ )
+ op.create_index(
+ "idx_ws_tickets_user", "websocket_tickets", ["user_id"]
+ )
+ op.create_index(
+ "idx_ws_tickets_campaign", "websocket_tickets", ["campaign_id"]
+ )
+ op.create_index(
+ "idx_ws_tickets_api_key", "websocket_tickets", ["api_key_id"]
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("idx_ws_tickets_api_key", table_name="websocket_tickets")
+ op.drop_index("idx_ws_tickets_campaign", table_name="websocket_tickets")
+ op.drop_index("idx_ws_tickets_user", table_name="websocket_tickets")
+ op.drop_index("idx_ws_tickets_expires", table_name="websocket_tickets")
+ op.drop_table("websocket_tickets")
diff --git a/tests/integration/test_postgres_websocket_tickets.py b/tests/integration/test_postgres_websocket_tickets.py
new file mode 100644
index 0000000..0164da9
--- /dev/null
+++ b/tests/integration/test_postgres_websocket_tickets.py
@@ -0,0 +1,3978 @@
+"""Real PostgreSQL integration coverage for one-time WebSocket tickets."""
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import multiprocessing
+import os
+import re
+import sys
+from collections.abc import AsyncIterator, Awaitable, Callable
+from contextlib import asynccontextmanager
+from dataclasses import dataclass, field, replace
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import patch
+from urllib.parse import quote
+from uuid import uuid4
+
+import pytest
+
+from ares.db import postgres as postgres_module
+from ares.db.postgres import PostgresDatabase
+from ares.db.websocket_tickets import (
+ ApiKeyTicketSource,
+ BearerTicketSource,
+ WebSocketTicketCredentialKind,
+ generate_websocket_ticket,
+ hash_websocket_ticket,
+)
+
+_POSTGRES_ENV = (
+ "ARES_TEST_POSTGRES_HOST",
+ "ARES_TEST_POSTGRES_PORT",
+ "ARES_TEST_POSTGRES_USER",
+ "ARES_TEST_POSTGRES_DB",
+)
+_SAFE_DATABASE_NAME = re.compile(r"^[a-z][a-z0-9_]+$")
+_SAFE_EXCEPTION_TYPE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
+_POSTGRES_OPERATION_TIMEOUT_SECONDS = 15.0
+_MIGRATION_PROCESS_TIMEOUT_SECONDS = 45.0
+_MIGRATION_ACTIONS = frozenset({"upgrade", "downgrade"})
+_MIGRATION_REVISIONS = frozenset({"0006", "0007"})
+_OWNED_MIGRATION_PROCESSES: set[Any] = set()
+
+
+@dataclass(frozen=True, slots=True, eq=False, repr=False)
+class _PostgresHarness:
+ database: PostgresDatabase = field(repr=False)
+ database_name: str = field(repr=False)
+
+
+def _require_fixed(condition: bool, message: str) -> None:
+ if not condition:
+ pytest.fail(message, pytrace=False)
+
+
+def _postgres_test_config() -> dict[str, str | int]:
+ present = {name for name in _POSTGRES_ENV if name in os.environ}
+ if not present:
+ pytest.skip("real PostgreSQL test environment is not configured")
+ if present != set(_POSTGRES_ENV):
+ pytest.fail(
+ "Incomplete PostgreSQL test environment",
+ pytrace=False,
+ )
+ values = {name: os.environ[name] for name in _POSTGRES_ENV}
+ if any(not value or value != value.strip() for value in values.values()):
+ pytest.fail("Invalid PostgreSQL test environment", pytrace=False)
+ raw_port = values["ARES_TEST_POSTGRES_PORT"]
+ if re.fullmatch(r"[1-9][0-9]{0,4}", raw_port) is None:
+ pytest.fail("PostgreSQL test port is invalid", pytrace=False)
+ port = int(raw_port)
+ if not 1 <= port <= 65535:
+ pytest.fail("PostgreSQL test port is outside its valid range", pytrace=False)
+ return {
+ "host": values["ARES_TEST_POSTGRES_HOST"],
+ "port": port,
+ "user": values["ARES_TEST_POSTGRES_USER"],
+ "database": values["ARES_TEST_POSTGRES_DB"],
+ }
+
+
+def _runtime_dsn(config: dict[str, str | int], database: str) -> str:
+ host = str(config["host"])
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ return (
+ "postgresql://"
+ f"{quote(str(config['user']), safe='')}@"
+ f"{host}:{config['port']}/"
+ f"{quote(database, safe='')}"
+ )
+
+
+def _database_for_target(
+ database_name: str,
+ *,
+ pool_min: int = 1,
+ pool_max: int = 2,
+) -> PostgresDatabase:
+ return PostgresDatabase(
+ _runtime_dsn(_postgres_test_config(), database_name),
+ pool_min=pool_min,
+ pool_max=pool_max,
+ )
+
+
+def _set_complete_postgres_config(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ARES_TEST_POSTGRES_HOST", "127.0.0.1")
+ monkeypatch.setenv("ARES_TEST_POSTGRES_PORT", "5432")
+ monkeypatch.setenv("ARES_TEST_POSTGRES_USER", "synthetic_runner")
+ monkeypatch.setenv("ARES_TEST_POSTGRES_DB", "synthetic_control")
+
+
+def test_ticket_postgres_config_skips_only_when_canonical_names_are_absent(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ for name in _POSTGRES_ENV:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("ARES_TEST_POSTGRES_DATABASE", "ignored_alias")
+ monkeypatch.setenv("ARES_DATABASE_URL", "ignored_fallback")
+ skipped = False
+ try:
+ _postgres_test_config()
+ except pytest.skip.Exception:
+ skipped = True
+ _require_fixed(
+ skipped,
+ "noncanonical PostgreSQL configuration prevented the intentional skip",
+ )
+
+
+ ("name", "value"),
+ [
+ pytest.param("ARES_TEST_POSTGRES_HOST", "", id="empty-host"),
+ pytest.param("ARES_TEST_POSTGRES_HOST", " ", id="blank-host"),
+ pytest.param("ARES_TEST_POSTGRES_HOST", " host", id="padded-host"),
+ pytest.param("ARES_TEST_POSTGRES_PORT", "not-a-port", id="invalid-port"),
+ pytest.param("ARES_TEST_POSTGRES_PORT", "+5432", id="signed-port"),
+ pytest.param("ARES_TEST_POSTGRES_PORT", "05432", id="leading-zero-port"),
+ pytest.param("ARES_TEST_POSTGRES_PORT", "5432", id="unicode-port"),
+ pytest.param("ARES_TEST_POSTGRES_PORT", "0", id="low-port"),
+ pytest.param("ARES_TEST_POSTGRES_PORT", "65536", id="high-port"),
+ pytest.param("ARES_TEST_POSTGRES_USER", "", id="empty-user"),
+ pytest.param("ARES_TEST_POSTGRES_DB", " ", id="blank-database"),
+ ],
+)
+def test_ticket_postgres_config_rejects_present_invalid_values(
+ monkeypatch: pytest.MonkeyPatch,
+ name: str,
+ value: str,
+) -> None:
+ _set_complete_postgres_config(monkeypatch)
+ monkeypatch.setenv(name, value)
+ failed = False
+ try:
+ _postgres_test_config()
+ except pytest.fail.Exception:
+ failed = True
+ _require_fixed(failed, "invalid PostgreSQL configuration was accepted")
+
+
+def test_ticket_postgres_config_rejects_partial_presence(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ for name in _POSTGRES_ENV:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("ARES_TEST_POSTGRES_HOST", "127.0.0.1")
+ failed = False
+ try:
+ _postgres_test_config()
+ except pytest.fail.Exception:
+ failed = True
+ _require_fixed(failed, "partial PostgreSQL configuration was accepted")
+
+
+def test_ticket_postgres_config_accepts_complete_canonical_names(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _set_complete_postgres_config(monkeypatch)
+ config = _postgres_test_config()
+ reduced = (
+ set(config) == {"host", "port", "user", "database"}
+ and config["port"] == 5432
+ and all(config[name] for name in ("host", "user", "database"))
+ )
+ _require_fixed(reduced, "complete canonical PostgreSQL configuration was rejected")
+
+
+def test_ticket_harness_representation_is_secret_safe() -> None:
+ marker = "synthetic-confidential-marker"
+ harness = _PostgresHarness(
+ database=PostgresDatabase(marker),
+ database_name=f"ares_ws_ticket_{uuid4().hex}",
+ )
+ marker_absent = marker not in repr(harness)
+ _require_fixed(marker_absent, "PostgreSQL harness representation exposed state")
+
+
+class _StartupPool:
+ def __init__(self) -> None:
+ self.close_count = 0
+
+ async def close(self) -> None:
+ self.close_count += 1
+
+
+async def test_postgres_connect_closes_failed_pool_and_can_recover(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ pools = (_StartupPool(), _StartupPool())
+ pool_index = 0
+
+ async def _create_pool(*_args: object, **_kwargs: object) -> _StartupPool:
+ nonlocal pool_index
+ selected = pools[pool_index]
+ pool_index += 1
+ return selected
+
+ primary = RuntimeError()
+ initialization_count = 0
+
+ async def _initialize() -> None:
+ nonlocal initialization_count
+ initialization_count += 1
+ if initialization_count == 1:
+ raise primary
+
+ monkeypatch.setitem(
+ sys.modules,
+ "asyncpg",
+ SimpleNamespace(create_pool=_create_pool),
+ )
+ database = PostgresDatabase("synthetic")
+ database._init_schema = _initialize
+ observed: BaseException | None = None
+ with patch.object(postgres_module.logger, "info", return_value=None):
+ try:
+ await database.connect()
+ except Exception as exc:
+ observed = exc
+ first_state = (
+ observed is primary
+ and pools[0].close_count == 1
+ and database._pool is None
+ )
+ recovered = await database.connect()
+ await database.close()
+ recovered_state = (
+ recovered is database
+ and database._pool is pools[1]
+ and pools[1].close_count == 1
+ and initialization_count == 2
+ )
+ _require_fixed(
+ first_state and recovered_state,
+ "PostgreSQL startup pool cleanup/recovery contract failed",
+ )
+
+
+ ("first", "terminal", "exit_code", "eof"),
+ [
+ pytest.param(("OK",), ("OK",), 0, True, id="ok-before-ready"),
+ pytest.param(("READY",), ("READY",), 0, True, id="duplicate-ready"),
+ pytest.param(("READY",), ("ERROR", "RuntimeError"), 0, True, id="error"),
+ pytest.param(("READY",), ("OK",), 1, True, id="success-then-crash"),
+ pytest.param(("READY",), ("OK",), 0, False, id="trailing-frame"),
+ pytest.param(("READY", "extra"), ("OK",), 0, True, id="malformed-ready"),
+ pytest.param(("READY",), ("OK", "extra"), 0, True, id="malformed-terminal"),
+ ],
+)
+def test_ticket_migration_protocol_rejects_invalid_sequences(
+ first: object,
+ terminal: object,
+ exit_code: object,
+ eof: bool,
+) -> None:
+ accepted = _migration_protocol_succeeded(first, terminal, exit_code, eof)
+ _require_fixed(not accepted, "invalid migration child protocol was accepted")
+
+
+def test_ticket_migration_protocol_accepts_one_complete_sequence() -> None:
+ accepted = _migration_protocol_succeeded(
+ ("READY",),
+ ("OK",),
+ 0,
+ True,
+ )
+ _require_fixed(accepted, "valid migration child protocol was rejected")
+
+
+def _sanitized_exception_type(exc: BaseException) -> str:
+ name = type(exc).__name__
+ return name if _SAFE_EXCEPTION_TYPE.fullmatch(name) else "Exception"
+
+
+def test_ticket_migration_exception_type_is_reduced_to_a_safe_frame() -> None:
+ unsafe_exception = type("unsafe exception", (Exception,), {})
+ reduced = _sanitized_exception_type(unsafe_exception())
+ _require_fixed(
+ reduced == "Exception",
+ "migration child exception type was not sanitized",
+ )
+
+
+class _SettlementProcess:
+ def __init__(self, states: tuple[bool, ...]) -> None:
+ self._states = list(states)
+ self._last_state = states[-1]
+ self.actions: list[str] = []
+
+ def is_alive(self) -> bool:
+ if self._states:
+ self._last_state = self._states.pop(0)
+ return self._last_state
+
+ def terminate(self) -> None:
+ self.actions.append("terminate")
+
+ def kill(self) -> None:
+ self.actions.append("kill")
+
+ def join(self, *, timeout: int) -> None:
+ self.actions.append(f"join-{timeout}")
+
+
+def test_ticket_migration_settlement_escalates_to_kill() -> None:
+ process = _SettlementProcess((True, True, False))
+ settled = _settle_migration_process(process)
+ _require_fixed(
+ settled
+ and tuple(process.actions)
+ == ("terminate", "join-2", "kill", "join-2"),
+ "migration child settlement did not use the bounded escalation order",
+ )
+
+
+def test_ticket_migration_settlement_refuses_unproved_death() -> None:
+ process = _SettlementProcess((True, True, True))
+ settled = _settle_migration_process(process)
+ _require_fixed(
+ not settled,
+ "migration child settlement accepted a live process",
+ )
+
+
+def _sanitized_setup_failure(action: str, exc: Exception) -> RuntimeError:
+ return RuntimeError(
+ f"PostgreSQL ticket setup failed [{action}: {type(exc).__name__}]"
+ )
+
+
+async def _bounded_operation(
+ action: str,
+ operation: Awaitable[Any],
+) -> Any:
+ try:
+ return await asyncio.wait_for(
+ operation,
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ except Exception as exc:
+ raise _sanitized_setup_failure(action, exc) from None
+
+
+async def _attempt_cleanup(
+ action: str,
+ cleanup: Callable[[], Awaitable[object]],
+ failures: list[str],
+) -> None:
+ try:
+ await asyncio.wait_for(
+ cleanup(),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ except Exception as exc:
+ failures.append(f"{action}: {type(exc).__name__}")
+
+
+def _migration_child_config() -> dict[str, str | int]:
+ if any(name not in os.environ for name in _POSTGRES_ENV):
+ raise RuntimeError()
+ values = {name: os.environ[name] for name in _POSTGRES_ENV}
+ if any(not value or value != value.strip() for value in values.values()):
+ raise RuntimeError()
+ raw_port = values["ARES_TEST_POSTGRES_PORT"]
+ if re.fullmatch(r"[1-9][0-9]{0,4}", raw_port) is None:
+ raise RuntimeError()
+ port = int(raw_port)
+ if not 1 <= port <= 65535:
+ raise RuntimeError()
+ return {
+ "host": values["ARES_TEST_POSTGRES_HOST"],
+ "port": port,
+ "user": values["ARES_TEST_POSTGRES_USER"],
+ "database": values["ARES_TEST_POSTGRES_DB"],
+ }
+
+
+def _ticket_migration_child(
+ database_name: str,
+ action: str,
+ revision: str,
+ control: Any,
+) -> None:
+ terminal_sent = False
+ ready_sent = False
+ devnull = -1
+ try:
+ devnull = os.open(os.devnull, os.O_WRONLY)
+ os.dup2(devnull, 1)
+ os.dup2(devnull, 2)
+
+ from alembic import command
+ from alembic.config import Config
+
+ if (
+ _SAFE_DATABASE_NAME.fullmatch(database_name) is None
+ or not database_name.startswith("ares_ws_ticket_")
+ or action not in _MIGRATION_ACTIONS
+ or revision not in _MIGRATION_REVISIONS
+ ):
+ raise RuntimeError()
+ config_values = _migration_child_config()
+ migration_url = _runtime_dsn(
+ config_values,
+ database_name,
+ ).replace("postgresql://", "postgresql+asyncpg://", 1)
+ alembic_config = Config("alembic.ini")
+ alembic_config.cmd_opts = SimpleNamespace(
+ x=[f"db_url={migration_url}"],
+ )
+ migration_action = getattr(command, action)
+ control.send(("READY",))
+ ready_sent = True
+ if control.recv() != ("GO",):
+ raise RuntimeError()
+ migration_action(alembic_config, revision)
+ control.send(("OK",))
+ terminal_sent = True
+ except Exception as exc:
+ if not terminal_sent:
+ frame = "ERROR" if ready_sent else "SETUP_ERROR"
+ with contextlib.suppress(Exception):
+ control.send((frame, _sanitized_exception_type(exc)))
+ finally:
+ if devnull >= 0:
+ with contextlib.suppress(OSError):
+ os.close(devnull)
+ with contextlib.suppress(Exception):
+ control.close()
+
+
+def _process_is_alive(process: Any) -> bool | None:
+ try:
+ return bool(process.is_alive())
+ except (AssertionError, ValueError):
+ return None
+
+
+def _settle_migration_process(process: Any) -> bool:
+ alive = _process_is_alive(process)
+ if alive is None:
+ return getattr(process, "pid", None) is None
+ if alive:
+ process.terminate()
+ process.join(timeout=2)
+ alive = _process_is_alive(process)
+ if alive:
+ process.kill()
+ process.join(timeout=2)
+ alive = _process_is_alive(process)
+ return alive is False
+
+
+def _migration_protocol_succeeded(
+ first: object,
+ terminal: object,
+ exit_code: object,
+ eof: bool,
+) -> bool:
+ return (
+ first == ("READY",)
+ and terminal == ("OK",)
+ and exit_code == 0
+ and eof
+ )
+
+
+def _run_ticket_migration(
+ database_name: str,
+ action: str,
+ revision: str,
+) -> None:
+ context = multiprocessing.get_context("spawn")
+ parent = None
+ child = None
+ process = None
+ start_attempted = False
+ completed = False
+ try:
+ parent, child = context.Pipe(duplex=True)
+ process = context.Process(
+ target=_ticket_migration_child,
+ args=(database_name, action, revision, child),
+ )
+ _OWNED_MIGRATION_PROCESSES.add(process)
+ start_attempted = True
+ process.start()
+ child.close()
+ if not parent.poll(_MIGRATION_PROCESS_TIMEOUT_SECONDS):
+ raise RuntimeError("PostgreSQL ticket migration process timed out")
+ first = parent.recv()
+ if first != ("READY",):
+ raise RuntimeError("PostgreSQL ticket migration setup failed")
+ parent.send(("GO",))
+ if not parent.poll(_MIGRATION_PROCESS_TIMEOUT_SECONDS):
+ raise RuntimeError("PostgreSQL ticket migration process timed out")
+ terminal = parent.recv()
+ process.join(timeout=2)
+ if process.is_alive():
+ raise RuntimeError("PostgreSQL ticket migration process did not exit")
+ eof = False
+ if parent.poll(1):
+ try:
+ parent.recv()
+ except EOFError:
+ eof = True
+ completed = _migration_protocol_succeeded(
+ first,
+ terminal,
+ process.exitcode,
+ eof,
+ )
+ if not completed:
+ raise RuntimeError("PostgreSQL ticket migration action failed")
+ finally:
+ settled = process is None
+ if process is not None:
+ if completed:
+ settled = _process_is_alive(process) is False
+ elif start_attempted:
+ settled = _settle_migration_process(process)
+ if not settled:
+ raise RuntimeError(
+ "PostgreSQL ticket migration process could not be settled"
+ ) from None
+ if parent is not None:
+ with contextlib.suppress(Exception):
+ parent.close()
+ if child is not None:
+ with contextlib.suppress(Exception):
+ child.close()
+ if process is not None and settled:
+ with contextlib.suppress(Exception):
+ process.close()
+ _OWNED_MIGRATION_PROCESSES.discard(process)
+
+
+@asynccontextmanager
+async def _postgres_harness(
+ *,
+ initialize_runtime: bool = True,
+) -> AsyncIterator[_PostgresHarness]:
+ config = _postgres_test_config()
+ try:
+ import asyncpg
+ except ImportError:
+ pytest.fail(
+ "asyncpg is required for configured PostgreSQL tests",
+ pytrace=False,
+ )
+
+ test_database = f"ares_ws_ticket_{uuid4().hex}"
+ _require_fixed(
+ _SAFE_DATABASE_NAME.fullmatch(test_database) is not None,
+ "generated PostgreSQL database identifier was unsafe",
+ )
+ _require_fixed(
+ test_database != config["database"],
+ "generated PostgreSQL database identifier collided",
+ )
+
+ admin = None
+ database = None
+ creation_attempted = False
+ cleanup_failures: list[str] = []
+ try:
+ try:
+ admin = await _bounded_operation(
+ "admin-connect",
+ asyncpg.connect(
+ host=config["host"],
+ port=config["port"],
+ user=config["user"],
+ database=config["database"],
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ ),
+ )
+ except Exception as exc:
+ raise _sanitized_setup_failure("admin-connect", exc) from None
+
+ creation_attempted = True
+ try:
+ await _bounded_operation(
+ "database-create",
+ admin.execute(f'CREATE DATABASE "{test_database}"'),
+ )
+ except Exception as exc:
+ raise _sanitized_setup_failure("database-create", exc) from None
+
+ dsn = _runtime_dsn(config, test_database)
+ database = PostgresDatabase(dsn, pool_min=1, pool_max=8)
+ if initialize_runtime:
+ try:
+ await _bounded_operation(
+ "runtime-initialize",
+ database.connect(),
+ )
+ except Exception as exc:
+ raise _sanitized_setup_failure("runtime-initialize", exc) from None
+ yield _PostgresHarness(
+ database=database,
+ database_name=test_database,
+ )
+ finally:
+ primary_failure = sys.exception()
+ workers_unsettled = bool(_OWNED_MIGRATION_PROCESSES)
+ if workers_unsettled:
+ cleanup_failures.append("migration-worker: UnsettledProcess")
+ if database is not None:
+ await _attempt_cleanup(
+ "close-runtime-pool",
+ database.close,
+ cleanup_failures,
+ )
+ if creation_attempted and admin is not None and not workers_unsettled:
+
+ async def _drop_database() -> None:
+ await admin.execute(
+ f'DROP DATABASE IF EXISTS "{test_database}" WITH (FORCE)'
+ )
+
+ await _attempt_cleanup(
+ "drop-test-database",
+ _drop_database,
+ cleanup_failures,
+ )
+ if admin is not None:
+ await _attempt_cleanup(
+ "close-admin-connection",
+ admin.close,
+ cleanup_failures,
+ )
+ if cleanup_failures:
+ if primary_failure is not None:
+ for failure in cleanup_failures:
+ primary_failure.add_note(
+ f"PostgreSQL ticket cleanup failure [{failure}]"
+ )
+ else:
+ raise RuntimeError(
+ "PostgreSQL ticket cleanup failed: "
+ + "; ".join(cleanup_failures)
+ ) from None
+
+
+async def _seed_identity(
+ database: PostgresDatabase,
+ *,
+ scopes: str = "read",
+) -> tuple[str, str, str, str, str]:
+ username = f"ws_ticket_{uuid4().hex}"
+ original_info = postgres_module.logger.info
+
+ def _suppress_identity_log(event: str, **values: object) -> Any:
+ if event == "user_created":
+ return None
+ return original_info(event, **values)
+
+ with patch.object(
+ postgres_module.logger,
+ "info",
+ new=_suppress_identity_log,
+ ):
+ user_id = await database.create_user(
+ username,
+ "synthetic-test-password",
+ "operator",
+ )
+ campaign_id = f"campaign-{uuid4().hex}"
+ other_campaign_id = f"campaign-{uuid4().hex}"
+ async with database._pool.acquire() as connection:
+ await connection.executemany(
+ """
+ INSERT INTO campaigns(id, name, operator)
+ VALUES($1, $2, $3)
+ """,
+ (
+ (campaign_id, "Ticket campaign", username),
+ (other_campaign_id, "Other campaign", username),
+ ),
+ )
+ api_key_id = (
+ await database.create_api_key(
+ user_id,
+ "ticket-key",
+ scopes=scopes,
+ )
+ )[0]
+ return user_id, username, campaign_id, other_campaign_id, api_key_id
+
+
+def _bearer_source(user_id: str, username: str) -> BearerTicketSource:
+ return BearerTicketSource(
+ user_id=user_id,
+ subject=username,
+ jti=f"ticket-jti-{uuid4().hex}",
+ expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
+ )
+
+
+_EXPECTED_TICKET_COLUMNS = (
+ ("ticket_hash", "text", True, "", "", True, None),
+ ("campaign_id", "text", True, "", "", True, None),
+ ("user_id", "text", True, "", "", True, None),
+ ("credential_kind", "text", True, "", "", True, None),
+ ("bearer_subject", "text", False, "", "", True, None),
+ ("bearer_jti", "text", False, "", "", True, None),
+ (
+ "bearer_expires_at",
+ "timestamp with time zone",
+ False,
+ "",
+ "",
+ True,
+ None,
+ ),
+ ("api_key_id", "text", False, "", "", True, None),
+ ("required_scope", "text", False, "", "", True, None),
+ (
+ "created_at",
+ "timestamp with time zone",
+ True,
+ "",
+ "",
+ True,
+ None,
+ ),
+ (
+ "expires_at",
+ "timestamp with time zone",
+ True,
+ "",
+ "",
+ True,
+ None,
+ ),
+ (
+ "consumed_at",
+ "timestamp with time zone",
+ False,
+ "",
+ "",
+ True,
+ None,
+ ),
+)
+
+_EXPECTED_TICKET_CHECKS = (
+ (
+ "ck_ws_ticket_bearer_expires_finite",
+ "CHECK (bearer_expires_at IS NULL OR isfinite(bearer_expires_at))",
+ ),
+ (
+ "ck_ws_ticket_consumed_at",
+ "CHECK (consumed_at IS NULL OR consumed_at < expires_at)",
+ ),
+ (
+ "ck_ws_ticket_consumed_finite",
+ "CHECK (consumed_at IS NULL OR isfinite(consumed_at))",
+ ),
+ ("ck_ws_ticket_created_at", "CHECK (created_at < expires_at)"),
+ ("ck_ws_ticket_created_finite", "CHECK (isfinite(created_at))"),
+ ("ck_ws_ticket_expires_at", "CHECK (expires_at > created_at)"),
+ ("ck_ws_ticket_expires_finite", "CHECK (isfinite(expires_at))"),
+ (
+ "ck_ws_ticket_hash",
+ "CHECK (ticket_hash ~ '^[0-9a-f]{64}$'::text)",
+ ),
+ (
+ "ck_ws_ticket_kind",
+ "CHECK (credential_kind = ANY "
+ "(ARRAY['bearer'::text, 'api_key'::text]))",
+ ),
+ (
+ "ck_ws_ticket_source_shape",
+ "CHECK (credential_kind = 'bearer'::text "
+ "AND bearer_subject IS NOT NULL "
+ "AND length(btrim(bearer_subject)) > 0 "
+ "AND bearer_subject = btrim(bearer_subject) "
+ "AND bearer_jti IS NOT NULL "
+ "AND length(btrim(bearer_jti)) > 0 "
+ "AND bearer_jti = btrim(bearer_jti) "
+ "AND bearer_expires_at IS NOT NULL "
+ "AND api_key_id IS NULL "
+ "AND required_scope IS NULL "
+ "OR credential_kind = 'api_key'::text "
+ "AND bearer_subject IS NULL "
+ "AND bearer_jti IS NULL "
+ "AND bearer_expires_at IS NULL "
+ "AND api_key_id IS NOT NULL "
+ "AND length(btrim(api_key_id)) > 0 "
+ "AND api_key_id = btrim(api_key_id) "
+ "AND required_scope = 'read'::text)",
+ ),
+ (
+ "ck_ws_ticket_time_order",
+ "CHECK (expires_at > created_at AND "
+ "(consumed_at IS NULL OR consumed_at < expires_at))",
+ ),
+)
+
+_EXPECTED_TICKET_FOREIGN_KEYS = (
+ (
+ "fk_ws_ticket_api_key",
+ ("api_key_id",),
+ "api_keys",
+ ("id",),
+ "a",
+ "c",
+ ),
+ (
+ "fk_ws_ticket_campaign",
+ ("campaign_id",),
+ "campaigns",
+ ("id",),
+ "a",
+ "c",
+ ),
+ (
+ "fk_ws_ticket_user",
+ ("user_id",),
+ "users",
+ ("id",),
+ "a",
+ "c",
+ ),
+)
+
+_EXPECTED_TICKET_INDEXES = (
+ (
+ "idx_ws_tickets_api_key",
+ "btree",
+ False,
+ False,
+ True,
+ True,
+ True,
+ 1,
+ 1,
+ ("api_key_id",),
+ (0,),
+ ("text_ops",),
+ (True,),
+ None,
+ None,
+ ),
+ (
+ "idx_ws_tickets_campaign",
+ "btree",
+ False,
+ False,
+ True,
+ True,
+ True,
+ 1,
+ 1,
+ ("campaign_id",),
+ (0,),
+ ("text_ops",),
+ (True,),
+ None,
+ None,
+ ),
+ (
+ "idx_ws_tickets_expires",
+ "btree",
+ False,
+ False,
+ True,
+ True,
+ True,
+ 1,
+ 1,
+ ("expires_at",),
+ (0,),
+ ("timestamptz_ops",),
+ (True,),
+ None,
+ None,
+ ),
+ (
+ "idx_ws_tickets_user",
+ "btree",
+ False,
+ False,
+ True,
+ True,
+ True,
+ 1,
+ 1,
+ ("user_id",),
+ (0,),
+ ("text_ops",),
+ (True,),
+ None,
+ None,
+ ),
+ (
+ "websocket_tickets_pkey",
+ "btree",
+ True,
+ True,
+ True,
+ True,
+ True,
+ 1,
+ 1,
+ ("ticket_hash",),
+ (0,),
+ ("text_ops",),
+ (True,),
+ None,
+ None,
+ ),
+)
+
+_EXPECTED_TICKET_INDEX_IDENTITIES = (
+ (
+ "idx_ws_tickets_api_key",
+ "i",
+ "p",
+ False,
+ ("text_ops",),
+ ("pg_catalog",),
+ ),
+ (
+ "idx_ws_tickets_campaign",
+ "i",
+ "p",
+ False,
+ ("text_ops",),
+ ("pg_catalog",),
+ ),
+ (
+ "idx_ws_tickets_expires",
+ "i",
+ "p",
+ False,
+ ("timestamptz_ops",),
+ ("pg_catalog",),
+ ),
+ (
+ "idx_ws_tickets_user",
+ "i",
+ "p",
+ False,
+ ("text_ops",),
+ ("pg_catalog",),
+ ),
+ (
+ "websocket_tickets_pkey",
+ "i",
+ "p",
+ False,
+ ("text_ops",),
+ ("pg_catalog",),
+ ),
+)
+
+
+async def _ticket_catalog_fingerprint(connection: Any) -> dict[str, object]:
+ relation = await connection.fetchrow(
+ """
+ SELECT rel.oid::bigint AS table_oid,
+ nsp.oid::bigint AS schema_oid,
+ nsp.nspname AS schema_name,
+ rel.relkind,
+ rel.relpersistence,
+ rel.relispartition,
+ rel.relrowsecurity,
+ rel.relforcerowsecurity,
+ (
+ SELECT COUNT(*) FROM pg_inherits AS inherited
+ WHERE inherited.inhrelid=rel.oid
+ ) AS parent_count,
+ (
+ SELECT COUNT(*) FROM pg_inherits AS inherited
+ WHERE inherited.inhparent=rel.oid
+ ) AS child_count,
+ (
+ SELECT COUNT(*) FROM pg_policy AS policy
+ WHERE policy.polrelid=rel.oid
+ ) AS policy_count,
+ (
+ SELECT COUNT(*) FROM pg_trigger AS trg
+ WHERE trg.tgrelid=rel.oid
+ AND NOT trg.tgisinternal
+ ) AS user_trigger_count,
+ (
+ SELECT COUNT(*) FROM pg_rewrite AS rewrite
+ WHERE rewrite.ev_class=rel.oid
+ ) AS user_rule_count
+ FROM pg_class AS rel
+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace
+ WHERE nsp.nspname=current_schema()
+ AND rel.relname='websocket_tickets'
+ """
+ )
+ if relation is None:
+ return {"relation": None}
+ table_oid = int(relation["table_oid"])
+ schema_oid = int(relation["schema_oid"])
+ column_rows = await connection.fetch(
+ """
+ SELECT att.attname AS name,
+ pg_catalog.format_type(att.atttypid, att.atttypmod) AS type,
+ att.attnotnull,
+ att.attidentity,
+ att.attgenerated,
+ att.attcollation=typ.typcollation AS collation_is_default,
+ pg_get_expr(def.adbin, def.adrelid) AS default_value
+ FROM pg_attribute AS att
+ JOIN pg_type AS typ ON typ.oid=att.atttypid
+ LEFT JOIN pg_attrdef AS def
+ ON def.adrelid=att.attrelid AND def.adnum=att.attnum
+ WHERE att.attrelid=$1::oid
+ AND att.attnum > 0
+ AND NOT att.attisdropped
+ ORDER BY att.attnum
+ """,
+ table_oid,
+ )
+ constraint_rows = await connection.fetch(
+ """
+ SELECT con.conname, con.contype,
+ con.conrelid::bigint AS table_oid,
+ con.confrelid::bigint AS referenced_oid,
+ con.conindid::bigint AS constraint_index_oid,
+ con.convalidated,
+ con.condeferrable, con.condeferred,
+ pg_get_constraintdef(con.oid, true) AS definition,
+ ref_nsp.oid::bigint AS referenced_schema_oid,
+ ref_nsp.nspname=current_schema() AS reference_is_local,
+ ref_rel.relname AS referenced_table,
+ ARRAY(
+ SELECT local_att.attname
+ FROM unnest(con.conkey) WITH ORDINALITY AS key(attnum, ordinality)
+ JOIN pg_attribute AS local_att
+ ON local_att.attrelid=con.conrelid
+ AND local_att.attnum=key.attnum
+ ORDER BY key.ordinality
+ ) AS local_columns,
+ ARRAY(
+ SELECT remote_att.attname
+ FROM unnest(con.confkey) WITH ORDINALITY AS key(attnum, ordinality)
+ JOIN pg_attribute AS remote_att
+ ON remote_att.attrelid=con.confrelid
+ AND remote_att.attnum=key.attnum
+ ORDER BY key.ordinality
+ ) AS remote_columns,
+ con.confupdtype, con.confdeltype
+ FROM pg_constraint AS con
+ LEFT JOIN pg_class AS ref_rel ON ref_rel.oid=con.confrelid
+ LEFT JOIN pg_namespace AS ref_nsp ON ref_nsp.oid=ref_rel.relnamespace
+ WHERE con.conrelid=$1::oid
+ ORDER BY con.conname
+ """,
+ table_oid,
+ )
+ index_rows = await connection.fetch(
+ """
+ SELECT ind.indrelid::bigint AS table_oid,
+ ind.indexrelid::bigint AS index_oid,
+ idx.relnamespace::bigint AS index_schema_oid,
+ idx_nsp.nspname=current_schema() AS index_schema_is_local,
+ idx.relname AS name,
+ idx.relkind,
+ idx.relpersistence,
+ idx.relispartition,
+ am.amname,
+ ind.indisunique, ind.indisprimary,
+ ind.indisvalid, ind.indisready, ind.indislive,
+ ind.indnkeyatts, ind.indnatts,
+ ARRAY(
+ SELECT CASE WHEN key.attnum=0 THEN NULL ELSE att.attname END
+ FROM unnest(ind.indkey) WITH ORDINALITY AS key(attnum, ordinality)
+ LEFT JOIN pg_attribute AS att
+ ON att.attrelid=ind.indrelid AND att.attnum=key.attnum
+ ORDER BY key.ordinality
+ ) AS columns,
+ ARRAY(
+ SELECT option
+ FROM unnest(ind.indoption) WITH ORDINALITY AS item(option, ordinality)
+ ORDER BY item.ordinality
+ ) AS options,
+ ARRAY(
+ SELECT opc.opcname
+ FROM unnest(ind.indclass) WITH ORDINALITY AS item(opclass, ordinality)
+ JOIN pg_opclass AS opc ON opc.oid=item.opclass
+ ORDER BY item.ordinality
+ ) AS opclasses,
+ ARRAY(
+ SELECT opc.oid::bigint
+ FROM unnest(ind.indclass) WITH ORDINALITY AS item(opclass, ordinality)
+ JOIN pg_opclass AS opc ON opc.oid=item.opclass
+ ORDER BY item.ordinality
+ ) AS opclass_oids,
+ ARRAY(
+ SELECT opc_nsp.nspname
+ FROM unnest(ind.indclass) WITH ORDINALITY AS item(opclass, ordinality)
+ JOIN pg_opclass AS opc ON opc.oid=item.opclass
+ JOIN pg_namespace AS opc_nsp
+ ON opc_nsp.oid=opc.opcnamespace
+ ORDER BY item.ordinality
+ ) AS opclass_namespaces,
+ ARRAY(
+ SELECT item.collation=att.attcollation
+ FROM unnest(ind.indcollation) WITH ORDINALITY
+ AS item(collation, ordinality)
+ JOIN unnest(ind.indkey) WITH ORDINALITY
+ AS key(attnum, ordinality)
+ ON key.ordinality=item.ordinality
+ LEFT JOIN pg_attribute AS att
+ ON att.attrelid=ind.indrelid AND att.attnum=key.attnum
+ ORDER BY item.ordinality
+ ) AS collations_match,
+ pg_get_expr(ind.indexprs, ind.indrelid) AS expressions,
+ pg_get_expr(ind.indpred, ind.indrelid) AS predicate
+ FROM pg_index AS ind
+ JOIN pg_class AS idx ON idx.oid=ind.indexrelid
+ JOIN pg_namespace AS idx_nsp ON idx_nsp.oid=idx.relnamespace
+ JOIN pg_am AS am ON am.oid=idx.relam
+ WHERE ind.indrelid=$1::oid
+ ORDER BY idx.relname
+ """,
+ table_oid,
+ )
+ canonical_opclass_rows = await connection.fetch(
+ """
+ SELECT opc.opcname, opc.oid::bigint AS opclass_oid
+ FROM pg_opclass AS opc
+ JOIN pg_namespace AS nsp ON nsp.oid=opc.opcnamespace
+ JOIN pg_am AS am ON am.oid=opc.opcmethod
+ WHERE nsp.nspname='pg_catalog'
+ AND am.amname='btree'
+ AND opc.opcname=ANY($1::text[])
+ """,
+ ["text_ops", "timestamptz_ops"],
+ )
+ canonical_opclasses = {
+ str(row["opcname"]): int(row["opclass_oid"])
+ for row in canonical_opclass_rows
+ }
+ checks = tuple(
+ (
+ str(row["conname"]),
+ " ".join(str(row["definition"]).split()),
+ )
+ for row in constraint_rows
+ if str(row["contype"]) == "c"
+ and bool(row["convalidated"])
+ and not bool(row["condeferrable"])
+ and not bool(row["condeferred"])
+ )
+ foreign_keys = tuple(
+ (
+ str(row["conname"]),
+ tuple(str(value) for value in row["local_columns"]),
+ str(row["referenced_table"]),
+ tuple(str(value) for value in row["remote_columns"]),
+ str(row["confupdtype"]),
+ str(row["confdeltype"]),
+ )
+ for row in constraint_rows
+ if str(row["contype"]) == "f"
+ and bool(row["convalidated"])
+ and not bool(row["condeferrable"])
+ and not bool(row["condeferred"])
+ and bool(row["reference_is_local"])
+ )
+ primary = tuple(
+ (
+ str(row["conname"]),
+ tuple(str(value) for value in row["local_columns"]),
+ bool(row["convalidated"]),
+ bool(row["condeferrable"]),
+ bool(row["condeferred"]),
+ )
+ for row in constraint_rows
+ if str(row["contype"]) == "p"
+ )
+ return {
+ "relation": (
+ str(relation["relkind"]),
+ str(relation["relpersistence"]),
+ bool(relation["relispartition"]),
+ bool(relation["relrowsecurity"]),
+ bool(relation["relforcerowsecurity"]),
+ int(relation["parent_count"]),
+ int(relation["child_count"]),
+ int(relation["policy_count"]),
+ int(relation["user_trigger_count"]),
+ int(relation["user_rule_count"]),
+ ),
+ "relation_oid": table_oid,
+ "schema_oid": schema_oid,
+ "columns": tuple(
+ (
+ str(row["name"]),
+ str(row["type"]),
+ bool(row["attnotnull"]),
+ str(row["attidentity"]),
+ str(row["attgenerated"]),
+ bool(row["collation_is_default"]),
+ None
+ if row["default_value"] is None
+ else str(row["default_value"]),
+ )
+ for row in column_rows
+ ),
+ "checks": checks,
+ "foreign_keys": foreign_keys,
+ "primary": primary,
+ "indexes": tuple(
+ (
+ str(row["name"]),
+ str(row["amname"]),
+ bool(row["indisunique"]),
+ bool(row["indisprimary"]),
+ bool(row["indisvalid"]),
+ bool(row["indisready"]),
+ bool(row["indislive"]),
+ int(row["indnkeyatts"]),
+ int(row["indnatts"]),
+ tuple(
+ None if value is None else str(value)
+ for value in row["columns"]
+ ),
+ tuple(int(value) for value in row["options"]),
+ tuple(str(value) for value in row["opclasses"]),
+ tuple(bool(value) for value in row["collations_match"]),
+ None if row["expressions"] is None else str(row["expressions"]),
+ None if row["predicate"] is None else str(row["predicate"]),
+ )
+ for row in index_rows
+ ),
+ "index_identities": tuple(
+ (
+ str(row["name"]),
+ str(row["relkind"]),
+ str(row["relpersistence"]),
+ bool(row["relispartition"]),
+ tuple(str(value) for value in row["opclasses"]),
+ tuple(str(value) for value in row["opclass_namespaces"]),
+ )
+ for row in index_rows
+ ),
+ "index_bindings": tuple(
+ (
+ int(row["table_oid"]) == table_oid,
+ int(row["index_schema_oid"]) == schema_oid,
+ bool(row["index_schema_is_local"]),
+ int(row["index_oid"]),
+ tuple(int(value) for value in row["opclass_oids"]),
+ tuple(
+ canonical_opclasses.get(str(name), -1)
+ for name in row["opclasses"]
+ ),
+ )
+ for row in index_rows
+ ),
+ "constraint_bindings": tuple(
+ (
+ str(row["conname"]),
+ int(row["table_oid"]),
+ int(row["referenced_oid"]),
+ None
+ if row["referenced_schema_oid"] is None
+ else int(row["referenced_schema_oid"]),
+ int(row["constraint_index_oid"]),
+ )
+ for row in constraint_rows
+ ),
+ "constraint_count": len(constraint_rows),
+ }
+
+
+def _ticket_catalog_matches_fixed_contract(
+ fingerprint: dict[str, object],
+) -> bool:
+ return (
+ fingerprint.get("relation")
+ == ("r", "p", False, False, False, 0, 0, 0, 0, 0)
+ and isinstance(fingerprint.get("relation_oid"), int)
+ and isinstance(fingerprint.get("schema_oid"), int)
+ and fingerprint.get("columns") == _EXPECTED_TICKET_COLUMNS
+ and fingerprint.get("checks") == _EXPECTED_TICKET_CHECKS
+ and fingerprint.get("foreign_keys") == _EXPECTED_TICKET_FOREIGN_KEYS
+ and fingerprint.get("primary")
+ == (("websocket_tickets_pkey", ("ticket_hash",), True, False, False),)
+ and fingerprint.get("indexes") == _EXPECTED_TICKET_INDEXES
+ and fingerprint.get("index_identities")
+ == _EXPECTED_TICKET_INDEX_IDENTITIES
+ and all(
+ table_is_exact
+ and schema_oid_is_exact
+ and schema_name_is_exact
+ and index_oid > 0
+ and opclass_oids == canonical_oids
+ for (
+ table_is_exact,
+ schema_oid_is_exact,
+ schema_name_is_exact,
+ index_oid,
+ opclass_oids,
+ canonical_oids,
+ ) in fingerprint.get("index_bindings", ())
+ )
+ and len(
+ {
+ binding[3]
+ for binding in fingerprint.get("index_bindings", ())
+ }
+ )
+ == 5
+ and all(
+ binding[1] == fingerprint.get("relation_oid")
+ for binding in fingerprint.get("constraint_bindings", ())
+ )
+ and fingerprint.get("constraint_count") == 15
+ )
+
+
+async def test_postgres_catalog_issue_consume_replay_and_revalidation() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ user_id, username, campaign_id, other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ source = _bearer_source(user_id, username)
+ issued = await database.issue_websocket_ticket(campaign_id, source)
+ _require_fixed(issued is not None, "valid bearer ticket was not issued")
+ raw_ticket, ttl = issued or ("", 0)
+
+ async with database._pool.acquire() as connection:
+ await database._validate_websocket_ticket_schema(connection)
+ catalog = await _ticket_catalog_fingerprint(connection)
+ row = await connection.fetchrow(
+ """
+ SELECT ticket_hash, bearer_subject, bearer_jti, api_key_id
+ FROM websocket_tickets
+ """
+ )
+ catalog_is_exact = _ticket_catalog_matches_fixed_contract(catalog)
+ raw_absent = row is not None and all(
+ raw_ticket != value for value in tuple(row)
+ )
+ digest_matches = (
+ row is not None
+ and row["ticket_hash"] == hash_websocket_ticket(raw_ticket)
+ )
+
+ wrong = await database.consume_websocket_ticket(raw_ticket, other_id)
+ consumed = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ replay = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ principal = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ resolved = (
+ principal is not None
+ and principal.user_id == user_id
+ and principal.role == "operator"
+ )
+
+ _require_fixed(ttl == 30, "ticket lifetime contract changed")
+ _require_fixed(catalog_is_exact, "ticket catalog contract changed")
+ _require_fixed(raw_absent, "raw ticket was persisted")
+ _require_fixed(digest_matches, "stored digest did not match ticket")
+ _require_fixed(wrong is None, "wrong campaign consumed a ticket")
+ _require_fixed(consumed is not None, "valid ticket was not consumed")
+ _require_fixed(replay is None, "ticket replay was accepted")
+ _require_fixed(resolved, "bearer principal was not resolved")
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='reporter' WHERE id=$1",
+ user_id,
+ )
+ current_role = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ current_role_applied = (
+ current_role is not None and current_role.role == "reporter"
+ )
+ _require_fixed(
+ current_role_applied,
+ "bearer resolver did not use the current role",
+ )
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='unknown-role' WHERE id=$1",
+ user_id,
+ )
+ invalid_role = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ _require_fixed(invalid_role is None, "unknown role remained authorized")
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='operator' WHERE id=$1",
+ user_id,
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator='different-operator' WHERE id=$1",
+ campaign_id,
+ )
+ inaccessible = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ _require_fixed(
+ inaccessible is None,
+ "campaign access loss remained authorized",
+ )
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='team_lead' WHERE id=$1",
+ user_id,
+ )
+ promoted = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='reporter' WHERE id=$1",
+ user_id,
+ )
+ demoted = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ _require_fixed(
+ promoted is not None
+ and promoted.role == "team_lead"
+ and demoted is None,
+ "bearer role/campaign revalidation matrix failed",
+ )
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='operator' WHERE id=$1",
+ user_id,
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator=$1 WHERE id=$2",
+ username,
+ campaign_id,
+ )
+ await connection.execute(
+ """
+ INSERT INTO revoked_access_tokens(jti, user_id, expires_at)
+ VALUES($1, $2, $3)
+ """,
+ source.jti,
+ user_id,
+ datetime.now(timezone.utc) + timedelta(minutes=5),
+ )
+ revoked = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ _require_fixed(revoked is None, "revoked bearer remained authorized")
+
+
+async def test_postgres_bearer_resolver_mutation_matrix_and_pool_recovery() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "bearer mutation setup failed")
+ consumed = await database.consume_websocket_ticket(
+ (issued or ("", 0))[0],
+ campaign_id,
+ )
+ _require_fixed(consumed is not None, "bearer mutation consume failed")
+ if consumed is None:
+ return
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET username='renamed-user' WHERE id=$1",
+ user_id,
+ )
+ renamed = await database.resolve_websocket_ticket_principal(consumed)
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET username=$1 WHERE id=$2",
+ username,
+ user_id,
+ )
+ await connection.execute(
+ "UPDATE users SET is_active=0 WHERE id=$1",
+ user_id,
+ )
+ inactive = await database.resolve_websocket_ticket_principal(consumed)
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET is_active=1 WHERE id=$1",
+ user_id,
+ )
+ expired = await database.resolve_websocket_ticket_principal(
+ replace(
+ consumed,
+ bearer_expires_at=datetime.now(timezone.utc)
+ - timedelta(seconds=1),
+ )
+ )
+ recovered = await database.resolve_websocket_ticket_principal(consumed)
+ async with database._pool.acquire() as connection:
+ reusable = await connection.fetchval("SELECT 1")
+ await connection.execute("DELETE FROM users WHERE id=$1", user_id)
+ deleted = await database.resolve_websocket_ticket_principal(consumed)
+ _require_fixed(
+ renamed is None
+ and inactive is None
+ and expired is None
+ and recovered is not None
+ and deleted is None
+ and reusable == 1,
+ "bearer resolver mutation matrix failed",
+ )
+
+
+async def test_postgres_ticket_timestamps_reject_both_infinities() -> None:
+ async with _postgres_harness() as harness:
+ import asyncpg
+
+ database = harness.database
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "finite timestamp setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ digest = hash_websocket_ticket(raw_ticket)
+ rejected = 0
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET bearer_expires_at=now() + interval '5 minutes',
+ expires_at=now() + interval '2 minutes',
+ created_at=now(),
+ consumed_at=now()
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ finite_values = await connection.fetchrow(
+ """
+ SELECT bearer_expires_at, created_at, expires_at, consumed_at
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ finite_values_are_aware = finite_values is not None and all(
+ value is not None and value.utcoffset() is not None
+ for value in tuple(finite_values)
+ )
+ for statement in (
+ """
+ UPDATE websocket_tickets
+ SET bearer_expires_at=$2::timestamptz
+ WHERE ticket_hash=$1
+ """,
+ """
+ UPDATE websocket_tickets
+ SET created_at=$2::timestamptz
+ WHERE ticket_hash=$1
+ """,
+ """
+ UPDATE websocket_tickets
+ SET expires_at=$2::timestamptz
+ WHERE ticket_hash=$1
+ """,
+ """
+ UPDATE websocket_tickets
+ SET consumed_at=$2::timestamptz
+ WHERE ticket_hash=$1
+ """,
+ ):
+ for literal in ("infinity", "-infinity"):
+ before = await connection.fetchrow(
+ """
+ SELECT bearer_expires_at, created_at,
+ expires_at, consumed_at
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ failed = False
+ try:
+ await connection.execute(
+ statement,
+ digest,
+ literal,
+ )
+ except asyncpg.CheckViolationError:
+ failed = True
+ after = await connection.fetchrow(
+ """
+ SELECT bearer_expires_at, created_at,
+ expires_at, consumed_at
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ unchanged = (
+ before is not None
+ and after is not None
+ and tuple(before) == tuple(after)
+ )
+ rejected += int(failed)
+ reusable = await connection.fetchval("SELECT 1")
+ _require_fixed(
+ failed and unchanged and reusable == 1,
+ "non-finite ticket timestamp was accepted",
+ )
+ null_rejected = 0
+ for statement in (
+ """
+ UPDATE websocket_tickets
+ SET created_at=NULL
+ WHERE ticket_hash=$1
+ """,
+ """
+ UPDATE websocket_tickets
+ SET expires_at=NULL
+ WHERE ticket_hash=$1
+ """,
+ ):
+ before = await connection.fetchrow(
+ """
+ SELECT bearer_expires_at, created_at,
+ expires_at, consumed_at
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ failed = False
+ try:
+ await connection.execute(
+ statement,
+ digest,
+ )
+ except asyncpg.NotNullViolationError:
+ failed = True
+ after = await connection.fetchrow(
+ """
+ SELECT bearer_expires_at, created_at,
+ expires_at, consumed_at
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ unchanged = (
+ before is not None
+ and after is not None
+ and tuple(before) == tuple(after)
+ )
+ reusable = await connection.fetchval("SELECT 1")
+ null_rejected += int(failed)
+ _require_fixed(
+ failed and unchanged and reusable == 1,
+ "required ticket timestamp accepted NULL",
+ )
+
+ api_issued = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=_key_id),
+ )
+ _require_fixed(
+ api_issued is not None,
+ "API-key timestamp setup failed",
+ )
+ api_digest = hash_websocket_ticket((api_issued or ("", 0))[0])
+ await connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET bearer_expires_at=NULL, consumed_at=NULL
+ WHERE ticket_hash=$1
+ """,
+ api_digest,
+ )
+ nullable_values = await connection.fetchrow(
+ """
+ SELECT bearer_expires_at IS NULL AS bearer_is_null,
+ consumed_at IS NULL AS consumed_is_null
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ api_digest,
+ )
+ nullable_accepted = (
+ nullable_values is not None
+ and bool(nullable_values["bearer_is_null"])
+ and bool(nullable_values["consumed_is_null"])
+ )
+ insert_hash = "f" * 64
+ insert_failed = False
+ try:
+ await connection.execute(
+ """
+ INSERT INTO websocket_tickets(
+ ticket_hash, campaign_id, user_id,
+ credential_kind, bearer_subject, bearer_jti,
+ bearer_expires_at, created_at, expires_at
+ )
+ VALUES(
+ $1, $2, $3, 'bearer', $4, $5,
+ now() + interval '5 minutes',
+ 'infinity'::timestamptz,
+ now() + interval '30 seconds'
+ )
+ """,
+ insert_hash,
+ campaign_id,
+ user_id,
+ username,
+ f"finite-insert-{uuid4().hex}",
+ )
+ except asyncpg.CheckViolationError:
+ insert_failed = True
+ inserted_rows = await connection.fetchval(
+ """
+ SELECT COUNT(*) FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ insert_hash,
+ )
+ insert_reusable = await connection.fetchval("SELECT 1")
+ rejected_insert_is_clean = (
+ insert_failed and inserted_rows == 0 and insert_reusable == 1
+ )
+ _require_fixed(rejected == 8, "finite timestamp rejection count changed")
+ _require_fixed(
+ null_rejected == 2,
+ "required timestamp NULL rejection count changed",
+ )
+ _require_fixed(
+ finite_values_are_aware
+ and nullable_accepted
+ and rejected_insert_is_clean,
+ "ticket timestamp finite/nullable contract changed",
+ )
+
+
+async def test_postgres_api_key_resolution_and_expiry_cleanup() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ user_id, username, campaign_id, _other_id, key_id = (
+ await _seed_identity(database, scopes="read,write")
+ )
+ async with database._pool.acquire() as connection:
+ before = await connection.fetchval(
+ "SELECT last_used FROM api_keys WHERE id=$1",
+ key_id,
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=key_id),
+ )
+ _require_fixed(issued is not None, "valid API-key ticket was not issued")
+ raw_ticket = (issued or ("", 0))[0]
+ handle = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ principal = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ repeated_principal = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ after = await connection.fetchval(
+ "SELECT last_used FROM api_keys WHERE id=$1",
+ key_id,
+ )
+ await connection.execute(
+ "UPDATE api_keys SET scopes='write' WHERE id=$1",
+ key_id,
+ )
+ write_principal = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE api_keys SET scopes='admin' WHERE id=$1",
+ key_id,
+ )
+ admin_principal = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ renamed_username = f"renamed-{uuid4().hex}"
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET username=$1 WHERE id=$2",
+ renamed_username,
+ user_id,
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator=$1 WHERE id=$2",
+ renamed_username,
+ campaign_id,
+ )
+ renamed_principal = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE campaigns SET operator='different-owner' WHERE id=$1",
+ campaign_id,
+ )
+ reassigned = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='team_lead' WHERE id=$1",
+ user_id,
+ )
+ promoted = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='reporter' WHERE id=$1",
+ user_id,
+ )
+ demoted = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET role='unknown-role' WHERE id=$1",
+ user_id,
+ )
+ invalid_role = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET username=$1, role='operator' WHERE id=$2",
+ username,
+ user_id,
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator=$1 WHERE id=$2",
+ username,
+ campaign_id,
+ )
+ await connection.execute(
+ "UPDATE api_keys SET scopes='read' WHERE id=$1",
+ key_id,
+ )
+ await connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET expires_at=now(), consumed_at=NULL
+ WHERE ticket_hash=$1
+ """,
+ hash_websocket_ticket(raw_ticket),
+ )
+ deleted = await database.purge_expired_websocket_tickets()
+ async with database._pool.acquire() as connection:
+ after_purge = await connection.fetchval(
+ "SELECT last_used FROM api_keys WHERE id=$1",
+ key_id,
+ )
+ resolved = (
+ principal is not None
+ and principal.credential_kind
+ is WebSocketTicketCredentialKind.API_KEY
+ and "read" in principal.api_key_scopes
+ )
+ _require_fixed(resolved, "API-key principal was not resolved")
+ scope_and_identity_matrix = (
+ repeated_principal is not None
+ and write_principal is not None
+ and write_principal.api_key_scopes == ("write",)
+ and admin_principal is not None
+ and admin_principal.api_key_scopes == ("admin",)
+ and renamed_principal is not None
+ and renamed_principal.username == renamed_username
+ and renamed_principal.user_id == user_id
+ and renamed_principal.api_key_id == key_id
+ and reassigned is None
+ and promoted is not None
+ and promoted.role == "team_lead"
+ and demoted is None
+ and invalid_role is None
+ )
+ _require_fixed(
+ scope_and_identity_matrix,
+ "API-key scope/identity/role matrix failed",
+ )
+ _require_fixed(
+ before == after == after_purge,
+ "API-key last_used was mutated",
+ )
+ _require_fixed(deleted == 1, "exact-now purge boundary changed")
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE api_keys SET scopes='telemetry' WHERE id=$1",
+ key_id,
+ )
+ invalid_scope = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ issue_denied = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=key_id),
+ )
+ _require_fixed(
+ invalid_scope is None,
+ "API-key scope loss remained authorized",
+ )
+ _require_fixed(
+ issue_denied is None,
+ "API key without an accepted scope issued a ticket",
+ )
+
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE api_keys SET scopes='read' WHERE id=$1",
+ key_id,
+ )
+ await connection.execute(
+ "UPDATE api_keys SET is_active=0 WHERE id=$1",
+ key_id,
+ )
+ inactive_key = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE api_keys SET is_active=1, expires_at=now() WHERE id=$1",
+ key_id,
+ )
+ expired_key = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE api_keys SET expires_at=NULL WHERE id=$1",
+ key_id,
+ )
+ await connection.execute(
+ "UPDATE users SET is_active=0 WHERE id=$1",
+ user_id,
+ )
+ inactive_user = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "UPDATE users SET is_active=1 WHERE id=$1",
+ user_id,
+ )
+ recovered_principal = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ _require_fixed(
+ inactive_key is None
+ and expired_key is None
+ and inactive_user is None
+ and recovered_principal is not None,
+ "API-key resolver mutation matrix failed",
+ )
+
+ expiring = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=key_id),
+ )
+ _require_fixed(expiring is not None, "expiry setup ticket was not issued")
+ expiring_raw = (expiring or ("", 0))[0]
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ """
+ UPDATE websocket_tickets SET expires_at=now()
+ WHERE ticket_hash=$1
+ """,
+ hash_websocket_ticket(expiring_raw),
+ )
+ exact_now = await database.consume_websocket_ticket(
+ expiring_raw,
+ campaign_id,
+ )
+ _require_fixed(exact_now is None, "exact-now ticket was consumed")
+
+ replacement_key_id = (
+ await database.create_api_key(
+ user_id,
+ "replacement-ticket-key",
+ scopes="read",
+ )
+ )[0]
+ stable_binding = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute(
+ "DELETE FROM api_keys WHERE id=$1",
+ key_id,
+ )
+ deleted_key = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ replacement_issued = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(
+ user_id=user_id,
+ api_key_id=replacement_key_id,
+ ),
+ )
+ replacement_handle = (
+ await database.consume_websocket_ticket(
+ (replacement_issued or ("", 0))[0],
+ campaign_id,
+ )
+ if replacement_issued is not None
+ else None
+ )
+ async with database._pool.acquire() as connection:
+ await connection.execute("DELETE FROM users WHERE id=$1", user_id)
+ deleted_owner = (
+ await database.resolve_websocket_ticket_principal(replacement_handle)
+ if replacement_handle is not None
+ else None
+ )
+ binding_and_deletion_matrix = (
+ stable_binding is not None
+ and stable_binding.user_id == user_id
+ and stable_binding.api_key_id == key_id
+ and replacement_key_id != key_id
+ and deleted_key is None
+ and replacement_handle is not None
+ and deleted_owner is None
+ )
+ _require_fixed(
+ binding_and_deletion_matrix,
+ "API-key ownership/replacement/deletion matrix failed",
+ )
+
+
+async def test_postgres_two_pools_have_one_consumer() -> None:
+ async with _postgres_harness() as harness:
+ first = harness.database
+ second = _database_for_target(harness.database_name)
+ first_task: asyncio.Task[Any] | None = None
+ second_task: asyncio.Task[Any] | None = None
+ release_exit = asyncio.Event()
+ original_pool = first._pool
+ second_original_pool = None
+ first_backend_pids: list[int] = []
+ second_backend_pids: list[int] = []
+ second_update_started = asyncio.Event()
+ try:
+ await _bounded_operation("second-runtime-initialize", second.connect())
+ second_original_pool = second._pool
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(first)
+ )
+ issued = await first.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ digest = hash_websocket_ticket(raw_ticket)
+ exit_reached = asyncio.Event()
+ first._pool = _BarrierPool(
+ original_pool,
+ exit_reached,
+ release_exit,
+ first_backend_pids,
+ )
+ second._pool = _PoolProxy(
+ second_original_pool,
+ [],
+ second_backend_pids,
+ second_update_started,
+ )
+ first_task = asyncio.create_task(
+ first.consume_websocket_ticket(raw_ticket, campaign_id)
+ )
+ await asyncio.wait_for(exit_reached.wait(), timeout=10)
+ second_task = asyncio.create_task(
+ second.consume_websocket_ticket(raw_ticket, campaign_id)
+ )
+ await asyncio.wait_for(second_update_started.wait(), timeout=10)
+
+ async def _observe_blocked_consumer() -> bool:
+ async with original_pool.acquire() as observer:
+ observer_pid = int(
+ await observer.fetchval("SELECT pg_backend_pid()")
+ )
+ for _ in range(200):
+ blocked = await observer.fetchval(
+ """
+ SELECT
+ EXISTS(
+ SELECT 1 FROM pg_locks
+ WHERE pid=$1 AND NOT granted
+ )
+ AND $2=ANY(pg_blocking_pids($1))
+ """,
+ second_backend_pids[0],
+ first_backend_pids[0],
+ )
+ if blocked:
+ hidden = await observer.fetchval(
+ """
+ SELECT consumed_at IS NULL
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ distinct = len(
+ {
+ first_backend_pids[0],
+ second_backend_pids[0],
+ observer_pid,
+ }
+ ) == 3
+ return bool(hidden) and distinct
+ await asyncio.sleep(0.01)
+ return False
+
+ lock_and_visibility_proved = await asyncio.wait_for(
+ _observe_blocked_consumer(),
+ timeout=10,
+ )
+ second_waited = not second_task.done()
+ release_exit.set()
+ results = await asyncio.wait_for(
+ asyncio.gather(first_task, second_task),
+ timeout=10,
+ )
+ first._pool = original_pool
+ second._pool = second_original_pool
+ winner_count = sum(result is not None for result in results)
+ async with original_pool.acquire() as observer:
+ committed_visible = await observer.fetchval(
+ """
+ SELECT consumed_at IS NOT NULL
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ digest,
+ )
+ _require_fixed(
+ lock_and_visibility_proved and second_waited,
+ "cross-pool row-lock visibility was not proved",
+ )
+ _require_fixed(
+ winner_count == 1 and bool(committed_visible),
+ "ticket did not have exactly one PostgreSQL consumer",
+ )
+ async with second._pool.acquire() as connection:
+ reusable = await connection.fetchval("SELECT 1")
+ _require_fixed(reusable == 1, "second pool was not reusable")
+ finally:
+ primary_failure = sys.exception()
+ release_exit.set()
+ first._pool = original_pool
+ if second_original_pool is not None:
+ second._pool = second_original_pool
+ for task in (first_task, second_task):
+ if task is not None and not task.done():
+ task.cancel()
+ tasks = tuple(
+ task
+ for task in (first_task, second_task)
+ if task is not None
+ )
+ if tasks:
+ await asyncio.wait_for(
+ asyncio.gather(*tasks, return_exceptions=True),
+ timeout=10,
+ )
+ close_failures: list[str] = []
+ if second._pool is not None:
+ await _attempt_cleanup(
+ "second-runtime-close",
+ second.close,
+ close_failures,
+ )
+ if close_failures:
+ if primary_failure is not None:
+ for failure in close_failures:
+ primary_failure.add_note(
+ f"PostgreSQL ticket cleanup failure [{failure}]"
+ )
+ else:
+ raise RuntimeError(
+ "PostgreSQL ticket secondary cleanup failed"
+ ) from None
+
+
+async def test_postgres_collision_rolls_back_and_pool_recovers(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async with _postgres_harness() as harness:
+ import asyncpg
+
+ database = harness.database
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ fixed_ticket = generate_websocket_ticket()
+ with monkeypatch.context() as patcher:
+ patcher.setattr(
+ postgres_module,
+ "generate_websocket_ticket",
+ lambda: fixed_ticket,
+ )
+ first = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(first is not None, "collision setup failed")
+ collision_type: type[BaseException] | None = None
+ try:
+ await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ except Exception as exc:
+ collision_type = type(exc)
+ _require_fixed(
+ collision_type is asyncpg.UniqueViolationError,
+ "ticket collision did not fail with the expected fixed type",
+ )
+
+ consumed = await database.consume_websocket_ticket(
+ fixed_ticket,
+ campaign_id,
+ )
+ recovered = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ async with database._pool.acquire() as connection:
+ reusable = await connection.fetchval("SELECT 1")
+ _require_fixed(consumed is not None, "collision damaged prior ticket")
+ _require_fixed(recovered is not None, "issuance did not recover")
+ _require_fixed(reusable == 1, "pool was not reusable after collision")
+
+
+class _ConnectionProxy:
+ def __init__(
+ self,
+ connection: Any,
+ classes: list[str],
+ backend_pids: list[int] | None = None,
+ update_started: asyncio.Event | None = None,
+ ) -> None:
+ self._connection = connection
+ self._classes = classes
+ self._backend_pids = backend_pids
+ self._update_started = update_started
+
+ def transaction(self, *args: object, **kwargs: object) -> Any:
+ return self._connection.transaction(*args, **kwargs)
+
+ async def fetchrow(
+ self,
+ query: str,
+ *args: object,
+ **kwargs: object,
+ ) -> Any:
+ normalized = " ".join(query.upper().split())
+ if (
+ normalized.startswith("INSERT INTO WEBSOCKET_TICKETS")
+ and "'API_KEY'" in normalized
+ ):
+ required = (
+ "CREDENTIAL_KIND, API_KEY_ID, REQUIRED_SCOPE,"
+ " CREATED_AT, EXPIRES_AT" in normalized
+ and "SELECT $1, C.ID, U.ID, 'API_KEY', AK.ID, 'READ',"
+ " NOW(), NOW() + INTERVAL '30 SECONDS'" in normalized
+ and "AK.ID=$4" in normalized
+ and "AK.USER_ID=$3" in normalized
+ )
+ self._classes.append(
+ "API KEY INSERT WITH REQUIRED SCOPE"
+ if required
+ else "UNSAFE API KEY INSERT"
+ )
+ elif normalized.startswith("UPDATE WEBSOCKET_TICKETS"):
+ if self._backend_pids is not None:
+ self._backend_pids.append(
+ int(await self._connection.fetchval("SELECT pg_backend_pid()"))
+ )
+ if self._update_started is not None:
+ self._update_started.set()
+ required_predicates = (
+ "TICKET_HASH=$1",
+ "CAMPAIGN_ID=$2",
+ "CONSUMED_AT IS NULL",
+ "EXPIRES_AT > NOW()",
+ )
+ required_return_fields = (
+ "CAMPAIGN_ID",
+ "USER_ID",
+ "CREDENTIAL_KIND",
+ "BEARER_SUBJECT",
+ "BEARER_JTI",
+ "BEARER_EXPIRES_AT",
+ "API_KEY_ID",
+ "REQUIRED_SCOPE",
+ )
+ returning = normalized.partition(" RETURNING ")[2]
+ returned_fields = tuple(
+ field.strip() for field in returning.split(",")
+ )
+ required = (
+ all(predicate in normalized for predicate in required_predicates)
+ and returned_fields == required_return_fields
+ )
+ self._classes.append(
+ "CONDITIONAL UPDATE RETURNING"
+ if required
+ else "UNSAFE UPDATE"
+ )
+ return await self._connection.fetchrow(query, *args, **kwargs)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._connection, name)
+
+
+class _AcquireProxy:
+ def __init__(
+ self,
+ acquisition: Any,
+ classes: list[str],
+ backend_pids: list[int] | None = None,
+ update_started: asyncio.Event | None = None,
+ ) -> None:
+ self._acquisition = acquisition
+ self._classes = classes
+ self._backend_pids = backend_pids
+ self._update_started = update_started
+ self._connection = None
+
+ async def __aenter__(self) -> _ConnectionProxy:
+ self._connection = await self._acquisition.__aenter__()
+ return _ConnectionProxy(
+ self._connection,
+ self._classes,
+ self._backend_pids,
+ self._update_started,
+ )
+
+ async def __aexit__(self, *exc_info: object) -> object:
+ return await self._acquisition.__aexit__(*exc_info)
+
+
+class _PoolProxy:
+ def __init__(
+ self,
+ pool: Any,
+ classes: list[str],
+ backend_pids: list[int] | None = None,
+ update_started: asyncio.Event | None = None,
+ ) -> None:
+ self._pool = pool
+ self._classes = classes
+ self._backend_pids = backend_pids
+ self._update_started = update_started
+
+ def acquire(self) -> _AcquireProxy:
+ return _AcquireProxy(
+ self._pool.acquire(),
+ self._classes,
+ self._backend_pids,
+ self._update_started,
+ )
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._pool, name)
+
+
+class _ResolverConnectionProxy:
+ def __init__(
+ self,
+ connection: Any,
+ started: asyncio.Event,
+ release: asyncio.Event | None,
+ failure: Exception | None,
+ ) -> None:
+ self._connection = connection
+ self._started = started
+ self._release = release
+ self._failure = failure
+
+ async def fetchrow(
+ self,
+ query: str,
+ *args: object,
+ **kwargs: object,
+ ) -> Any:
+ normalized = " ".join(query.upper().split())
+ if normalized.startswith("SELECT U.ID"):
+ self._started.set()
+ if self._failure is not None:
+ raise self._failure
+ if self._release is not None:
+ await asyncio.wait_for(self._release.wait(), timeout=10)
+ return await self._connection.fetchrow(query, *args, **kwargs)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._connection, name)
+
+
+class _ResolverAcquireProxy:
+ def __init__(
+ self,
+ acquisition: Any,
+ started: asyncio.Event,
+ release: asyncio.Event | None,
+ failure: Exception | None,
+ ) -> None:
+ self._acquisition = acquisition
+ self._started = started
+ self._release = release
+ self._failure = failure
+
+ async def __aenter__(self) -> _ResolverConnectionProxy:
+ connection = await self._acquisition.__aenter__()
+ return _ResolverConnectionProxy(
+ connection,
+ self._started,
+ self._release,
+ self._failure,
+ )
+
+ async def __aexit__(self, *exc_info: object) -> object:
+ return await self._acquisition.__aexit__(*exc_info)
+
+
+class _ResolverPoolProxy:
+ def __init__(
+ self,
+ pool: Any,
+ started: asyncio.Event,
+ release: asyncio.Event | None = None,
+ failure: Exception | None = None,
+ ) -> None:
+ self._pool = pool
+ self._started = started
+ self._release = release
+ self._failure = failure
+
+ def acquire(self) -> _ResolverAcquireProxy:
+ return _ResolverAcquireProxy(
+ self._pool.acquire(),
+ self._started,
+ self._release,
+ self._failure,
+ )
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._pool, name)
+
+
+class _PureAsyncContext:
+ def __init__(self, value: Any = None) -> None:
+ self._value = value
+
+ async def __aenter__(self) -> Any:
+ return self._value
+
+ async def __aexit__(self, *exc_info: object) -> None:
+ return None
+
+
+class _PureTicketConnection:
+ def transaction(self, *args: object, **kwargs: object) -> _PureAsyncContext:
+ return _PureAsyncContext()
+
+ async def execute(
+ self,
+ _query: str,
+ *_args: object,
+ **_kwargs: object,
+ ) -> str:
+ return "DELETE 0"
+
+ async def fetchrow(
+ self,
+ _query: str,
+ *_args: object,
+ **_kwargs: object,
+ ) -> dict[str, object]:
+ return {
+ "campaign_id": "synthetic-campaign",
+ "user_id": "synthetic-user",
+ "credential_kind": "bearer",
+ "bearer_subject": "synthetic-subject",
+ "bearer_jti": "synthetic-jti",
+ "bearer_expires_at": datetime.now(timezone.utc)
+ + timedelta(minutes=1),
+ "api_key_id": None,
+ "required_scope": None,
+ }
+
+
+class _PureTicketPool:
+ def __init__(self) -> None:
+ self._connection = _PureTicketConnection()
+
+ def acquire(self) -> _PureAsyncContext:
+ return _PureAsyncContext(self._connection)
+
+
+class _TransactionExitBarrier:
+ def __init__(
+ self,
+ transaction: Any,
+ exit_reached: asyncio.Event,
+ release_exit: asyncio.Event,
+ ) -> None:
+ self._transaction = transaction
+ self._exit_reached = exit_reached
+ self._release_exit = release_exit
+
+ async def __aenter__(self) -> Any:
+ return await self._transaction.__aenter__()
+
+ async def __aexit__(self, *exc_info: object) -> object:
+ self._exit_reached.set()
+ await asyncio.wait_for(self._release_exit.wait(), timeout=10)
+ return await self._transaction.__aexit__(*exc_info)
+
+
+class _BarrierConnection:
+ def __init__(
+ self,
+ connection: Any,
+ exit_reached: asyncio.Event,
+ release_exit: asyncio.Event,
+ backend_pids: list[int],
+ ) -> None:
+ self._connection = connection
+ self._exit_reached = exit_reached
+ self._release_exit = release_exit
+ self._backend_pids = backend_pids
+
+ def transaction(self, *args: object, **kwargs: object) -> Any:
+ return _TransactionExitBarrier(
+ self._connection.transaction(*args, **kwargs),
+ self._exit_reached,
+ self._release_exit,
+ )
+
+ async def fetchrow(
+ self,
+ query: str,
+ *args: object,
+ **kwargs: object,
+ ) -> Any:
+ normalized = " ".join(query.upper().split())
+ if normalized.startswith("UPDATE WEBSOCKET_TICKETS"):
+ self._backend_pids.append(
+ int(await self._connection.fetchval("SELECT pg_backend_pid()"))
+ )
+ return await self._connection.fetchrow(query, *args, **kwargs)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._connection, name)
+
+
+class _BarrierAcquire:
+ def __init__(
+ self,
+ acquisition: Any,
+ exit_reached: asyncio.Event,
+ release_exit: asyncio.Event,
+ backend_pids: list[int],
+ ) -> None:
+ self._acquisition = acquisition
+ self._exit_reached = exit_reached
+ self._release_exit = release_exit
+ self._backend_pids = backend_pids
+
+ async def __aenter__(self) -> _BarrierConnection:
+ connection = await self._acquisition.__aenter__()
+ return _BarrierConnection(
+ connection,
+ self._exit_reached,
+ self._release_exit,
+ self._backend_pids,
+ )
+
+ async def __aexit__(self, *exc_info: object) -> object:
+ return await self._acquisition.__aexit__(*exc_info)
+
+
+class _BarrierPool:
+ def __init__(
+ self,
+ pool: Any,
+ exit_reached: asyncio.Event,
+ release_exit: asyncio.Event,
+ backend_pids: list[int],
+ ) -> None:
+ self._pool = pool
+ self._exit_reached = exit_reached
+ self._release_exit = release_exit
+ self._backend_pids = backend_pids
+
+ def acquire(self) -> _BarrierAcquire:
+ return _BarrierAcquire(
+ self._pool.acquire(),
+ self._exit_reached,
+ self._release_exit,
+ self._backend_pids,
+ )
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._pool, name)
+
+
+async def test_consume_sql_tripwire_exercises_production_without_postgres() -> None:
+ statement_classes: list[str] = []
+ database = PostgresDatabase("synthetic")
+ database._pool = _PoolProxy(_PureTicketPool(), statement_classes)
+ consumed = await database.consume_websocket_ticket(
+ generate_websocket_ticket(),
+ "synthetic-campaign",
+ )
+ _require_fixed(consumed is not None, "pure consume tripwire did not execute")
+ _require_fixed(
+ tuple(statement_classes) == ("CONDITIONAL UPDATE RETURNING",),
+ "production consume SQL lost its exact CAS/return contract",
+ )
+
+
+async def test_api_key_issue_sql_persists_required_scope_without_postgres() -> None:
+ statement_classes: list[str] = []
+ database = PostgresDatabase("synthetic")
+ database._pool = _PoolProxy(_PureTicketPool(), statement_classes)
+ issued = await database.issue_websocket_ticket(
+ "synthetic-campaign",
+ ApiKeyTicketSource(
+ user_id="synthetic-user",
+ api_key_id="synthetic-key",
+ ),
+ )
+ _require_fixed(issued is not None, "pure API-key issue tripwire did not execute")
+ _require_fixed(
+ tuple(statement_classes) == ("API KEY INSERT WITH REQUIRED SCOPE",),
+ "production API-key ticket SQL lost its required scope",
+ )
+
+
+async def test_postgres_consume_uses_one_conditional_update_returning() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ original_pool = database._pool
+ statement_classes: list[str] = []
+ database._pool = _PoolProxy(original_pool, statement_classes)
+ try:
+ consumed = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ finally:
+ database._pool = original_pool
+
+ _require_fixed(consumed is not None, "instrumented consume failed")
+ _require_fixed(
+ tuple(statement_classes) == ("CONDITIONAL UPDATE RETURNING",),
+ "PostgreSQL consume lost its conditional UPDATE RETURNING",
+ )
+
+
+async def test_postgres_resolver_errors_and_cancellation_release_pool() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ user_id, username, campaign_id, _other_id, key_id = (
+ await _seed_identity(database)
+ )
+ bearer_issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ api_issued = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=key_id),
+ )
+ _require_fixed(
+ bearer_issued is not None and api_issued is not None,
+ "resolver failure setup failed",
+ )
+ bearer = await database.consume_websocket_ticket(
+ (bearer_issued or ("", 0))[0],
+ campaign_id,
+ )
+ api_key = await database.consume_websocket_ticket(
+ (api_issued or ("", 0))[0],
+ campaign_id,
+ )
+ _require_fixed(
+ bearer is not None and api_key is not None,
+ "resolver failure handles were not created",
+ )
+ if bearer is None or api_key is None:
+ return
+
+ original_pool = database._pool
+ for handle in (bearer, api_key):
+ started = asyncio.Event()
+ database._pool = _ResolverPoolProxy(
+ original_pool,
+ started,
+ failure=RuntimeError(),
+ )
+ failure_type: type[BaseException] | None = None
+ try:
+ await database.resolve_websocket_ticket_principal(handle)
+ except Exception as exc:
+ failure_type = type(exc)
+ finally:
+ database._pool = original_pool
+ _require_fixed(
+ started.is_set() and failure_type is RuntimeError,
+ "resolver database error did not propagate safely",
+ )
+
+ cancel_started = asyncio.Event()
+ release = asyncio.Event()
+ database._pool = _ResolverPoolProxy(
+ original_pool,
+ cancel_started,
+ release=release,
+ )
+ task = asyncio.create_task(
+ database.resolve_websocket_ticket_principal(handle)
+ )
+ cancelled = False
+ try:
+ await asyncio.wait_for(cancel_started.wait(), timeout=10)
+ task.cancel()
+ try:
+ await asyncio.wait_for(task, timeout=10)
+ except asyncio.CancelledError:
+ cancelled = True
+ finally:
+ release.set()
+ database._pool = original_pool
+ if not task.done():
+ task.cancel()
+ await asyncio.wait_for(
+ asyncio.gather(task, return_exceptions=True),
+ timeout=10,
+ )
+ recovered = await database.resolve_websocket_ticket_principal(handle)
+ async with original_pool.acquire() as connection:
+ reusable = await connection.fetchval("SELECT 1")
+ _require_fixed(
+ cancelled and recovered is not None and reusable == 1,
+ "resolver cancellation did not release and recover the pool",
+ )
+
+
+async def test_postgres_issue_returns_only_after_transaction_exit() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_pool = database._pool
+ exit_reached = asyncio.Event()
+ release_exit = asyncio.Event()
+ task: asyncio.Task[tuple[str, int] | None] | None = None
+ database._pool = _BarrierPool(
+ original_pool,
+ exit_reached,
+ release_exit,
+ [],
+ )
+ try:
+ task = asyncio.create_task(
+ database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ )
+ await asyncio.wait_for(exit_reached.wait(), timeout=10)
+ returned_early = task.done()
+ release_exit.set()
+ issued = await asyncio.wait_for(task, timeout=10)
+ finally:
+ release_exit.set()
+ database._pool = original_pool
+ if task is not None and not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+
+ _require_fixed(
+ not returned_early,
+ "ticket was returned before transaction exit",
+ )
+ _require_fixed(issued is not None, "barrier issuance did not complete")
+
+
+async def test_postgres_revision_0007_upgrade_and_downgrade(
+) -> None:
+ migration_catalog: dict[str, object] | None = None
+ async with _postgres_harness(initialize_runtime=False) as harness:
+ import asyncpg
+
+ config = _postgres_test_config()
+
+ async def _connect() -> Any:
+ return await _bounded_operation(
+ "migration-catalog-connect",
+ asyncpg.connect(
+ host=config["host"],
+ port=config["port"],
+ user=config["user"],
+ database=harness.database_name,
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ ),
+ )
+
+ connection = await _connect()
+ try:
+ initial_counts = await _bounded_operation(
+ "migration-empty-catalog",
+ connection.fetchrow(
+ """
+ SELECT
+ (
+ SELECT COUNT(*)
+ FROM information_schema.tables
+ WHERE table_schema=current_schema()
+ ) AS tables,
+ (
+ SELECT to_regclass('alembic_version') IS NULL
+ ) AS version_absent
+ """
+ ),
+ )
+ finally:
+ await _attempt_cleanup(
+ "migration-empty-close",
+ connection.close,
+ [],
+ )
+ initially_empty = (
+ initial_counts is not None
+ and int(initial_counts["tables"]) == 0
+ and bool(initial_counts["version_absent"])
+ )
+ _require_fixed(
+ initially_empty,
+ "PostgreSQL migration target was not genuinely empty",
+ )
+
+ _run_ticket_migration(harness.database_name, "upgrade", "0006")
+ connection = await _connect()
+ try:
+ parent_revision = await connection.fetchval(
+ "SELECT version_num FROM alembic_version"
+ )
+ seed_user = f"migration-user-{uuid4().hex}"
+ seed_campaign = f"migration-campaign-{uuid4().hex}"
+ seed_key = f"migration-key-{uuid4().hex}"
+ await connection.execute(
+ """
+ INSERT INTO users(id, username, hashed_password, role)
+ VALUES($1, $2, $3, 'operator')
+ """,
+ seed_user,
+ f"migration-name-{uuid4().hex}",
+ "synthetic-hash",
+ )
+ await connection.execute(
+ """
+ INSERT INTO campaigns(id, name, operator)
+ VALUES($1, $2, $3)
+ """,
+ seed_campaign,
+ "Migration campaign",
+ "migration-operator",
+ )
+ await connection.execute(
+ """
+ INSERT INTO api_keys(
+ id, user_id, name, key_hash, key_prefix, scopes
+ )
+ VALUES($1, $2, $3, $4, $5, 'read')
+ """,
+ seed_key,
+ seed_user,
+ "migration-key",
+ "synthetic-key-hash",
+ "synthetic-key",
+ )
+ finally:
+ await _attempt_cleanup(
+ "migration-parent-close",
+ connection.close,
+ [],
+ )
+ _require_fixed(
+ parent_revision == "0006",
+ "PostgreSQL migration did not reach revision 0006",
+ )
+
+ _run_ticket_migration(harness.database_name, "upgrade", "0007")
+ connection = await _connect()
+ try:
+ await PostgresDatabase._validate_websocket_ticket_schema(connection)
+ migration_catalog = await _ticket_catalog_fingerprint(connection)
+ upgraded_state = await connection.fetchrow(
+ """
+ SELECT
+ (SELECT version_num FROM alembic_version) AS revision,
+ (SELECT COUNT(*) FROM users WHERE id=$1) AS users,
+ (SELECT COUNT(*) FROM campaigns WHERE id=$2) AS campaigns,
+ (SELECT COUNT(*) FROM api_keys WHERE id=$3) AS api_keys
+ """,
+ seed_user,
+ seed_campaign,
+ seed_key,
+ )
+ finally:
+ await _attempt_cleanup(
+ "migration-upgrade-close",
+ connection.close,
+ [],
+ )
+ upgraded = (
+ upgraded_state is not None
+ and upgraded_state["revision"] == "0007"
+ and all(
+ int(upgraded_state[name]) == 1
+ for name in ("users", "campaigns", "api_keys")
+ )
+ and migration_catalog is not None
+ and _ticket_catalog_matches_fixed_contract(migration_catalog)
+ )
+ _require_fixed(
+ upgraded,
+ "PostgreSQL ticket migration contract changed",
+ )
+
+ _run_ticket_migration(harness.database_name, "downgrade", "0006")
+ connection = await _connect()
+ try:
+ downgraded_state = await connection.fetchrow(
+ """
+ SELECT
+ to_regclass('websocket_tickets') IS NULL AS ticket_absent,
+ (SELECT version_num FROM alembic_version) AS revision,
+ (SELECT COUNT(*) FROM users WHERE id=$1) AS users,
+ (SELECT COUNT(*) FROM campaigns WHERE id=$2) AS campaigns,
+ (SELECT COUNT(*) FROM api_keys WHERE id=$3) AS api_keys
+ """,
+ seed_user,
+ seed_campaign,
+ seed_key,
+ )
+ finally:
+ await _attempt_cleanup(
+ "migration-downgrade-close",
+ connection.close,
+ [],
+ )
+ downgraded = (
+ downgraded_state is not None
+ and bool(downgraded_state["ticket_absent"])
+ and downgraded_state["revision"] == "0006"
+ and all(
+ int(downgraded_state[name]) == 1
+ for name in ("users", "campaigns", "api_keys")
+ )
+ )
+ _require_fixed(downgraded, "PostgreSQL ticket downgrade contract changed")
+
+ _run_ticket_migration(harness.database_name, "upgrade", "0007")
+ connection = await _connect()
+ try:
+ await PostgresDatabase._validate_websocket_ticket_schema(connection)
+ reupgraded_catalog = await _ticket_catalog_fingerprint(connection)
+ final_state = await connection.fetchrow(
+ """
+ SELECT
+ (SELECT version_num FROM alembic_version) AS revision,
+ (SELECT COUNT(*) FROM users WHERE id=$1) AS users,
+ (SELECT COUNT(*) FROM campaigns WHERE id=$2) AS campaigns,
+ (SELECT COUNT(*) FROM api_keys WHERE id=$3) AS api_keys
+ """,
+ seed_user,
+ seed_campaign,
+ seed_key,
+ )
+ finally:
+ await _attempt_cleanup(
+ "migration-reupgrade-close",
+ connection.close,
+ [],
+ )
+ final_state_is_exact = (
+ final_state is not None
+ and final_state["revision"] == "0007"
+ and all(
+ int(final_state[name]) == 1
+ for name in ("users", "campaigns", "api_keys")
+ )
+ and _ticket_catalog_matches_fixed_contract(reupgraded_catalog)
+ and reupgraded_catalog == migration_catalog
+ )
+ _require_fixed(
+ final_state_is_exact,
+ "PostgreSQL ticket re-upgrade contract changed",
+ )
+
+ async with _postgres_harness() as runtime_harness:
+ async with runtime_harness.database._pool.acquire() as connection:
+ runtime_catalog = await _ticket_catalog_fingerprint(connection)
+ parity = (
+ migration_catalog is not None
+ and _ticket_catalog_matches_fixed_contract(runtime_catalog)
+ and runtime_catalog == migration_catalog
+ )
+ _require_fixed(
+ parity,
+ "runtime and migration ticket catalogs diverged",
+ )
+
+
+async def test_postgres_partial_ticket_schema_fails_clearly() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ async with database._pool.acquire() as connection:
+ await connection.execute("DROP TABLE websocket_tickets")
+ await connection.execute(
+ """
+ CREATE TABLE websocket_tickets(
+ ticket_hash TEXT PRIMARY KEY
+ )
+ """
+ )
+ incompatible = await _ticket_catalog_fingerprint(connection)
+ failure_type: type[BaseException] | None = None
+ failure_message_is_fixed = False
+ try:
+ await database._init_schema()
+ except Exception as exc:
+ failure_type = type(exc)
+ failure_message_is_fixed = (
+ str(exc) == "Incompatible WebSocket ticket schema"
+ )
+ async with database._pool.acquire() as connection:
+ after_failure = await _ticket_catalog_fingerprint(connection)
+ reusable = await connection.fetchval("SELECT 1")
+ _require_fixed(
+ failure_type is RuntimeError
+ and failure_message_is_fixed
+ and incompatible == after_failure
+ and reusable == 1,
+ "partial PostgreSQL ticket schema did not fail clearly",
+ )
+
+
+ "mutation",
+ [
+ pytest.param(
+ """
+ CREATE INDEX idx_ws_ticket_unexpected_expression
+ ON websocket_tickets ((lower(ticket_hash)))
+ """,
+ id="expression-index",
+ ),
+ pytest.param(
+ """
+ DROP INDEX idx_ws_tickets_expires;
+ CREATE INDEX idx_ws_tickets_expires
+ ON websocket_tickets(expires_at DESC)
+ """,
+ id="index-order",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ DROP CONSTRAINT ck_ws_ticket_created_finite;
+ ALTER TABLE websocket_tickets
+ ADD CONSTRAINT ck_ws_ticket_created_finite
+ CHECK (isfinite(created_at)) NOT VALID
+ """,
+ id="not-valid-check",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ DROP CONSTRAINT fk_ws_ticket_campaign;
+ ALTER TABLE websocket_tickets
+ ADD CONSTRAINT fk_ws_ticket_campaign
+ FOREIGN KEY(campaign_id) REFERENCES campaigns(id)
+ ON UPDATE CASCADE ON DELETE CASCADE
+ """,
+ id="foreign-key-action",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ ALTER COLUMN required_scope SET DEFAULT 'read'
+ """,
+ id="column-default",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ ALTER COLUMN created_at SET DEFAULT now()
+ """,
+ id="timestamp-column-default",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ DROP CONSTRAINT ck_ws_ticket_created_at;
+ ALTER TABLE websocket_tickets
+ ADD CONSTRAINT ck_ws_ticket_created_at
+ CHECK (created_at <= expires_at)
+ """,
+ id="same-name-check-body",
+ ),
+ pytest.param(
+ """
+ DROP INDEX idx_ws_tickets_campaign;
+ CREATE INDEX idx_ws_tickets_campaign
+ ON websocket_tickets(user_id)
+ """,
+ id="same-name-index-column",
+ ),
+ pytest.param(
+ """
+ DROP INDEX idx_ws_tickets_campaign;
+ CREATE UNIQUE INDEX idx_ws_tickets_campaign
+ ON websocket_tickets(campaign_id)
+ """,
+ id="same-name-index-uniqueness",
+ ),
+ pytest.param(
+ """
+ CREATE INDEX idx_ws_ticket_duplicate_campaign
+ ON websocket_tickets(campaign_id)
+ """,
+ id="duplicate-equivalent-index",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ DROP CONSTRAINT websocket_tickets_pkey;
+ ALTER TABLE websocket_tickets
+ ADD CONSTRAINT websocket_tickets_pkey PRIMARY KEY(campaign_id)
+ """,
+ id="wrong-primary-key",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ DROP CONSTRAINT fk_ws_ticket_campaign;
+ ALTER TABLE websocket_tickets
+ ADD CONSTRAINT fk_ws_ticket_campaign
+ FOREIGN KEY(campaign_id) REFERENCES users(id)
+ ON DELETE CASCADE
+ """,
+ id="wrong-foreign-key-target",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ DROP CONSTRAINT ck_ws_ticket_created_finite
+ """,
+ id="missing-constraint",
+ ),
+ pytest.param(
+ """
+ DROP INDEX idx_ws_tickets_campaign
+ """,
+ id="missing-index",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ ADD CONSTRAINT ck_ws_ticket_unexpected CHECK (true)
+ """,
+ id="extra-constraint",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ ALTER COLUMN bearer_expires_at
+ TYPE timestamp without time zone
+ USING bearer_expires_at AT TIME ZONE 'UTC'
+ """,
+ id="timestamp-type",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ ALTER COLUMN created_at DROP NOT NULL
+ """,
+ id="column-nullability",
+ ),
+ pytest.param(
+ """
+ ALTER TABLE websocket_tickets
+ ALTER COLUMN bearer_subject TYPE text COLLATE "C"
+ """,
+ id="column-collation",
+ ),
+ ],
+)
+async def test_postgres_validator_rejects_near_compatible_catalogs(
+ mutation: str,
+) -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ async with database._pool.acquire() as connection:
+ await connection.execute(mutation)
+ incompatible = await _ticket_catalog_fingerprint(connection)
+ failure_type: type[BaseException] | None = None
+ fixed_message = False
+ try:
+ await database._init_schema()
+ except Exception as exc:
+ failure_type = type(exc)
+ fixed_message = (
+ str(exc) == "Incompatible WebSocket ticket schema"
+ )
+ async with database._pool.acquire() as connection:
+ after_failure = await _ticket_catalog_fingerprint(connection)
+ reusable = await connection.fetchval("SELECT 1")
+ _require_fixed(
+ failure_type is RuntimeError
+ and fixed_message
+ and incompatible == after_failure
+ and reusable == 1,
+ "near-compatible ticket startup prevalidation failed",
+ )
+
+
+_POSTGRES_RELATION_METADATA_MUTATIONS = (
+ "unlogged",
+ "wrong-kind",
+ "partitioned",
+ "inheritance-child",
+ "inheritance-parent",
+ "rls",
+ "force-rls",
+ "policy",
+ "consumption-trigger",
+ "rewrite-rule",
+ "decoy-schema",
+ "wrong-opclass",
+ "wrong-relation-binding",
+)
+
+
+async def _apply_ticket_metadata_mutation(
+ connection: Any,
+ mutation: str,
+) -> None:
+ if mutation == "unlogged":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets SET UNLOGGED"
+ )
+ elif mutation == "wrong-kind":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets RENAME TO websocket_tickets_saved"
+ )
+ await connection.execute(
+ """
+ CREATE VIEW websocket_tickets AS
+ SELECT * FROM websocket_tickets_saved
+ """
+ )
+ elif mutation == "partitioned":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets RENAME TO websocket_tickets_saved"
+ )
+ await connection.execute(
+ """
+ CREATE TABLE websocket_tickets(ticket_hash TEXT NOT NULL)
+ PARTITION BY HASH(ticket_hash)
+ """
+ )
+ await connection.execute(
+ """
+ CREATE TABLE websocket_tickets_partition
+ PARTITION OF websocket_tickets
+ FOR VALUES WITH (MODULUS 1, REMAINDER 0)
+ """
+ )
+ elif mutation == "inheritance-child":
+ await connection.execute(
+ "CREATE TABLE ws_ticket_inheritance_parent()"
+ )
+ await connection.execute(
+ """
+ ALTER TABLE websocket_tickets
+ INHERIT ws_ticket_inheritance_parent
+ """
+ )
+ elif mutation == "inheritance-parent":
+ await connection.execute(
+ """
+ CREATE TABLE ws_ticket_inheritance_child()
+ INHERITS (websocket_tickets)
+ """
+ )
+ elif mutation == "rls":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets ENABLE ROW LEVEL SECURITY"
+ )
+ elif mutation == "force-rls":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets ENABLE ROW LEVEL SECURITY"
+ )
+ await connection.execute(
+ "ALTER TABLE websocket_tickets FORCE ROW LEVEL SECURITY"
+ )
+ elif mutation == "policy":
+ await connection.execute(
+ """
+ CREATE POLICY ws_ticket_policy
+ ON websocket_tickets
+ USING (true)
+ WITH CHECK (true)
+ """
+ )
+ elif mutation == "consumption-trigger":
+ await connection.execute(
+ """
+ CREATE FUNCTION ws_ticket_preserve_unconsumed()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ AS $function$
+ BEGIN
+ NEW.consumed_at := NULL;
+ RETURN NEW;
+ END
+ $function$
+ """
+ )
+ await connection.execute(
+ """
+ CREATE TRIGGER ws_ticket_preserve_unconsumed
+ BEFORE UPDATE OF consumed_at ON websocket_tickets
+ FOR EACH ROW
+ WHEN (NEW.consumed_at IS NOT NULL)
+ EXECUTE FUNCTION ws_ticket_preserve_unconsumed()
+ """
+ )
+ elif mutation == "rewrite-rule":
+ await connection.execute(
+ """
+ CREATE RULE ws_ticket_update_rule AS
+ ON UPDATE TO websocket_tickets
+ DO ALSO NOTHING
+ """
+ )
+ elif mutation == "decoy-schema":
+ await connection.execute(
+ "DROP INDEX idx_ws_tickets_campaign"
+ )
+ await connection.execute("CREATE SCHEMA ws_ticket_decoy")
+ await connection.execute(
+ """
+ CREATE TABLE ws_ticket_decoy.websocket_tickets(
+ campaign_id TEXT
+ )
+ """
+ )
+ await connection.execute(
+ """
+ CREATE INDEX idx_ws_tickets_campaign
+ ON ws_ticket_decoy.websocket_tickets(campaign_id)
+ """
+ )
+ elif mutation == "wrong-opclass":
+ await connection.execute(
+ "DROP INDEX idx_ws_tickets_campaign"
+ )
+ await connection.execute(
+ """
+ CREATE INDEX idx_ws_tickets_campaign
+ ON websocket_tickets(campaign_id text_pattern_ops)
+ """
+ )
+ elif mutation == "wrong-relation-binding":
+ await connection.execute(
+ "DROP INDEX idx_ws_tickets_campaign"
+ )
+ await connection.execute(
+ "CREATE TABLE ws_ticket_index_decoy(campaign_id TEXT)"
+ )
+ await connection.execute(
+ """
+ CREATE INDEX idx_ws_tickets_campaign
+ ON ws_ticket_index_decoy(campaign_id)
+ """
+ )
+ else:
+ raise RuntimeError("Unknown PostgreSQL ticket metadata mutation")
+
+
+async def _remove_ticket_metadata_mutation(
+ connection: Any,
+ mutation: str,
+) -> None:
+ if mutation == "unlogged":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets SET LOGGED"
+ )
+ elif mutation == "wrong-kind":
+ await connection.execute("DROP VIEW websocket_tickets")
+ await connection.execute(
+ "ALTER TABLE websocket_tickets_saved RENAME TO websocket_tickets"
+ )
+ elif mutation == "partitioned":
+ await connection.execute(
+ "DROP TABLE websocket_tickets CASCADE"
+ )
+ await connection.execute(
+ "ALTER TABLE websocket_tickets_saved RENAME TO websocket_tickets"
+ )
+ elif mutation == "inheritance-child":
+ await connection.execute(
+ """
+ ALTER TABLE websocket_tickets
+ NO INHERIT ws_ticket_inheritance_parent
+ """
+ )
+ await connection.execute(
+ "DROP TABLE ws_ticket_inheritance_parent"
+ )
+ elif mutation == "inheritance-parent":
+ await connection.execute(
+ "DROP TABLE ws_ticket_inheritance_child"
+ )
+ elif mutation == "rls":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets DISABLE ROW LEVEL SECURITY"
+ )
+ elif mutation == "force-rls":
+ await connection.execute(
+ "ALTER TABLE websocket_tickets NO FORCE ROW LEVEL SECURITY"
+ )
+ await connection.execute(
+ "ALTER TABLE websocket_tickets DISABLE ROW LEVEL SECURITY"
+ )
+ elif mutation == "policy":
+ await connection.execute(
+ "DROP POLICY ws_ticket_policy ON websocket_tickets"
+ )
+ elif mutation == "consumption-trigger":
+ await connection.execute(
+ """
+ DROP TRIGGER ws_ticket_preserve_unconsumed
+ ON websocket_tickets
+ """
+ )
+ await connection.execute(
+ "DROP FUNCTION ws_ticket_preserve_unconsumed()"
+ )
+ elif mutation == "rewrite-rule":
+ await connection.execute(
+ "DROP RULE ws_ticket_update_rule ON websocket_tickets"
+ )
+ elif mutation == "decoy-schema":
+ await connection.execute(
+ "DROP SCHEMA ws_ticket_decoy CASCADE"
+ )
+ await connection.execute(
+ """
+ CREATE INDEX idx_ws_tickets_campaign
+ ON websocket_tickets(campaign_id)
+ """
+ )
+ elif mutation == "wrong-opclass":
+ await connection.execute(
+ "DROP INDEX idx_ws_tickets_campaign"
+ )
+ await connection.execute(
+ """
+ CREATE INDEX idx_ws_tickets_campaign
+ ON websocket_tickets(campaign_id)
+ """
+ )
+ elif mutation == "wrong-relation-binding":
+ await connection.execute(
+ "DROP TABLE ws_ticket_index_decoy"
+ )
+ await connection.execute(
+ """
+ CREATE INDEX idx_ws_tickets_campaign
+ ON websocket_tickets(campaign_id)
+ """
+ )
+ else:
+ raise RuntimeError("Unknown PostgreSQL ticket metadata mutation")
+
+
+async def _ticket_metadata_mutation_exists(
+ connection: Any,
+ mutation: str,
+) -> bool:
+ fingerprint = await _ticket_catalog_fingerprint(connection)
+ relation = fingerprint.get("relation")
+ if not isinstance(relation, tuple):
+ return False
+ if mutation == "unlogged":
+ return relation[1] == "u"
+ if mutation == "wrong-kind":
+ return relation[0] == "v"
+ if mutation == "partitioned":
+ return relation[0] == "p" and relation[6] == 1
+ if mutation == "inheritance-child":
+ return relation[5] == 1
+ if mutation == "inheritance-parent":
+ return relation[6] == 1
+ if mutation == "rls":
+ return relation[3] is True and relation[4] is False
+ if mutation == "force-rls":
+ return relation[3] is True and relation[4] is True
+ if mutation == "policy":
+ return relation[7] == 1
+ if mutation == "consumption-trigger":
+ return relation[8] == 1
+ if mutation == "rewrite-rule":
+ return relation[9] == 1
+ if mutation == "wrong-opclass":
+ return any(
+ identity[0] == "idx_ws_tickets_campaign"
+ and identity[4] == ("text_pattern_ops",)
+ and identity[5] == ("pg_catalog",)
+ for identity in fingerprint.get("index_identities", ())
+ )
+ if mutation == "decoy-schema":
+ return bool(
+ await connection.fetchval(
+ """
+ SELECT
+ NOT EXISTS(
+ SELECT 1
+ FROM pg_index AS ind
+ JOIN pg_class AS rel ON rel.oid=ind.indrelid
+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace
+ JOIN pg_class AS idx ON idx.oid=ind.indexrelid
+ WHERE nsp.nspname=current_schema()
+ AND rel.relname='websocket_tickets'
+ AND idx.relname='idx_ws_tickets_campaign'
+ )
+ AND EXISTS(
+ SELECT 1
+ FROM pg_index AS ind
+ JOIN pg_class AS rel ON rel.oid=ind.indrelid
+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace
+ JOIN pg_class AS idx ON idx.oid=ind.indexrelid
+ WHERE nsp.nspname='ws_ticket_decoy'
+ AND rel.relname='websocket_tickets'
+ AND idx.relname='idx_ws_tickets_campaign'
+ )
+ """
+ )
+ )
+ if mutation == "wrong-relation-binding":
+ return bool(
+ await connection.fetchval(
+ """
+ SELECT
+ NOT EXISTS(
+ SELECT 1
+ FROM pg_index AS ind
+ JOIN pg_class AS rel ON rel.oid=ind.indrelid
+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace
+ JOIN pg_class AS idx ON idx.oid=ind.indexrelid
+ WHERE nsp.nspname=current_schema()
+ AND rel.relname='websocket_tickets'
+ AND idx.relname='idx_ws_tickets_campaign'
+ )
+ AND EXISTS(
+ SELECT 1
+ FROM pg_index AS ind
+ JOIN pg_class AS rel ON rel.oid=ind.indrelid
+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace
+ JOIN pg_class AS idx ON idx.oid=ind.indexrelid
+ WHERE nsp.nspname=current_schema()
+ AND rel.relname='ws_ticket_index_decoy'
+ AND idx.relname='idx_ws_tickets_campaign'
+ )
+ """
+ )
+ )
+ return False
+
+
+async def _ticket_related_object_fingerprint(
+ connection: Any,
+) -> tuple[tuple[object, ...], ...]:
+ rows = await connection.fetch(
+ """
+ SELECT nsp.nspname, rel.relname, rel.relkind,
+ rel.relpersistence, rel.relispartition,
+ rel.relrowsecurity, rel.relforcerowsecurity
+ FROM pg_class AS rel
+ JOIN pg_namespace AS nsp ON nsp.oid=rel.relnamespace
+ WHERE (
+ nsp.nspname=current_schema()
+ AND (
+ rel.relname LIKE 'websocket_tickets%'
+ OR rel.relname LIKE 'idx_ws_tickets%'
+ OR rel.relname LIKE 'ws_ticket_%'
+ )
+ )
+ OR nsp.nspname='ws_ticket_decoy'
+ ORDER BY nsp.nspname, rel.relname
+ """
+ )
+ return tuple(tuple(row) for row in rows)
+
+
+async def _ticket_rows_for_metadata_mutation(
+ connection: Any,
+ mutation: str,
+) -> tuple[tuple[object, ...], ...]:
+ if mutation in {"wrong-kind", "partitioned"}:
+ query = """
+ SELECT ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope, created_at, expires_at,
+ consumed_at
+ FROM websocket_tickets_saved
+ ORDER BY ticket_hash
+ """
+ else:
+ query = """
+ SELECT ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope, created_at, expires_at,
+ consumed_at
+ FROM websocket_tickets
+ ORDER BY ticket_hash
+ """
+ rows = await connection.fetch(
+ query
+ )
+ return tuple(tuple(row) for row in rows)
+
+
+ "mutation",
+ [
+ pytest.param(value, id=value)
+ for value in _POSTGRES_RELATION_METADATA_MUTATIONS
+ ],
+)
+async def test_postgres_rejects_security_altering_relation_metadata(
+ mutation: str,
+) -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(
+ issued is not None,
+ "PostgreSQL metadata mutation ticket setup failed",
+ )
+ raw_ticket = (issued or ("", 0))[0]
+ observer_pool = database._pool
+ candidate = _database_for_target(harness.database_name)
+ mutation_applied = False
+ candidate_connected = False
+ try:
+ async with observer_pool.acquire() as connection:
+ await asyncio.wait_for(
+ _apply_ticket_metadata_mutation(connection, mutation),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ mutation_applied = True
+ mutation_exists = await asyncio.wait_for(
+ _ticket_metadata_mutation_exists(connection, mutation),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+
+ trigger_would_enable_replay = True
+ if mutation == "consumption-trigger":
+ first = await asyncio.wait_for(
+ database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ ),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ second = await asyncio.wait_for(
+ database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ ),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ async with observer_pool.acquire() as connection:
+ remains_unconsumed = bool(
+ await connection.fetchval(
+ """
+ SELECT consumed_at IS NULL
+ FROM websocket_tickets
+ WHERE ticket_hash=$1
+ """,
+ hash_websocket_ticket(raw_ticket),
+ )
+ )
+ trigger_would_enable_replay = (
+ first is not None
+ and second is not None
+ and remains_unconsumed
+ )
+
+ async with observer_pool.acquire() as connection:
+ before_catalog = await asyncio.wait_for(
+ _ticket_catalog_fingerprint(connection),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ before_related = await asyncio.wait_for(
+ _ticket_related_object_fingerprint(connection),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ before_rows = await asyncio.wait_for(
+ _ticket_rows_for_metadata_mutation(connection, mutation),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+
+ failure_type: type[BaseException] | None = None
+ fixed_message = False
+ try:
+ await asyncio.wait_for(
+ candidate.connect(),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ candidate_connected = True
+ except Exception as exc:
+ failure_type = type(exc)
+ fixed_message = (
+ str(exc) == "Incompatible WebSocket ticket schema"
+ )
+ pool_was_cleared = candidate._pool is None
+
+ async with observer_pool.acquire() as connection:
+ after_catalog = await asyncio.wait_for(
+ _ticket_catalog_fingerprint(connection),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ after_related = await asyncio.wait_for(
+ _ticket_related_object_fingerprint(connection),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ after_rows = await asyncio.wait_for(
+ _ticket_rows_for_metadata_mutation(connection, mutation),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ observer_reusable = (
+ await asyncio.wait_for(
+ connection.fetchval("SELECT 1"),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ == 1
+ )
+ startup_preserved_state = (
+ before_catalog == after_catalog
+ and before_related == after_related
+ and before_rows == after_rows
+ )
+ _require_fixed(
+ mutation_exists
+ and trigger_would_enable_replay
+ and failure_type is RuntimeError
+ and fixed_message
+ and pool_was_cleared
+ and startup_preserved_state
+ and observer_reusable,
+ "PostgreSQL relation metadata prevalidation failed",
+ )
+ finally:
+ if candidate_connected or candidate._pool is not None:
+ await _attempt_cleanup(
+ "metadata-candidate-close",
+ candidate.close,
+ [],
+ )
+ if mutation_applied:
+ async with observer_pool.acquire() as connection:
+ await asyncio.wait_for(
+ _remove_ticket_metadata_mutation(connection, mutation),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+
+ recovery = _database_for_target(harness.database_name)
+ try:
+ await asyncio.wait_for(
+ recovery.connect(),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ async with recovery._pool.acquire() as connection:
+ recovered_catalog = await asyncio.wait_for(
+ _ticket_catalog_fingerprint(connection),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ recovered_connection = (
+ await asyncio.wait_for(
+ connection.fetchval("SELECT 1"),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ == 1
+ )
+ consumed = await asyncio.wait_for(
+ recovery.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ ),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ replay = await asyncio.wait_for(
+ recovery.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ ),
+ timeout=_POSTGRES_OPERATION_TIMEOUT_SECONDS,
+ )
+ recovery_is_exact = (
+ _ticket_catalog_matches_fixed_contract(recovered_catalog)
+ and recovered_connection
+ and consumed is not None
+ and replay is None
+ )
+ _require_fixed(
+ recovery_is_exact,
+ "PostgreSQL metadata correction recovery failed",
+ )
+ finally:
+ if recovery._pool is not None:
+ await _attempt_cleanup(
+ "metadata-recovery-close",
+ recovery.close,
+ [],
+ )
diff --git a/tests/unit/test_websocket_ticket_lifecycle.py b/tests/unit/test_websocket_ticket_lifecycle.py
new file mode 100644
index 0000000..82c3718
--- /dev/null
+++ b/tests/unit/test_websocket_ticket_lifecycle.py
@@ -0,0 +1,2568 @@
+"""SQLite and pure-contract coverage for one-time WebSocket tickets."""
+from __future__ import annotations
+
+import asyncio
+import os
+import re
+import sqlite3
+import threading
+from dataclasses import FrozenInstanceError, replace
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any
+from unittest.mock import patch
+from uuid import uuid4
+
+import aiosqlite
+import pytest
+
+import ares.db.database as database_module
+from ares.db.database import AresDatabase
+from ares.db.websocket_tickets import (
+ WEBSOCKET_TICKET_TTL_SECONDS,
+ ApiKeyTicketSource,
+ BearerTicketSource,
+ ConsumedWebSocketTicket,
+ WebSocketTicketCredentialKind,
+ WebSocketTicketPrincipal,
+ generate_websocket_ticket,
+ hash_websocket_ticket,
+ is_canonical_websocket_ticket,
+)
+
+
+def _require_fixed(condition: bool, message: str) -> None:
+ if not condition:
+ pytest.fail(message, pytrace=False)
+
+
+async def _connected_database(path: Path | str) -> AresDatabase:
+ database = AresDatabase(str(path))
+ await database.connect()
+ return database
+
+
+async def _connected_raw_database(path: Path | str) -> AresDatabase:
+ database = AresDatabase(str(path))
+
+ async def migrations_unavailable() -> bool:
+ return False
+
+ database._run_alembic_migrations = migrations_unavailable # type: ignore[method-assign]
+ await database.connect()
+ return database
+
+
+async def _seed_identity(
+ database: AresDatabase,
+ *,
+ role: str = "operator",
+ scopes: str = "read",
+) -> tuple[str, str, str, str, str]:
+ username = f"ticket_user_{uuid4().hex}"
+ original_info = database_module.logger.info
+
+ def suppress_user_created(
+ event: str,
+ *args: object,
+ **values: object,
+ ) -> Any:
+ if event == "user_created":
+ return None
+ return original_info(event, *args, **values)
+
+ with patch.object(
+ database_module.logger,
+ "info",
+ suppress_user_created,
+ ):
+ user_id = await database.create_user(
+ username,
+ "synthetic-test-password",
+ role,
+ )
+ campaign_id = f"campaign-{uuid4().hex}"
+ other_campaign_id = f"campaign-{uuid4().hex}"
+ connection = database._require_connected()
+ await connection.executemany(
+ """
+ INSERT INTO campaigns(id, name, operator)
+ VALUES(?, ?, ?)
+ """,
+ (
+ (campaign_id, "Ticket campaign", username),
+ (other_campaign_id, "Other campaign", username),
+ ),
+ )
+ await connection.commit()
+ api_key_id = f"api-key-{uuid4().hex}"
+ await connection.execute(
+ """
+ INSERT INTO api_keys(
+ id, user_id, name, key_hash, key_prefix, scopes
+ )
+ VALUES(?, ?, 'ticket-key', 'synthetic-test-only', 'test', ?)
+ """,
+ (api_key_id, user_id, scopes),
+ )
+ await connection.commit()
+ return user_id, username, campaign_id, other_campaign_id, api_key_id
+
+
+def _bearer_source(user_id: str, username: str) -> BearerTicketSource:
+ return BearerTicketSource(
+ user_id=user_id,
+ subject=username,
+ jti=f"ticket-jti-{uuid4().hex}",
+ expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
+ )
+
+
+def _identity_dataclass_contract(
+ first: object,
+ second: object,
+ *,
+ sensitive_values: tuple[object, ...],
+ frozen_field: str,
+) -> tuple[bool, bool, bool, bool, bool, bool]:
+ first_representation = repr(first)
+ second_representation = repr(second)
+ sensitive_markers = tuple(
+ marker
+ for value in sensitive_values
+ for marker in (str(value), repr(value))
+ if marker
+ )
+ representation_is_safe = all(
+ marker not in first_representation
+ and marker not in second_representation
+ for marker in sensitive_markers
+ )
+ identity_equality_is_preserved = (
+ first is not second
+ and first != second
+ and first == first
+ and second == second
+ )
+ identity_methods_are_preserved = (
+ type(first) is type(second)
+ and type(first).__eq__ is object.__eq__
+ and type(first).__ne__ is object.__ne__
+ and type(first).__hash__ is object.__hash__
+ and type(first).__lt__ is object.__lt__
+ and type(first).__le__ is object.__le__
+ and type(first).__gt__ is object.__gt__
+ and type(first).__ge__ is object.__ge__
+ )
+
+ hashing_is_usable = False
+ collections_preserve_identity = False
+ try:
+ hash(first)
+ hash(second)
+ instance_set = {first, second}
+ instance_dictionary = {first: "first", second: "second"}
+ hashing_is_usable = True
+ collections_preserve_identity = (
+ len(instance_set) == 2
+ and len(instance_dictionary) == 2
+ and instance_dictionary.get(first) == "first"
+ and instance_dictionary.get(second) == "second"
+ )
+ except TypeError:
+ pass
+
+ existing_field_rejected = False
+ try:
+ setattr(first, frozen_field, "synthetic-mutated-value")
+ except FrozenInstanceError:
+ existing_field_rejected = True
+
+ unexpected_field_rejected = False
+ unexpected_field = "synthetic_unexpected_field"
+ try:
+ setattr(first, unexpected_field, "synthetic-value")
+ except (AttributeError, TypeError):
+ unexpected_field_rejected = True
+ frozen_slots_are_preserved = (
+ existing_field_rejected
+ and unexpected_field_rejected
+ and not hasattr(first, "__dict__")
+ )
+
+ rejected_ordering_count = 0
+ ordering_operations = (
+ lambda: first < second,
+ lambda: first <= second,
+ lambda: first > second,
+ lambda: first >= second,
+ )
+ for operation in ordering_operations:
+ try:
+ operation()
+ except TypeError:
+ rejected_ordering_count += 1
+ ordering_is_not_generated = rejected_ordering_count == len(
+ ordering_operations
+ )
+
+ return (
+ representation_is_safe,
+ identity_equality_is_preserved,
+ identity_methods_are_preserved,
+ hashing_is_usable and collections_preserve_identity,
+ frozen_slots_are_preserved,
+ ordering_is_not_generated,
+ )
+
+
+def _require_identity_dataclass_contract(
+ checks: tuple[bool, bool, bool, bool, bool, bool],
+) -> None:
+ (
+ representation_is_safe,
+ identity_equality_is_preserved,
+ identity_methods_are_preserved,
+ identity_collections_are_preserved,
+ frozen_slots_are_preserved,
+ ordering_is_not_generated,
+ ) = checks
+ _require_fixed(
+ representation_is_safe,
+ "ticket contract representation exposed a sensitive field",
+ )
+ _require_fixed(
+ identity_equality_is_preserved,
+ "ticket contract gained value equality",
+ )
+ _require_fixed(
+ identity_methods_are_preserved,
+ "ticket contract generated comparison or hashing methods",
+ )
+ _require_fixed(
+ identity_collections_are_preserved,
+ "ticket contract lost identity-based collection behavior",
+ )
+ _require_fixed(
+ frozen_slots_are_preserved,
+ "ticket contract lost frozen or slotted behavior",
+ )
+ _require_fixed(
+ ordering_is_not_generated,
+ "ticket contract gained field-based ordering",
+ )
+
+
+def _owned_ticket_tasks() -> list[asyncio.Task[Any]]:
+ current = asyncio.current_task()
+ return [
+ task
+ for task in asyncio.all_tasks()
+ if task is not current
+ and not task.done()
+ and task.get_name().startswith("ares-sqlite-websocket-ticket-")
+ ]
+
+
+class _PostExecuteBarrier:
+ def __init__(
+ self,
+ result: Any,
+ entered: asyncio.Event,
+ release: asyncio.Event,
+ ) -> None:
+ self._result = result
+ self._entered = entered
+ self._release = release
+ self._cursor: Any = None
+
+ async def __aenter__(self) -> Any:
+ self._cursor = await self._result
+ if self._cursor.rowcount == 1:
+ self._entered.set()
+ await asyncio.wait_for(self._release.wait(), timeout=5)
+ return self._cursor
+
+ async def __aexit__(self, *_args: object) -> None:
+ if self._cursor is not None:
+ await self._cursor.close()
+
+
+class _BeginProbe:
+ def __init__(
+ self,
+ result: Any,
+ acquired: asyncio.Event,
+ ) -> None:
+ self._result = result
+ self._acquired = acquired
+
+ async def _wait(self) -> Any:
+ result = await self._result
+ self._acquired.set()
+ return result
+
+ def __await__(self) -> Any:
+ return self._wait().__await__()
+
+
+class _TicketConnectionProxy:
+ def __init__(
+ self,
+ connection: aiosqlite.Connection,
+ *,
+ cas_entered: asyncio.Event | None = None,
+ cas_release: asyncio.Event | None = None,
+ begin_acquired: asyncio.Event | None = None,
+ ) -> None:
+ self._connection = connection
+ self._cas_entered = cas_entered
+ self._cas_release = cas_release
+ self._begin_acquired = begin_acquired
+ self.statement_order: list[str] = []
+
+ @property
+ def row_factory(self) -> Any:
+ return self._connection.row_factory
+
+ @row_factory.setter
+ def row_factory(self, value: Any) -> None:
+ self._connection.row_factory = value
+
+ def execute(self, statement: str, *parameters: object) -> Any:
+ normalized = " ".join(statement.upper().split())
+ result = self._connection.execute(statement, *parameters)
+ if normalized == "BEGIN IMMEDIATE":
+ self.statement_order.append("BEGIN IMMEDIATE")
+ if self._begin_acquired is not None:
+ return _BeginProbe(
+ result,
+ self._begin_acquired,
+ )
+ elif normalized.startswith("UPDATE WEBSOCKET_TICKETS"):
+ self.statement_order.append("CAS UPDATE")
+ if (
+ self._cas_entered is not None
+ and self._cas_release is not None
+ ):
+ return _PostExecuteBarrier(
+ result,
+ self._cas_entered,
+ self._cas_release,
+ )
+ elif (
+ normalized.startswith("SELECT ")
+ and "FROM WEBSOCKET_TICKETS" in normalized
+ ):
+ self.statement_order.append("HANDLE SELECT")
+ return result
+
+ async def commit(self) -> None:
+ self.statement_order.append("COMMIT")
+ await self._connection.commit()
+
+ async def rollback(self) -> None:
+ self.statement_order.append("ROLLBACK")
+ await self._connection.rollback()
+
+ async def close(self) -> None:
+ await self._connection.close()
+
+
+def _sqlite_schema_snapshot(path: Path) -> tuple[tuple[object, ...], ...]:
+ connection = sqlite3.connect(path)
+ try:
+ return tuple(
+ connection.execute(
+ """
+ SELECT type, name, tbl_name, sql
+ FROM sqlite_schema
+ WHERE name NOT LIKE 'sqlite_%'
+ ORDER BY type, name
+ """
+ ).fetchall()
+ )
+ finally:
+ connection.close()
+
+
+def _replace_once(source: str, old: str, new: str) -> str:
+ if source.count(old) != 1:
+ raise RuntimeError("ticket schema mutation setup failed")
+ return source.replace(old, new, 1)
+
+
+def _regex_replace_once(source: str, pattern: str, replacement: str) -> str:
+ mutated, count = re.subn(
+ pattern,
+ replacement,
+ source,
+ count=1,
+ flags=re.IGNORECASE,
+ )
+ if count != 1:
+ raise RuntimeError("ticket schema mutation setup failed")
+ return mutated
+
+
+def _mutate_ticket_schema(path: Path, mutation: str) -> None:
+ connection = sqlite3.connect(path)
+ try:
+ table_row = connection.execute(
+ "SELECT sql FROM sqlite_schema "
+ "WHERE type='table' AND name='websocket_tickets'"
+ ).fetchone()
+ index_rows = connection.execute(
+ "SELECT name, sql FROM sqlite_schema "
+ "WHERE type='index' AND tbl_name='websocket_tickets' "
+ "AND sql IS NOT NULL ORDER BY name"
+ ).fetchall()
+ if table_row is None:
+ raise RuntimeError("ticket schema mutation setup failed")
+ table_sql = str(table_row[0])
+
+ if mutation == "wrong_check":
+ table_sql = _replace_once(
+ table_sql,
+ "length(ticket_hash)=64",
+ "length(ticket_hash)=63",
+ )
+ elif mutation == "wrong_fk_action":
+ table_sql = _regex_replace_once(
+ table_sql,
+ r"ON\s+DELETE\s+CASCADE",
+ "ON DELETE SET NULL",
+ )
+ elif mutation == "wrong_pk":
+ table_sql = _regex_replace_once(
+ table_sql,
+ r"NOT\s+NULL\s+PRIMARY\s+KEY",
+ "NOT NULL UNIQUE",
+ )
+ elif mutation == "wrong_nullability":
+ table_sql = _regex_replace_once(
+ table_sql,
+ r"\bcreated_at\s+TEXT\s+NOT\s+NULL",
+ "created_at TEXT",
+ )
+ elif mutation == "wrong_default":
+ table_sql = _regex_replace_once(
+ table_sql,
+ r"\bcreated_at\s+TEXT\s+NOT\s+NULL",
+ "created_at TEXT NOT NULL DEFAULT ''",
+ )
+ elif mutation == "extra_check":
+ closing = table_sql.rfind(")")
+ if closing < 0:
+ raise RuntimeError("ticket schema mutation setup failed")
+ table_sql = (
+ table_sql[:closing]
+ + ", CONSTRAINT ck_ws_ticket_extra CHECK (1)"
+ + table_sql[closing:]
+ )
+ elif mutation == "on_conflict":
+ table_sql = _replace_once(
+ table_sql,
+ "PRIMARY KEY",
+ "PRIMARY KEY ON CONFLICT REPLACE",
+ )
+ elif mutation == "deferrable":
+ table_sql = _regex_replace_once(
+ table_sql,
+ r"ON\s+DELETE\s+CASCADE",
+ "ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED",
+ )
+ elif mutation == "swapped_fk_names":
+ table_sql = _replace_once(
+ table_sql,
+ "fk_ws_ticket_campaign",
+ "fk_ws_ticket_name_swap",
+ )
+ table_sql = _replace_once(
+ table_sql,
+ "fk_ws_ticket_user",
+ "fk_ws_ticket_campaign",
+ )
+ table_sql = _replace_once(
+ table_sql,
+ "fk_ws_ticket_name_swap",
+ "fk_ws_ticket_user",
+ )
+
+ connection.execute("PRAGMA foreign_keys=OFF")
+ connection.execute("BEGIN")
+ if mutation in {
+ "wrong_check",
+ "wrong_fk_action",
+ "wrong_pk",
+ "wrong_nullability",
+ "wrong_default",
+ "extra_check",
+ "on_conflict",
+ "deferrable",
+ "swapped_fk_names",
+ }:
+ connection.execute("DROP TABLE websocket_tickets")
+ connection.execute(table_sql)
+ for _name, index_sql in index_rows:
+ connection.execute(str(index_sql))
+ elif mutation == "missing_index":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ elif mutation == "wrong_index":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_expires "
+ "ON websocket_tickets(consumed_at)"
+ )
+ elif mutation == "wrong_index_order":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_expires "
+ "ON websocket_tickets(expires_at, user_id)"
+ )
+ elif mutation == "wrong_uniqueness":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ connection.execute(
+ "CREATE UNIQUE INDEX idx_ws_tickets_expires "
+ "ON websocket_tickets(expires_at)"
+ )
+ elif mutation == "duplicate_index":
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_duplicate "
+ "ON websocket_tickets(expires_at)"
+ )
+ else:
+ raise RuntimeError("unknown ticket schema mutation")
+ connection.commit()
+ finally:
+ connection.close()
+
+
+async def _ticket_count(database: AresDatabase) -> int:
+ async with database.conn.execute(
+ "SELECT COUNT(*) AS count FROM websocket_tickets"
+ ) as cursor:
+ return int((await cursor.fetchone())["count"])
+
+
+async def _consumed_ticket_count(database: AresDatabase) -> int:
+ async with database.conn.execute(
+ "SELECT COUNT(*) AS count FROM websocket_tickets "
+ "WHERE consumed_at IS NOT NULL"
+ ) as cursor:
+ return int((await cursor.fetchone())["count"])
+
+
+def test_ticket_contract_is_canonical_and_sensitive_fields_are_not_represented() -> None:
+ raw_ticket = generate_websocket_ticket()
+ raw_is_canonical = is_canonical_websocket_ticket(raw_ticket)
+ digest = hash_websocket_ticket(raw_ticket)
+ digest_is_canonical = (
+ len(digest) == 64
+ and digest == digest.lower()
+ and all(character in "0123456789abcdef" for character in digest)
+ )
+ source = _bearer_source("user-contract", "contract-subject")
+ source_repr_is_safe = (
+ source.user_id not in repr(source)
+ and source.subject not in repr(source)
+ and source.jti not in repr(source)
+ )
+
+ _require_fixed(raw_is_canonical, "generated ticket was not canonical")
+ _require_fixed(digest_is_canonical, "ticket digest was not canonical")
+ _require_fixed(source_repr_is_safe, "source representation exposed an identifier")
+ _require_fixed(
+ WEBSOCKET_TICKET_TTL_SECONDS == 30,
+ "ticket lifetime contract changed",
+ )
+
+
+def test_bearer_ticket_source_preserves_identity_and_confidentiality() -> None:
+ expires_at = datetime(2035, 1, 2, 3, 4, 5, tzinfo=timezone.utc)
+ values = {
+ "user_id": "synthetic-bearer-user",
+ "subject": "synthetic-bearer-subject",
+ "jti": "synthetic-bearer-jti",
+ "expires_at": expires_at,
+ }
+ first = BearerTicketSource(**values)
+ second = BearerTicketSource(**values)
+ checks = _identity_dataclass_contract(
+ first,
+ second,
+ sensitive_values=tuple(values.values()),
+ frozen_field="subject",
+ )
+
+ _require_identity_dataclass_contract(checks)
+
+
+def test_api_key_ticket_source_preserves_identity_and_confidentiality() -> None:
+ values = {
+ "user_id": "synthetic-api-user",
+ "api_key_id": "synthetic-api-key",
+ }
+ first = ApiKeyTicketSource(**values)
+ second = ApiKeyTicketSource(**values)
+ checks = _identity_dataclass_contract(
+ first,
+ second,
+ sensitive_values=tuple(values.values()),
+ frozen_field="api_key_id",
+ )
+
+ _require_identity_dataclass_contract(checks)
+
+
+def test_consumed_ticket_preserves_identity_and_confidentiality() -> None:
+ bearer_expiry = datetime(2035, 2, 3, 4, 5, 6, tzinfo=timezone.utc)
+ bearer_values = {
+ "campaign_id": "synthetic-bearer-campaign",
+ "user_id": "synthetic-consumed-bearer-user",
+ "credential_kind": WebSocketTicketCredentialKind.BEARER,
+ "bearer_subject": "synthetic-consumed-subject",
+ "bearer_jti": "synthetic-consumed-jti",
+ "bearer_expires_at": bearer_expiry,
+ }
+ first_bearer = ConsumedWebSocketTicket(**bearer_values)
+ second_bearer = ConsumedWebSocketTicket(**bearer_values)
+ bearer_checks = _identity_dataclass_contract(
+ first_bearer,
+ second_bearer,
+ sensitive_values=(
+ bearer_values["campaign_id"],
+ bearer_values["user_id"],
+ bearer_values["bearer_subject"],
+ bearer_values["bearer_jti"],
+ bearer_values["bearer_expires_at"],
+ ),
+ frozen_field="bearer_jti",
+ )
+
+ api_key_values = {
+ "campaign_id": "synthetic-api-campaign",
+ "user_id": "synthetic-consumed-api-user",
+ "credential_kind": WebSocketTicketCredentialKind.API_KEY,
+ "api_key_id": "synthetic-consumed-api-key",
+ "required_scope": "read",
+ }
+ first_api_key = ConsumedWebSocketTicket(**api_key_values)
+ second_api_key = ConsumedWebSocketTicket(**api_key_values)
+ api_key_checks = _identity_dataclass_contract(
+ first_api_key,
+ second_api_key,
+ sensitive_values=(
+ api_key_values["campaign_id"],
+ api_key_values["user_id"],
+ api_key_values["api_key_id"],
+ api_key_values["required_scope"],
+ ),
+ frozen_field="api_key_id",
+ )
+
+ _require_identity_dataclass_contract(bearer_checks)
+ _require_identity_dataclass_contract(api_key_checks)
+
+
+def test_ticket_principal_preserves_identity_and_confidentiality() -> None:
+ values = {
+ "user_id": "synthetic-principal-user",
+ "username": "synthetic-principal-name",
+ "role": "operator",
+ "credential_kind": WebSocketTicketCredentialKind.API_KEY,
+ "api_key_id": "synthetic-principal-api-key",
+ "api_key_scopes": ("synthetic-scope",),
+ }
+ first = WebSocketTicketPrincipal(**values)
+ second = WebSocketTicketPrincipal(**values)
+ checks = _identity_dataclass_contract(
+ first,
+ second,
+ sensitive_values=(
+ values["user_id"],
+ values["username"],
+ values["api_key_id"],
+ values["api_key_scopes"],
+ ),
+ frozen_field="username",
+ )
+
+ _require_identity_dataclass_contract(checks)
+
+
+def test_ticket_contract_rejects_invalid_and_mixed_shapes() -> None:
+ invalid_values = ("", "short", " " * 43, "!" * 43, "a" * 44)
+ invalid_results = [
+ is_canonical_websocket_ticket(candidate)
+ for candidate in invalid_values
+ ]
+ mixed_rejected = False
+ try:
+ ConsumedWebSocketTicket(
+ campaign_id="campaign-contract",
+ user_id="user-contract",
+ credential_kind=WebSocketTicketCredentialKind.API_KEY,
+ api_key_id="key-contract",
+ required_scope="read",
+ bearer_subject="unexpected",
+ )
+ except ValueError:
+ mixed_rejected = True
+
+ _require_fixed(
+ not any(invalid_results),
+ "invalid ticket syntax was accepted",
+ )
+ _require_fixed(mixed_rejected, "mixed credential state was accepted")
+
+
+ "mutation",
+ [
+ "wrong_check",
+ "wrong_fk_action",
+ "wrong_pk",
+ "wrong_nullability",
+ "wrong_default",
+ "extra_check",
+ "on_conflict",
+ "deferrable",
+ "swapped_fk_names",
+ "missing_index",
+ "wrong_index",
+ "wrong_index_order",
+ "wrong_uniqueness",
+ "duplicate_index",
+ ],
+)
+async def test_sqlite_existing_ticket_schema_rejects_exact_mutations_without_change(
+ tmp_path: Path,
+ mutation: str,
+) -> None:
+ path = tmp_path / f"ticket-schema-{mutation}.db"
+ setup = await _connected_raw_database(path)
+ await setup.close()
+ _mutate_ticket_schema(path, mutation)
+ before = _sqlite_schema_snapshot(path)
+
+ candidate = AresDatabase(path)
+ rejected = False
+ try:
+ await candidate.connect()
+ except RuntimeError:
+ rejected = True
+ finally:
+ if candidate._conn is not None:
+ await candidate.close()
+ after = _sqlite_schema_snapshot(path)
+
+ _require_fixed(rejected, "incompatible ticket schema was accepted")
+ _require_fixed(
+ before == after,
+ "failed ticket schema validation mutated the database",
+ )
+
+
+async def test_sqlite_raw_bootstrap_validates_before_commit_and_rolls_back(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ path = tmp_path / "ticket-bootstrap-rollback.db"
+ database = AresDatabase(path)
+
+ async def migrations_unavailable() -> bool:
+ return False
+
+ class ValidationError(RuntimeError):
+ pass
+
+ async def reject_created_schema() -> None:
+ raise ValidationError("fixed validation failure")
+
+ monkeypatch.setattr(
+ database,
+ "_run_alembic_migrations",
+ migrations_unavailable,
+ )
+ monkeypatch.setattr(
+ database,
+ "_validate_websocket_ticket_schema",
+ reject_created_schema,
+ )
+ failure_is_primary = False
+ try:
+ await database.connect()
+ except ValidationError:
+ failure_is_primary = True
+
+ connection = sqlite3.connect(path)
+ try:
+ application_table_count = int(
+ connection.execute(
+ "SELECT COUNT(*) FROM sqlite_schema "
+ "WHERE type='table' AND name NOT LIKE 'sqlite_%'"
+ ).fetchone()[0]
+ )
+ finally:
+ connection.close()
+
+ recovered = await _connected_raw_database(path)
+ try:
+ schema_is_present = await _ticket_count(recovered) == 0
+ finally:
+ await recovered.close()
+
+ _require_fixed(
+ failure_is_primary,
+ "bootstrap validation failure was not propagated",
+ )
+ _require_fixed(
+ application_table_count == 0,
+ "failed bootstrap committed partial schema",
+ )
+ _require_fixed(
+ schema_is_present,
+ "bootstrap failure prevented clean recovery",
+ )
+
+
+async def test_sqlite_issue_consume_replay_and_raw_not_stored(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-lifecycle.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "valid bearer ticket was not issued")
+ raw_ticket, ttl = issued or ("", 0)
+
+ connection = database._require_connected()
+ async with connection.execute(
+ """
+ SELECT ticket_hash, bearer_subject, bearer_jti, api_key_id,
+ required_scope, consumed_at
+ FROM websocket_tickets
+ """
+ ) as cursor:
+ stored = await cursor.fetchone()
+ raw_absent = stored is not None and all(
+ raw_ticket != value for value in tuple(stored)
+ )
+ digest_matches = (
+ stored is not None
+ and stored["ticket_hash"] == hash_websocket_ticket(raw_ticket)
+ )
+
+ consumed = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ replay = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ principal = (
+ await database.resolve_websocket_ticket_principal(consumed)
+ if consumed is not None
+ else None
+ )
+ resolved = (
+ principal is not None
+ and principal.user_id == user_id
+ and principal.username == username
+ and principal.role == "operator"
+ )
+
+ _require_fixed(ttl == 30, "issued ticket lifetime changed")
+ _require_fixed(raw_absent, "raw ticket was persisted")
+ _require_fixed(digest_matches, "stored digest did not match the ticket")
+ _require_fixed(consumed is not None, "valid ticket was not consumed")
+ _require_fixed(replay is None, "consumed ticket was accepted twice")
+ _require_fixed(resolved, "bearer principal was not resolved")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_wrong_campaign_and_malformed_input_do_not_consume(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-campaign.db")
+ try:
+ user_id, username, campaign_id, other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+
+ malformed = await database.consume_websocket_ticket(
+ "not-a-ticket",
+ campaign_id,
+ )
+ wrong = await database.consume_websocket_ticket(raw_ticket, other_id)
+ correct = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ _require_fixed(malformed is None, "malformed ticket reached storage")
+ _require_fixed(wrong is None, "wrong campaign consumed a ticket")
+ _require_fixed(
+ correct is not None,
+ "wrong-campaign attempt mutated the ticket",
+ )
+ finally:
+ await database.close()
+
+
+async def test_sqlite_exact_now_expiry_and_purge_boundaries(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-expiry.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ digest = hash_websocket_ticket(raw_ticket)
+ connection = database._require_connected()
+ await connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET expires_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
+ WHERE ticket_hash=?
+ """,
+ (digest,),
+ )
+ await connection.commit()
+
+ expired = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ deleted = await database.purge_expired_websocket_tickets()
+ async with connection.execute(
+ "SELECT COUNT(*) AS count FROM websocket_tickets"
+ ) as cursor:
+ remaining = int((await cursor.fetchone())["count"])
+
+ _require_fixed(expired is None, "exact-now ticket was accepted")
+ _require_fixed(deleted == 1, "expired ticket purge count was incorrect")
+ _require_fixed(remaining == 0, "expired ticket remained stored")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_api_key_revalidation_does_not_update_last_used(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-api-key.db")
+ try:
+ user_id, _username, campaign_id, _other_id, key_id = (
+ await _seed_identity(database, scopes="read,write")
+ )
+ connection = database._require_connected()
+ async with connection.execute(
+ "SELECT last_used FROM api_keys WHERE id=?",
+ (key_id,),
+ ) as cursor:
+ before = (await cursor.fetchone())["last_used"]
+
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=key_id),
+ )
+ _require_fixed(issued is not None, "valid API-key ticket was not issued")
+ raw_ticket = (issued or ("", 0))[0]
+ handle = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ principal = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ async with connection.execute(
+ "SELECT last_used FROM api_keys WHERE id=?",
+ (key_id,),
+ ) as cursor:
+ after = (await cursor.fetchone())["last_used"]
+ unchanged = before == after
+ resolved = (
+ principal is not None
+ and principal.credential_kind
+ is WebSocketTicketCredentialKind.API_KEY
+ and "read" in principal.api_key_scopes
+ )
+
+ _require_fixed(resolved, "API-key principal was not resolved")
+ _require_fixed(
+ unchanged,
+ "ticket resolution mutated API-key usage state",
+ )
+
+ await connection.execute(
+ "UPDATE api_keys SET is_active=0 WHERE id=?",
+ (key_id,),
+ )
+ await connection.commit()
+ denied = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ _require_fixed(denied is None, "revoked API key remained authorized")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_source_and_campaign_revalidation_is_authoritative(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-revalidation.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ source = _bearer_source(user_id, username)
+ issued = await database.issue_websocket_ticket(campaign_id, source)
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ handle = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ _require_fixed(handle is not None, "ticket handle setup failed")
+
+ connection = database._require_connected()
+ await connection.execute(
+ "INSERT INTO revoked_access_tokens(jti,user_id,expires_at) "
+ "VALUES(?,?,?)",
+ (
+ source.jti,
+ user_id,
+ (
+ datetime.now(timezone.utc) + timedelta(minutes=5)
+ ).isoformat(),
+ ),
+ )
+ await connection.commit()
+ revoked = (
+ await database.resolve_websocket_ticket_principal(handle)
+ if handle is not None
+ else None
+ )
+ _require_fixed(revoked is None, "revoked source remained authorized")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_issue_revalidates_source_role_and_campaign_access(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-issue-auth.db")
+ try:
+ user_id, username, campaign_id, _other_id, key_id = (
+ await _seed_identity(database, scopes="telemetry")
+ )
+ source = _bearer_source(user_id, username)
+ connection = database._require_connected()
+ await connection.execute(
+ "INSERT INTO revoked_access_tokens(jti,user_id,expires_at) "
+ "VALUES(?,?,?)",
+ (
+ source.jti,
+ user_id,
+ (
+ datetime.now(timezone.utc) + timedelta(minutes=5)
+ ).isoformat(),
+ ),
+ )
+ await connection.commit()
+ revoked = await database.issue_websocket_ticket(campaign_id, source)
+
+ await connection.execute(
+ "DELETE FROM revoked_access_tokens WHERE jti=?",
+ (source.jti,),
+ )
+ await connection.execute(
+ "UPDATE users SET role='unknown-role' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ unknown_role = await database.issue_websocket_ticket(
+ campaign_id,
+ source,
+ )
+
+ await connection.execute(
+ "UPDATE users SET role='operator' WHERE id=?",
+ (user_id,),
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator='different-operator' WHERE id=?",
+ (campaign_id,),
+ )
+ await connection.commit()
+ inaccessible = await database.issue_websocket_ticket(
+ campaign_id,
+ source,
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator=? WHERE id=?",
+ (username, campaign_id),
+ )
+ await connection.commit()
+ invalid_scope = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=key_id),
+ )
+ await connection.execute(
+ "UPDATE users SET is_active=0 WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ inactive = await database.issue_websocket_ticket(
+ campaign_id,
+ source,
+ )
+
+ _require_fixed(revoked is None, "revoked bearer source issued a ticket")
+ _require_fixed(unknown_role is None, "unknown role issued a ticket")
+ _require_fixed(
+ inaccessible is None,
+ "campaign access loss still issued a ticket",
+ )
+ _require_fixed(
+ invalid_scope is None,
+ "API key without an accepted scope issued a ticket",
+ )
+ _require_fixed(inactive is None, "inactive user issued a ticket")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_bearer_resolver_complete_authority_mutations(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-bearer-matrix.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ source = _bearer_source(user_id, username)
+ issued = await database.issue_websocket_ticket(campaign_id, source)
+ _require_fixed(issued is not None, "bearer ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ handle = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ _require_fixed(handle is not None, "bearer handle setup failed")
+ if handle is None:
+ return
+
+ connection = database.conn
+ changes_before = connection.total_changes
+ active = await database.resolve_websocket_ticket_principal(handle)
+ active_again = await database.resolve_websocket_ticket_principal(handle)
+ read_only = connection.total_changes == changes_before
+
+ await connection.execute(
+ "UPDATE users SET is_active=0 WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ inactive = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET is_active=1 WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ reactivated = await database.resolve_websocket_ticket_principal(handle)
+
+ await connection.execute(
+ "UPDATE users SET role='team_lead' WHERE id=?",
+ (user_id,),
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator='different-operator' WHERE id=?",
+ (campaign_id,),
+ )
+ await connection.commit()
+ promoted = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET role='operator' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ demoted = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE campaigns SET operator=? WHERE id=?",
+ (username, campaign_id),
+ )
+ await connection.execute(
+ "UPDATE users SET role='unknown-role' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ invalid_role = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET role='reporter' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ current_role = await database.resolve_websocket_ticket_principal(handle)
+
+ await connection.execute(
+ "INSERT INTO revoked_access_tokens(jti,user_id,expires_at) "
+ "VALUES(?,?,?)",
+ (
+ source.jti,
+ user_id,
+ (
+ datetime.now(timezone.utc) + timedelta(minutes=5)
+ ).isoformat(),
+ ),
+ )
+ await connection.commit()
+ revoked = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "DELETE FROM revoked_access_tokens WHERE jti=?",
+ (source.jti,),
+ )
+ await connection.commit()
+ unrevoked = await database.resolve_websocket_ticket_principal(handle)
+
+ expired_handle = replace(
+ handle,
+ bearer_expires_at=datetime.now(timezone.utc) - timedelta(seconds=1),
+ )
+ expired_source = await database.resolve_websocket_ticket_principal(
+ expired_handle
+ )
+
+ renamed_username = f"renamed_{uuid4().hex}"
+ await connection.execute(
+ "UPDATE users SET username=? WHERE id=?",
+ (renamed_username, user_id),
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator=? WHERE id=?",
+ (renamed_username, campaign_id),
+ )
+ await connection.commit()
+ renamed = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET username=? WHERE id=?",
+ (username, user_id),
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator=? WHERE id=?",
+ (username, campaign_id),
+ )
+ await connection.commit()
+
+ digest = hash_websocket_ticket(raw_ticket)
+ await connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET created_at='2000-01-01T00:00:00.000Z',
+ consumed_at='2000-01-01T00:00:00.001Z',
+ expires_at='2000-01-01T00:00:00.002Z'
+ WHERE ticket_hash=?
+ """,
+ (digest,),
+ )
+ await connection.commit()
+ purged = await database.purge_expired_websocket_tickets()
+ after_row_purge = await database.resolve_websocket_ticket_principal(
+ handle
+ )
+ replay = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+
+ await connection.execute("DELETE FROM users WHERE id=?", (user_id,))
+ await connection.commit()
+ deleted = await database.resolve_websocket_ticket_principal(handle)
+
+ active_valid = (
+ active is not None
+ and active_again is not None
+ and active.user_id == user_id
+ and active.role == "operator"
+ )
+ reactivation_valid = (
+ inactive is None
+ and reactivated is not None
+ and reactivated.user_id == user_id
+ )
+ role_matrix_valid = (
+ promoted is not None
+ and promoted.role == "team_lead"
+ and demoted is None
+ and invalid_role is None
+ and current_role is not None
+ and current_role.role == "reporter"
+ )
+ revocation_valid = revoked is None and unrevoked is not None
+ lifetime_valid = (
+ expired_source is None
+ and renamed is None
+ and purged == 1
+ and after_row_purge is not None
+ and replay is None
+ and deleted is None
+ )
+
+ _require_fixed(active_valid, "active bearer authority was incorrect")
+ _require_fixed(
+ reactivation_valid,
+ "bearer reactivation did not use the same authority",
+ )
+ _require_fixed(role_matrix_valid, "bearer role authority was incorrect")
+ _require_fixed(revocation_valid, "bearer revocation authority was incorrect")
+ _require_fixed(lifetime_valid, "bearer handle lifetime rules changed")
+ _require_fixed(read_only, "bearer resolution mutated database state")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_api_key_resolver_complete_authority_mutations(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-api-matrix.db")
+ try:
+ user_id, username, campaign_id, _other_id, key_id = (
+ await _seed_identity(database, scopes="read")
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ ApiKeyTicketSource(user_id=user_id, api_key_id=key_id),
+ )
+ _require_fixed(issued is not None, "API-key ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ handle = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ _require_fixed(handle is not None, "API-key handle setup failed")
+ if handle is None:
+ return
+
+ connection = database.conn
+ async with connection.execute(
+ "SELECT last_used FROM api_keys WHERE id=?",
+ (key_id,),
+ ) as cursor:
+ last_used_before = (await cursor.fetchone())["last_used"]
+
+ read_principal = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE api_keys SET scopes='write' WHERE id=?",
+ (key_id,),
+ )
+ await connection.commit()
+ write_principal = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE api_keys SET scopes='admin' WHERE id=?",
+ (key_id,),
+ )
+ await connection.commit()
+ admin_principal = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE api_keys SET scopes='telemetry' WHERE id=?",
+ (key_id,),
+ )
+ await connection.commit()
+ insufficient = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE api_keys SET scopes='read', is_active=0 WHERE id=?",
+ (key_id,),
+ )
+ await connection.commit()
+ revoked = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE api_keys SET is_active=1 WHERE id=?",
+ (key_id,),
+ )
+ await connection.commit()
+ reactivated = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE api_keys SET expires_at='2000-01-01T00:00:00.000Z' "
+ "WHERE id=?",
+ (key_id,),
+ )
+ await connection.commit()
+ expired = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE api_keys SET expires_at=NULL WHERE id=?",
+ (key_id,),
+ )
+ await connection.execute(
+ "UPDATE users SET is_active=0 WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ owner_inactive = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET is_active=1 WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ owner_reactivated = (
+ await database.resolve_websocket_ticket_principal(handle)
+ )
+
+ renamed_username = f"renamed_{uuid4().hex}"
+ await connection.execute(
+ "UPDATE users SET username=? WHERE id=?",
+ (renamed_username, user_id),
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator=? WHERE id=?",
+ (renamed_username, campaign_id),
+ )
+ await connection.commit()
+ renamed = await database.resolve_websocket_ticket_principal(handle)
+
+ await connection.execute(
+ "UPDATE users SET role='reporter' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ current_role = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET role='unknown-role' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ invalid_role = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET role='operator' WHERE id=?",
+ (user_id,),
+ )
+ await connection.execute(
+ "UPDATE campaigns SET operator='different-operator' WHERE id=?",
+ (campaign_id,),
+ )
+ await connection.commit()
+ reassigned = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET role='team_lead' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ promoted = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE users SET role='operator' WHERE id=?",
+ (user_id,),
+ )
+ await connection.commit()
+ demoted = await database.resolve_websocket_ticket_principal(handle)
+ await connection.execute(
+ "UPDATE campaigns SET operator=? WHERE id=?",
+ (renamed_username, campaign_id),
+ )
+ await connection.commit()
+
+ wrong_key = await database.resolve_websocket_ticket_principal(
+ replace(handle, api_key_id=f"replacement-{uuid4().hex}")
+ )
+ wrong_owner = await database.resolve_websocket_ticket_principal(
+ replace(handle, user_id=f"replacement-{uuid4().hex}")
+ )
+
+ digest = hash_websocket_ticket(raw_ticket)
+ await connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET created_at='2000-01-01T00:00:00.000Z',
+ consumed_at='2000-01-01T00:00:00.001Z',
+ expires_at='2000-01-01T00:00:00.002Z'
+ WHERE ticket_hash=?
+ """,
+ (digest,),
+ )
+ await connection.commit()
+ purged = await database.purge_expired_websocket_tickets()
+ after_row_purge = await database.resolve_websocket_ticket_principal(
+ handle
+ )
+ replay = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ async with connection.execute(
+ "SELECT last_used FROM api_keys WHERE id=?",
+ (key_id,),
+ ) as cursor:
+ last_used_after = (await cursor.fetchone())["last_used"]
+
+ await connection.execute("DELETE FROM api_keys WHERE id=?", (key_id,))
+ replacement_key_id = f"replacement-{uuid4().hex}"
+ await connection.execute(
+ """
+ INSERT INTO api_keys(
+ id, user_id, name, key_hash, key_prefix, scopes
+ )
+ VALUES(?, ?, 'replacement', 'synthetic', 'test', 'read')
+ """,
+ (replacement_key_id, user_id),
+ )
+ await connection.commit()
+ replacement_does_not_match = (
+ await database.resolve_websocket_ticket_principal(handle)
+ )
+ await connection.execute("DELETE FROM users WHERE id=?", (user_id,))
+ await connection.commit()
+ owner_deleted = await database.resolve_websocket_ticket_principal(handle)
+
+ scopes_valid = (
+ read_principal is not None
+ and "read" in read_principal.api_key_scopes
+ and write_principal is not None
+ and "write" in write_principal.api_key_scopes
+ and admin_principal is not None
+ and "admin" in admin_principal.api_key_scopes
+ and insufficient is None
+ )
+ lifecycle_valid = (
+ revoked is None
+ and reactivated is not None
+ and expired is None
+ and owner_inactive is None
+ and owner_reactivated is not None
+ )
+ identity_valid = (
+ renamed is not None
+ and renamed.username == renamed_username
+ and current_role is not None
+ and current_role.role == "reporter"
+ and invalid_role is None
+ )
+ campaign_valid = (
+ reassigned is None
+ and promoted is not None
+ and promoted.role == "team_lead"
+ and demoted is None
+ )
+ stable_binding_valid = (
+ wrong_key is None
+ and wrong_owner is None
+ and replacement_does_not_match is None
+ and owner_deleted is None
+ )
+ lifetime_valid = (
+ purged == 1
+ and after_row_purge is not None
+ and replay is None
+ )
+ read_only = last_used_before == last_used_after
+
+ _require_fixed(scopes_valid, "API-key scope authority was incorrect")
+ _require_fixed(
+ lifecycle_valid,
+ "API-key lifecycle authority was incorrect",
+ )
+ _require_fixed(
+ identity_valid,
+ "API-key canonical identity was incorrect",
+ )
+ _require_fixed(
+ campaign_valid,
+ "API-key campaign authority was incorrect",
+ )
+ _require_fixed(
+ stable_binding_valid,
+ "API-key stable ownership was not enforced",
+ )
+ _require_fixed(lifetime_valid, "API-key handle lifetime rules changed")
+ _require_fixed(read_only, "ticket operations updated API-key usage")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_purge_removes_malformed_expiry_defensively(
+ tmp_path: Path,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-malformed.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ connection = database._require_connected()
+ digest = hash_websocket_ticket(generate_websocket_ticket())
+ canonical_now = (
+ datetime.now(timezone.utc)
+ .isoformat(timespec="milliseconds")
+ .replace("+00:00", "Z")
+ )
+ canonical_source_expiry = (
+ (datetime.now(timezone.utc) + timedelta(minutes=5))
+ .isoformat(timespec="milliseconds")
+ .replace("+00:00", "Z")
+ )
+ await connection.execute("PRAGMA ignore_check_constraints=ON")
+ try:
+ await connection.execute(
+ """
+ INSERT INTO websocket_tickets(
+ ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ created_at, expires_at
+ )
+ VALUES(?, ?, ?, 'bearer', ?, ?, ?, ?, ?)
+ """,
+ (
+ digest,
+ campaign_id,
+ user_id,
+ username,
+ f"malformed-jti-{uuid4().hex}",
+ canonical_source_expiry,
+ canonical_now,
+ "not-a-timestamp",
+ ),
+ )
+ await connection.commit()
+ finally:
+ await connection.execute("PRAGMA ignore_check_constraints=OFF")
+
+ deleted = await database.purge_expired_websocket_tickets()
+ async with connection.execute(
+ "SELECT COUNT(*) AS count FROM websocket_tickets"
+ ) as cursor:
+ remaining = int((await cursor.fetchone())["count"])
+ _require_fixed(deleted == 1, "malformed expiry purge count was wrong")
+ _require_fixed(remaining == 0, "malformed expiry row was retained")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_collision_rolls_back_and_recovers(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-collision.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ fixed_ticket = generate_websocket_ticket()
+ with monkeypatch.context() as patcher:
+ patcher.setattr(
+ "ares.db.database.generate_websocket_ticket",
+ lambda: fixed_ticket,
+ )
+ first = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(first is not None, "collision setup failed")
+ collision_rejected = False
+ try:
+ await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ except aiosqlite.IntegrityError:
+ collision_rejected = True
+
+ consumed = await database.consume_websocket_ticket(
+ fixed_ticket,
+ campaign_id,
+ )
+ recovered = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(
+ consumed is not None,
+ "collision damaged the existing ticket",
+ )
+ _require_fixed(collision_rejected, "ticket collision was not rejected")
+ _require_fixed(recovered is not None, "database did not recover")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_commit_failure_rolls_back_and_recovers(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-commit-failure.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_commit = database._commit_websocket_ticket_operation
+
+ async def failed_commit(connection: Any) -> None:
+ raise RuntimeError("synthetic commit failure")
+
+ monkeypatch.setattr(
+ database,
+ "_commit_websocket_ticket_operation",
+ failed_commit,
+ )
+ failure_type: type[BaseException] | None = None
+ try:
+ await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ except Exception as exc:
+ failure_type = type(exc)
+ monkeypatch.setattr(
+ database,
+ "_commit_websocket_ticket_operation",
+ original_commit,
+ )
+
+ connection = database._require_connected()
+ async with connection.execute(
+ "SELECT COUNT(*) AS count FROM websocket_tickets"
+ ) as cursor:
+ count = int((await cursor.fetchone())["count"])
+ recovered = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(
+ failure_type is RuntimeError,
+ "commit failure did not propagate",
+ )
+ _require_fixed(count == 0, "commit failure persisted a ticket")
+ _require_fixed(recovered is not None, "commit failure prevented recovery")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_two_instances_have_one_consumer(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ path = tmp_path / "ticket-concurrency.db"
+ first = await _connected_database(path)
+ second = await _connected_database(path)
+ first_cas_won = asyncio.Event()
+ release_first = asyncio.Event()
+ second_begin_submitted = asyncio.Event()
+ second_begin_acquired = asyncio.Event()
+ first_task: asyncio.Task[ConsumedWebSocketTicket | None] | None = None
+ second_task: asyncio.Task[ConsumedWebSocketTicket | None] | None = None
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(first)
+ )
+ issued = await first.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+
+ original_first_open = first._open_websocket_ticket_connection
+ original_second_open = second._open_websocket_ticket_connection
+ first_proxy: _TicketConnectionProxy | None = None
+ second_proxy: _TicketConnectionProxy | None = None
+
+ async def open_first() -> Any:
+ nonlocal first_proxy
+ first_proxy = _TicketConnectionProxy(
+ await original_first_open(),
+ cas_entered=first_cas_won,
+ cas_release=release_first,
+ )
+ return first_proxy
+
+ async def open_second() -> Any:
+ nonlocal second_proxy
+ connection = await original_second_open()
+ loop = asyncio.get_running_loop()
+
+ def trace(statement: str) -> None:
+ if " ".join(statement.upper().split()) == "BEGIN IMMEDIATE":
+ loop.call_soon_threadsafe(second_begin_submitted.set)
+
+ await connection.set_trace_callback(trace)
+ second_proxy = _TicketConnectionProxy(
+ connection,
+ begin_acquired=second_begin_acquired,
+ )
+ return second_proxy
+
+ monkeypatch.setattr(
+ first,
+ "_open_websocket_ticket_connection",
+ open_first,
+ )
+ monkeypatch.setattr(
+ second,
+ "_open_websocket_ticket_connection",
+ open_second,
+ )
+
+ first_task = asyncio.create_task(
+ first.consume_websocket_ticket(raw_ticket, campaign_id)
+ )
+ await asyncio.wait_for(first_cas_won.wait(), timeout=5)
+
+ lock_probe = sqlite3.connect(path, timeout=0)
+ writer_lock_observed = False
+ try:
+ try:
+ lock_probe.execute("BEGIN IMMEDIATE")
+ except sqlite3.OperationalError:
+ writer_lock_observed = True
+ else:
+ lock_probe.rollback()
+ finally:
+ lock_probe.close()
+
+ second_task = asyncio.create_task(
+ second.consume_websocket_ticket(raw_ticket, campaign_id)
+ )
+ await asyncio.wait_for(second_begin_submitted.wait(), timeout=5)
+ second_waiting = (
+ not second_begin_acquired.is_set()
+ and not second_task.done()
+ )
+
+ release_first.set()
+ results = await asyncio.wait_for(
+ asyncio.gather(first_task, second_task),
+ timeout=10,
+ )
+ winner_count = sum(result is not None for result in results)
+ durable_count = await _consumed_ticket_count(first)
+ first_reusable = await first.conn.execute_fetchall("SELECT 1")
+ second_reusable = await second.conn.execute_fetchall("SELECT 1")
+ first_order = (
+ tuple(first_proxy.statement_order)
+ if first_proxy is not None
+ else ()
+ )
+ second_order = (
+ tuple(second_proxy.statement_order)
+ if second_proxy is not None
+ else ()
+ )
+
+ _require_fixed(
+ writer_lock_observed,
+ "first consumer did not hold the physical writer lock",
+ )
+ _require_fixed(
+ second_waiting,
+ "second consumer did not wait on the writer lock",
+ )
+ _require_fixed(winner_count == 1, "ticket did not have one consumer")
+ _require_fixed(
+ durable_count == 1,
+ "ticket consumption was not durable exactly once",
+ )
+ _require_fixed(
+ first_order
+ == (
+ "BEGIN IMMEDIATE",
+ "CAS UPDATE",
+ "HANDLE SELECT",
+ "COMMIT",
+ ),
+ "winning ticket statement order changed",
+ )
+ _require_fixed(
+ second_order
+ == ("BEGIN IMMEDIATE", "CAS UPDATE", "COMMIT"),
+ "losing ticket statement order changed",
+ )
+ _require_fixed(
+ bool(first_reusable) and bool(second_reusable),
+ "ticket contention left a connection unusable",
+ )
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "ticket operation left an owned task",
+ )
+ finally:
+ release_first.set()
+ pending = [
+ task
+ for task in (first_task, second_task)
+ if task is not None and not task.done()
+ ]
+ for task in pending:
+ task.cancel()
+ if pending:
+ await asyncio.gather(*pending, return_exceptions=True)
+ await second.close()
+ await first.close()
+
+
+async def test_sqlite_lifecycle_and_relative_identity(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ original_cwd = Path.cwd()
+ first_directory = tmp_path / "first"
+ second_directory = tmp_path / "second"
+ first_directory.mkdir()
+ second_directory.mkdir()
+ database: AresDatabase | None = None
+ try:
+ monkeypatch.chdir(first_directory)
+ database = AresDatabase("relative-ticket.db")
+ with pytest.raises(RuntimeError):
+ await database.issue_websocket_ticket(
+ "campaign-before-connect",
+ _bearer_source("user-before-connect", "before-connect"),
+ )
+ await database.connect()
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ monkeypatch.chdir(second_directory)
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "relative database identity changed")
+ alternate_absent = not (second_directory / "relative-ticket.db").exists()
+ _require_fixed(
+ alternate_absent,
+ "CWD change created an alternate database",
+ )
+ await database.close()
+ with pytest.raises(RuntimeError):
+ await database.consume_websocket_ticket(
+ (issued or ("", 0))[0],
+ campaign_id,
+ )
+ finally:
+ if database is not None and database._conn is not None:
+ await database.close()
+ os.chdir(original_cwd)
+
+
+async def test_sqlite_transaction_order_contains_required_cas(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-order.db")
+ statements: list[str] = []
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ original_open = database._open_websocket_ticket_connection
+
+ async def traced_open() -> Any:
+ connection = await original_open()
+
+ def trace(statement: str) -> None:
+ normalized = " ".join(statement.upper().split())
+ if normalized == "BEGIN IMMEDIATE":
+ statements.append("BEGIN IMMEDIATE")
+ elif normalized.startswith("UPDATE WEBSOCKET_TICKETS"):
+ statements.append("CAS UPDATE")
+ elif (
+ normalized.startswith("SELECT ")
+ and "FROM WEBSOCKET_TICKETS" in normalized
+ ):
+ statements.append("HANDLE SELECT")
+ elif normalized == "COMMIT":
+ statements.append("COMMIT")
+
+ await connection.set_trace_callback(trace)
+ return connection
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ traced_open,
+ )
+ consumed = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ _require_fixed(consumed is not None, "traced consume failed")
+ _require_fixed(
+ tuple(statements)
+ == ("BEGIN IMMEDIATE", "CAS UPDATE", "HANDLE SELECT", "COMMIT"),
+ "ticket transaction statement order changed",
+ )
+ finally:
+ await database.close()
+
+
+async def test_sqlite_cancellation_before_commit_rolls_back(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-cancel-before.db")
+ entered = asyncio.Event()
+ release = asyncio.Event()
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_purge = database._purge_websocket_ticket_rows
+
+ async def paused_purge(connection: Any) -> int:
+ count = await original_purge(connection)
+ entered.set()
+ await asyncio.wait_for(release.wait(), timeout=5)
+ return count
+
+ monkeypatch.setattr(
+ database,
+ "_purge_websocket_ticket_rows",
+ paused_purge,
+ )
+ task = asyncio.create_task(
+ database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ )
+ await asyncio.wait_for(entered.wait(), timeout=5)
+ task.cancel()
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, timeout=5)
+
+ connection = database._require_connected()
+ async with connection.execute(
+ "SELECT COUNT(*) AS count FROM websocket_tickets"
+ ) as cursor:
+ count = int((await cursor.fetchone())["count"])
+ _require_fixed(count == 0, "pre-commit cancellation persisted a ticket")
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "pre-commit cancellation left an owned task",
+ )
+ finally:
+ release.set()
+ await database.close()
+
+
+async def test_sqlite_cancellation_after_real_commit_returns_result(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-cancel-commit.db")
+ commit_started = asyncio.Event()
+ release_commit = threading.Event()
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_open = database._open_websocket_ticket_connection
+ loop = asyncio.get_running_loop()
+
+ async def traced_open() -> Any:
+ connection = await original_open()
+
+ def trace(statement: str) -> None:
+ if " ".join(statement.upper().split()) == "COMMIT":
+ loop.call_soon_threadsafe(commit_started.set)
+ release_commit.wait(timeout=5)
+
+ await connection.set_trace_callback(trace)
+ return connection
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ traced_open,
+ )
+ task = asyncio.create_task(
+ database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ )
+ await asyncio.wait_for(commit_started.wait(), timeout=5)
+ baseline = task.cancelling()
+ task.cancel()
+ release_commit.set()
+ result = await asyncio.wait_for(task, timeout=5)
+ normalized = (
+ result is not None
+ and not task.cancelled()
+ and task.cancelling() == baseline
+ )
+ _require_fixed(
+ normalized,
+ "post-commit cancellation was not normalized",
+ )
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "post-commit cancellation left an owned task",
+ )
+ finally:
+ release_commit.set()
+ await database.close()
+
+
+async def test_sqlite_consume_cancellation_after_real_cas_rolls_back(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-cancel-cas.db")
+ cas_won = asyncio.Event()
+ release = asyncio.Event()
+ consume_task: asyncio.Task[ConsumedWebSocketTicket | None] | None = None
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ raw_ticket = (issued or ("", 0))[0]
+ original_open = database._open_websocket_ticket_connection
+
+ async def open_paused() -> Any:
+ return _TicketConnectionProxy(
+ await original_open(),
+ cas_entered=cas_won,
+ cas_release=release,
+ )
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ open_paused,
+ )
+ consume_task = asyncio.create_task(
+ database.consume_websocket_ticket(raw_ticket, campaign_id)
+ )
+ await asyncio.wait_for(cas_won.wait(), timeout=5)
+ consume_task.cancel()
+ release.set()
+ cancelled = False
+ try:
+ await asyncio.wait_for(consume_task, timeout=5)
+ except asyncio.CancelledError:
+ cancelled = True
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ original_open,
+ )
+ durable_before_retry = await _consumed_ticket_count(database)
+ retry = await database.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ _require_fixed(cancelled, "consume cancellation did not propagate")
+ _require_fixed(
+ durable_before_retry == 0,
+ "cancelled consume committed the CAS",
+ )
+ _require_fixed(retry is not None, "cancelled consume did not recover")
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "cancelled consume left an owned task",
+ )
+ finally:
+ release.set()
+ if consume_task is not None and not consume_task.done():
+ consume_task.cancel()
+ await asyncio.gather(consume_task, return_exceptions=True)
+ await database.close()
+
+
+async def test_sqlite_repeated_commit_cancellation_preserves_existing_debt(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-cancel-debt.db")
+ commit_started = asyncio.Event()
+ release_commit = threading.Event()
+ task: asyncio.Task[Any] | None = None
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_open = database._open_websocket_ticket_connection
+ loop = asyncio.get_running_loop()
+
+ async def traced_open() -> Any:
+ connection = await original_open()
+
+ def trace(statement: str) -> None:
+ if " ".join(statement.upper().split()) == "COMMIT":
+ loop.call_soon_threadsafe(commit_started.set)
+ release_commit.wait(timeout=5)
+
+ await connection.set_trace_callback(trace)
+ return connection
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ traced_open,
+ )
+
+ async def issue_with_existing_debt() -> tuple[Any, int, int]:
+ current = asyncio.current_task()
+ if current is None:
+ raise RuntimeError("ticket cancellation task is unavailable")
+ current.cancel()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ pass
+ entry_debt = current.cancelling()
+ try:
+ result = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ return result, entry_debt, current.cancelling()
+ finally:
+ while current.cancelling():
+ current.uncancel()
+
+ task = asyncio.create_task(issue_with_existing_debt())
+ await asyncio.wait_for(commit_started.wait(), timeout=5)
+ before_new_cancellations = task.cancelling()
+ task.cancel()
+ task.cancel()
+ release_commit.set()
+ result, entry_debt, final_debt = await asyncio.wait_for(
+ task,
+ timeout=5,
+ )
+
+ _require_fixed(result is not None, "committed ticket result was lost")
+ _require_fixed(
+ before_new_cancellations == entry_debt == final_debt == 1,
+ "commit normalization changed pre-existing cancellation debt",
+ )
+ _require_fixed(
+ task.cancelling() == 0,
+ "test cancellation debt was not settled",
+ )
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "repeated cancellation left an owned task",
+ )
+ finally:
+ release_commit.set()
+ if task is not None and not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ await database.close()
+
+
+async def test_sqlite_rollback_cleanup_failure_preserves_primary_and_recovers(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-rollback-error.db")
+ warnings: list[tuple[object, object]] = []
+
+ class PrimaryTicketError(RuntimeError):
+ pass
+
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_open = database._open_websocket_ticket_connection
+
+ async def open_with_failing_rollback() -> Any:
+ connection = await original_open()
+ original_rollback = connection.rollback
+
+ async def rollback_then_fail() -> None:
+ await original_rollback()
+ raise RuntimeError("synthetic cleanup failure")
+
+ monkeypatch.setattr(connection, "rollback", rollback_then_fail)
+ return connection
+
+ async def fail_operation(_connection: Any) -> int:
+ raise PrimaryTicketError("synthetic primary failure")
+
+ def record_warning(_event: str, **values: object) -> None:
+ warnings.append(
+ (values.get("action"), values.get("error_type"))
+ )
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ open_with_failing_rollback,
+ )
+ monkeypatch.setattr(
+ database,
+ "_purge_websocket_ticket_rows",
+ fail_operation,
+ )
+ with patch.object(
+ database_module.logger,
+ "warning",
+ record_warning,
+ ):
+ caught_type: type[BaseException] | None = None
+ try:
+ await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ except BaseException as exc:
+ caught_type = type(exc)
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ original_open,
+ )
+ monkeypatch.undo()
+ recovered = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ cleanup_recorded = (
+ ("rollback-before-commit", "RuntimeError") in warnings
+ )
+
+ _require_fixed(
+ caught_type is PrimaryTicketError,
+ "cleanup failure replaced the primary ticket failure",
+ )
+ _require_fixed(
+ cleanup_recorded,
+ "rollback cleanup failure was not sanitized",
+ )
+ _require_fixed(recovered is not None, "rollback failure blocked recovery")
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "rollback failure left an owned task",
+ )
+ finally:
+ await database.close()
+
+
+async def test_sqlite_close_cleanup_failure_keeps_committed_result(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-close-error.db")
+ warnings: list[tuple[object, object]] = []
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_open = database._open_websocket_ticket_connection
+
+ async def open_with_failing_close() -> Any:
+ connection = await original_open()
+ original_close = connection.close
+
+ async def close_then_fail() -> None:
+ await original_close()
+ raise RuntimeError("synthetic cleanup failure")
+
+ monkeypatch.setattr(connection, "close", close_then_fail)
+ return connection
+
+ def record_warning(_event: str, **values: object) -> None:
+ warnings.append(
+ (values.get("action"), values.get("error_type"))
+ )
+
+ monkeypatch.setattr(
+ database,
+ "_open_websocket_ticket_connection",
+ open_with_failing_close,
+ )
+ with patch.object(
+ database_module.logger,
+ "warning",
+ record_warning,
+ ):
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ close_recorded = ("close", "RuntimeError") in warnings
+
+ _require_fixed(issued is not None, "close failure lost committed result")
+ _require_fixed(
+ await _ticket_count(database) == 1,
+ "close failure changed committed ticket state",
+ )
+ _require_fixed(
+ close_recorded,
+ "close cleanup failure was not sanitized",
+ )
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "close failure left an owned task",
+ )
+ finally:
+ await database.close()
+
+
[email protected]("error_type", [KeyboardInterrupt, SystemExit])
+async def test_sqlite_ticket_control_flow_exceptions_propagate_and_recover(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ error_type: type[BaseException],
+) -> None:
+ database = await _connected_database(
+ tmp_path / f"ticket-control-{error_type.__name__}.db"
+ )
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ original_purge = database._purge_websocket_ticket_rows
+
+ async def raise_control_flow(_connection: Any) -> int:
+ raise error_type()
+
+ monkeypatch.setattr(
+ database,
+ "_purge_websocket_ticket_rows",
+ raise_control_flow,
+ )
+ caught_type: type[BaseException] | None = None
+ try:
+ await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ except BaseException as exc:
+ caught_type = type(exc)
+ monkeypatch.setattr(
+ database,
+ "_purge_websocket_ticket_rows",
+ original_purge,
+ )
+ recovered = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+
+ _require_fixed(
+ caught_type is error_type,
+ "control-flow exception was converted or replaced",
+ )
+ _require_fixed(recovered is not None, "control-flow failure blocked recovery")
+ _require_fixed(
+ not _owned_ticket_tasks(),
+ "control-flow failure left an owned task",
+ )
+ finally:
+ await database.close()
+
+
+async def test_sqlite_purge_uses_protected_transaction_and_recovers(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ database = await _connected_database(tmp_path / "ticket-purge-tx.db")
+ try:
+ user_id, username, campaign_id, _other_id, _key_id = (
+ await _seed_identity(database)
+ )
+ issued = await database.issue_websocket_ticket(
+ campaign_id,
+ _bearer_source(user_id, username),
+ )
+ _require_fixed(issued is not None, "ticket setup failed")
+ digest = hash_websocket_ticket((issued or ("", 0))[0])
+ await database.conn.execute(
+ "UPDATE websocket_tickets "
+ "SET expires_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now') "
+ "WHERE ticket_hash=?",
+ (digest,),
+ )
+ await database.conn.commit()
+ original_commit = database._commit_websocket_ticket_operation
+
+ async def fail_commit(_connection: Any) -> None:
+ raise RuntimeError("synthetic commit failure")
+
+ monkeypatch.setattr(
+ database,
+ "_commit_websocket_ticket_operation",
+ fail_commit,
+ )
+ failed = False
+ try:
+ await database.purge_expired_websocket_tickets()
+ except RuntimeError:
+ failed = True
+ retained = await _ticket_count(database)
+ monkeypatch.setattr(
+ database,
+ "_commit_websocket_ticket_operation",
+ original_commit,
+ )
+ purged = await database.purge_expired_websocket_tickets()
+ remaining = await _ticket_count(database)
+
+ _require_fixed(failed, "purge commit failure did not propagate")
+ _require_fixed(retained == 1, "failed purge committed a deletion")
+ _require_fixed(purged == 1, "recovered purge count changed")
+ _require_fixed(remaining == 0, "recovered purge left an expired row")
+ finally:
+ await database.close()
diff --git a/tests/unit/test_websocket_ticket_migration.py b/tests/unit/test_websocket_ticket_migration.py
new file mode 100644
index 0000000..f10cac0
--- /dev/null
+++ b/tests/unit/test_websocket_ticket_migration.py
@@ -0,0 +1,1821 @@
+"""Real SQLite migration and bootstrap proof for WebSocket ticket storage."""
+from __future__ import annotations
+
+import argparse
+import asyncio
+import importlib
+import re
+import sqlite3
+from collections.abc import Callable, Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+import pytest
+from alembic import command
+from alembic.config import Config
+
+from ares.db.database import AresDatabase
+from ares.db.schema import SCHEMA_VERSION
+from ares.db.websocket_tickets import ApiKeyTicketSource
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+_TICKET_TABLE = "websocket_tickets"
+_TICKET_INDEX_NAMES = (
+ "idx_ws_tickets_api_key",
+ "idx_ws_tickets_campaign",
+ "idx_ws_tickets_expires",
+ "idx_ws_tickets_user",
+)
+_CHECK_NAMES = (
+ "ck_ws_ticket_consumed_at",
+ "ck_ws_ticket_created_at",
+ "ck_ws_ticket_expires_at",
+ "ck_ws_ticket_hash",
+ "ck_ws_ticket_kind",
+ "ck_ws_ticket_source_shape",
+ "ck_ws_ticket_time_order",
+)
+_FOREIGN_KEY_NAMES = (
+ "fk_ws_ticket_api_key",
+ "fk_ws_ticket_campaign",
+ "fk_ws_ticket_user",
+)
+
+
+@dataclass(frozen=True, slots=True)
+class _ColumnContract:
+ ordinal: int
+ name: str
+ logical_type: str
+ nullable: bool
+ default: str | None
+ primary_key_position: int
+ hidden: int
+
+
+@dataclass(frozen=True, slots=True)
+class _ForeignKeyContract:
+ local_column: str
+ target_table: str
+ target_column: str
+ on_update: str
+ on_delete: str
+ match: str
+
+
+@dataclass(frozen=True, slots=True)
+class _IndexContract:
+ name: str
+ unique: bool
+ origin: str
+ partial: bool
+ columns: tuple[tuple[str, bool, str], ...]
+
+
+@dataclass(frozen=True, slots=True)
+class _ManagedPrimaryKeyIndexContract:
+ unique: bool
+ origin: str
+ partial: bool
+ structure: tuple[
+ tuple[int, int, str | None, bool, str, bool],
+ ...,
+ ]
+ schema_objects: tuple[tuple[str, str, bool], ...]
+
+
+@dataclass(frozen=True, slots=True)
+class _AttachedObjectContract:
+ object_type: str
+ name: str
+ table_name: str
+ definition: str | None
+
+
+@dataclass(frozen=True, slots=True)
+class _TicketContract:
+ columns: tuple[_ColumnContract, ...]
+ primary_key: tuple[str, ...]
+ foreign_keys: tuple[_ForeignKeyContract, ...]
+ checks: tuple[tuple[str, str], ...]
+ indexes: tuple[_IndexContract, ...]
+ managed_primary_key_indexes: tuple[
+ _ManagedPrimaryKeyIndexContract,
+ ...,
+ ]
+ attached_objects: tuple[_AttachedObjectContract, ...]
+ named_constraints: tuple[str, ...]
+ canonical_table: bool
+ named_foreign_keys_bound: tuple[str, ...]
+
+
+def _require_fixed(condition: bool, message: str) -> None:
+ if not condition:
+ pytest.fail(message, pytrace=False)
+
+
+@contextmanager
+def _temporary_database(label: str) -> Iterator[Path]:
+ with TemporaryDirectory(prefix="ares-ws-ticket-migration-") as directory:
+ yield Path(directory) / f"{label}.db"
+
+
+def _alembic_config(path: Path) -> Config:
+ url = f"sqlite:///{path.resolve().as_posix()}"
+ config = Config(str(_REPO_ROOT / "alembic.ini"))
+ config.set_main_option(
+ "script_location",
+ str(_REPO_ROOT / "migrations"),
+ )
+ config.set_main_option("sqlalchemy.url", "sqlite:///unused.db")
+ config.cmd_opts = argparse.Namespace(x=[f"db_url={url}"])
+ return config
+
+
+def _upgrade(path: Path, revision: str) -> None:
+ try:
+ command.upgrade(_alembic_config(path), revision)
+ except Exception as exc:
+ raise RuntimeError(
+ "SQLite ticket migration failed "
+ f"[upgrade: {type(exc).__name__}]"
+ ) from None
+
+
+def _downgrade(path: Path, revision: str) -> None:
+ try:
+ command.downgrade(_alembic_config(path), revision)
+ except Exception as exc:
+ raise RuntimeError(
+ "SQLite ticket migration failed "
+ f"[downgrade: {type(exc).__name__}]"
+ ) from None
+
+
+def _connect(path: Path) -> sqlite3.Connection:
+ connection = sqlite3.connect(path)
+ connection.row_factory = sqlite3.Row
+ connection.execute("PRAGMA foreign_keys=ON")
+ return connection
+
+
+def _version(path: Path) -> str | None:
+ connection = _connect(path)
+ try:
+ exists = connection.execute(
+ "SELECT 1 FROM sqlite_master "
+ "WHERE type='table' AND name='alembic_version'"
+ ).fetchone()
+ if exists is None:
+ return None
+ row = connection.execute(
+ "SELECT version_num FROM alembic_version"
+ ).fetchone()
+ return str(row[0]) if row is not None else None
+ finally:
+ connection.close()
+
+
+def _application_tables(path: Path) -> tuple[str, ...]:
+ connection = _connect(path)
+ try:
+ return tuple(
+ str(row[0])
+ for row in connection.execute(
+ "SELECT name FROM sqlite_master "
+ "WHERE type='table' AND name NOT LIKE 'sqlite_%' "
+ "ORDER BY name"
+ )
+ )
+ finally:
+ connection.close()
+
+
+def _compact_sql(value: str) -> str:
+ compact: list[str] = []
+ quote: str | None = None
+ index = 0
+ while index < len(value):
+ character = value[index]
+ if quote is not None:
+ compact.append(character)
+ if character == quote:
+ if index + 1 < len(value) and value[index + 1] == quote:
+ compact.append(value[index + 1])
+ index += 1
+ else:
+ quote = None
+ elif character in {"'", '"', "`"}:
+ quote = character
+ compact.append(character)
+ elif character == "[":
+ quote = "]"
+ compact.append(character)
+ elif not character.isspace():
+ compact.append(character.lower())
+ index += 1
+ if quote is not None:
+ raise RuntimeError("Malformed WebSocket ticket SQL")
+ return "".join(compact)
+
+
+def _parenthesized_sql(value: str, open_index: int) -> tuple[str, int]:
+ depth = 0
+ quote: str | None = None
+ index = open_index
+ while index < len(value):
+ character = value[index]
+ if quote is not None:
+ if character == quote:
+ if index + 1 < len(value) and value[index + 1] == quote:
+ index += 2
+ continue
+ quote = None
+ elif character in {"'", '"'}:
+ quote = character
+ elif character == "(":
+ depth += 1
+ elif character == ")":
+ depth -= 1
+ if depth == 0:
+ return value[open_index + 1:index], index
+ index += 1
+ raise RuntimeError("Malformed WebSocket ticket table definition")
+
+
+def _named_checks(table_sql: str) -> tuple[tuple[str, str], ...]:
+ checks: list[tuple[str, str]] = []
+ pattern = re.compile(
+ r"\bCONSTRAINT\s+[\"`\[]?([A-Za-z0-9_]+)[\"`\]]?"
+ r"\s+CHECK\s*\(",
+ re.IGNORECASE,
+ )
+ for match in pattern.finditer(table_sql):
+ expression, _end = _parenthesized_sql(table_sql, match.end() - 1)
+ checks.append((match.group(1), _compact_sql(expression)))
+ return tuple(sorted(checks))
+
+
+def _named_constraints(table_sql: str) -> tuple[str, ...]:
+ names = re.findall(
+ r"\bCONSTRAINT\s+[\"`\[]?([A-Za-z0-9_]+)[\"`\]]?",
+ table_sql,
+ flags=re.IGNORECASE,
+ )
+ return tuple(sorted(names))
+
+
+def _named_foreign_keys_bound(table_sql: str) -> tuple[str, ...]:
+ compact = _compact_sql(table_sql)
+ expected = {
+ "fk_ws_ticket_campaign": (
+ "campaign_id",
+ "campaigns",
+ "id",
+ True,
+ ),
+ "fk_ws_ticket_user": ("user_id", "users", "id", True),
+ "fk_ws_ticket_api_key": (
+ "api_key_id",
+ "api_keys",
+ "id",
+ False,
+ ),
+ }
+ bound: list[str] = []
+ for name, (local, target, remote, required) in expected.items():
+ update_action = "(?:onupdatenoaction)?"
+ table_pattern = re.compile(
+ f"constraint{name}foreignkey\\({local}\\)"
+ f"references{target}\\({remote}\\)"
+ f"{update_action}ondeletecascade"
+ )
+ nullable = "notnull" if required else "(?:notnull)?"
+ inline_pattern = re.compile(
+ f"{local}text{nullable}constraint{name}"
+ f"references{target}\\({remote}\\)"
+ f"{update_action}ondeletecascade"
+ )
+ if (
+ table_pattern.search(compact) is not None
+ or inline_pattern.search(compact) is not None
+ ):
+ bound.append(name)
+ return tuple(sorted(bound))
+
+
+def _ticket_contract(path: Path) -> _TicketContract | None:
+ connection = _connect(path)
+ try:
+ table_row = connection.execute(
+ "SELECT sql FROM sqlite_master "
+ "WHERE type='table' AND name=?",
+ (_TICKET_TABLE,),
+ ).fetchone()
+ if table_row is None:
+ return None
+ table_sql = str(table_row[0] or "")
+ column_rows = connection.execute(
+ f"PRAGMA table_xinfo({_TICKET_TABLE})"
+ ).fetchall()
+ columns = tuple(
+ _ColumnContract(
+ ordinal=int(row["cid"]),
+ name=str(row["name"]),
+ logical_type=str(row["type"]).upper(),
+ nullable=not bool(row["notnull"]),
+ default=(
+ None
+ if row["dflt_value"] is None
+ else _compact_sql(str(row["dflt_value"]))
+ ),
+ primary_key_position=int(row["pk"]),
+ hidden=int(row["hidden"]),
+ )
+ for row in column_rows
+ )
+ primary_key = tuple(
+ column.name
+ for column in sorted(
+ (item for item in columns if item.primary_key_position),
+ key=lambda item: item.primary_key_position,
+ )
+ )
+ foreign_keys = tuple(
+ sorted(
+ (
+ _ForeignKeyContract(
+ local_column=str(row["from"]),
+ target_table=str(row["table"]),
+ target_column=str(row["to"]),
+ on_update=str(row["on_update"]).upper(),
+ on_delete=str(row["on_delete"]).upper(),
+ match=str(row["match"]).upper(),
+ )
+ for row in connection.execute(
+ f"PRAGMA foreign_key_list({_TICKET_TABLE})"
+ )
+ ),
+ key=lambda item: item.local_column,
+ )
+ )
+ indexes: list[_IndexContract] = []
+ managed_primary_key_indexes: list[
+ _ManagedPrimaryKeyIndexContract
+ ] = []
+ managed_primary_key_names: set[str] = set()
+ for row in connection.execute(
+ f"PRAGMA index_list({_TICKET_TABLE})"
+ ):
+ name = str(row["name"])
+ index_details = tuple(
+ (
+ int(detail["seqno"]),
+ int(detail["cid"]),
+ None
+ if detail["name"] is None
+ else str(detail["name"]),
+ bool(detail["desc"]),
+ str(detail["coll"]).upper(),
+ bool(detail["key"]),
+ )
+ for detail in connection.execute(
+ f"PRAGMA index_xinfo('{name}')"
+ )
+ )
+ origin = str(row["origin"]).lower()
+ if origin == "pk":
+ managed_primary_key_names.add(name)
+ schema_objects = tuple(
+ (
+ str(schema_row["type"]),
+ str(schema_row["tbl_name"]),
+ schema_row["sql"] is None,
+ )
+ for schema_row in connection.execute(
+ "SELECT type, tbl_name, sql "
+ "FROM sqlite_schema WHERE name=?",
+ (name,),
+ )
+ )
+ managed_primary_key_indexes.append(
+ _ManagedPrimaryKeyIndexContract(
+ unique=bool(row["unique"]),
+ origin=origin,
+ partial=bool(row["partial"]),
+ structure=index_details,
+ schema_objects=schema_objects,
+ )
+ )
+ continue
+ indexes.append(
+ _IndexContract(
+ name=name,
+ unique=bool(row["unique"]),
+ origin=origin,
+ partial=bool(row["partial"]),
+ columns=tuple(
+ (
+ str(detail[2]),
+ detail[3],
+ detail[4],
+ )
+ for detail in index_details
+ if detail[5]
+ ),
+ )
+ )
+ compact_table = _compact_sql(table_sql)
+ canonical_table = (
+ (
+ compact_table.startswith(
+ "createtablewebsocket_tickets("
+ )
+ or compact_table.startswith(
+ "createtableifnotexistswebsocket_tickets("
+ )
+ )
+ and all(
+ forbidden not in compact_table
+ for forbidden in (
+ "withoutrowid",
+ "strict",
+ "collate",
+ "onconflict",
+ "deferrable",
+ "initiallydeferred",
+ "initiallyimmediate",
+ )
+ )
+ and len(re.findall(r"\bCHECK\s*\(", table_sql, re.IGNORECASE))
+ == len(_CHECK_NAMES)
+ )
+ attached_objects = tuple(
+ _AttachedObjectContract(
+ object_type=str(row["type"]),
+ name=str(row["name"]),
+ table_name=str(row["tbl_name"]),
+ definition=(
+ None
+ if row["sql"] is None
+ else (
+ "ordinary-ticket-table"
+ if str(row["type"]) == "table"
+ and str(row["name"]) == _TICKET_TABLE
+ and str(row["tbl_name"]) == _TICKET_TABLE
+ else _compact_sql(str(row["sql"])).replace(
+ "createindexifnotexists",
+ "createindex",
+ 1,
+ )
+ )
+ ),
+ )
+ for row in connection.execute(
+ "SELECT type, name, tbl_name, sql "
+ "FROM sqlite_schema WHERE tbl_name=? "
+ "ORDER BY type, name",
+ (_TICKET_TABLE,),
+ )
+ if not (
+ str(row["type"]) == "index"
+ and str(row["name"]) in managed_primary_key_names
+ )
+ )
+ return _TicketContract(
+ columns=columns,
+ primary_key=primary_key,
+ foreign_keys=foreign_keys,
+ checks=_named_checks(table_sql),
+ indexes=tuple(sorted(indexes, key=lambda item: item.name)),
+ managed_primary_key_indexes=tuple(
+ managed_primary_key_indexes
+ ),
+ attached_objects=attached_objects,
+ named_constraints=_named_constraints(table_sql),
+ canonical_table=canonical_table,
+ named_foreign_keys_bound=_named_foreign_keys_bound(table_sql),
+ )
+ finally:
+ connection.close()
+
+
+def _expected_ticket_contract() -> _TicketContract:
+ columns = (
+ _ColumnContract(0, "ticket_hash", "TEXT", False, None, 1, 0),
+ _ColumnContract(1, "campaign_id", "TEXT", False, None, 0, 0),
+ _ColumnContract(2, "user_id", "TEXT", False, None, 0, 0),
+ _ColumnContract(3, "credential_kind", "TEXT", False, None, 0, 0),
+ _ColumnContract(4, "bearer_subject", "TEXT", True, None, 0, 0),
+ _ColumnContract(5, "bearer_jti", "TEXT", True, None, 0, 0),
+ _ColumnContract(6, "bearer_expires_at", "TEXT", True, None, 0, 0),
+ _ColumnContract(7, "api_key_id", "TEXT", True, None, 0, 0),
+ _ColumnContract(8, "required_scope", "TEXT", True, None, 0, 0),
+ _ColumnContract(9, "created_at", "TEXT", False, None, 0, 0),
+ _ColumnContract(10, "expires_at", "TEXT", False, None, 0, 0),
+ _ColumnContract(11, "consumed_at", "TEXT", True, None, 0, 0),
+ )
+ checks = {
+ "ck_ws_ticket_hash": (
+ "length(ticket_hash)=64 "
+ "AND ticket_hash NOT GLOB '*[^0-9a-f]*'"
+ ),
+ "ck_ws_ticket_kind": (
+ "credential_kind IN ('bearer', 'api_key')"
+ ),
+ "ck_ws_ticket_created_at": (
+ "strftime('%Y-%m-%dT%H:%M:%fZ', created_at) IS NOT NULL "
+ "AND strftime('%Y-%m-%dT%H:%M:%fZ', created_at)=created_at"
+ ),
+ "ck_ws_ticket_expires_at": (
+ "strftime('%Y-%m-%dT%H:%M:%fZ', expires_at) IS NOT NULL "
+ "AND strftime('%Y-%m-%dT%H:%M:%fZ', expires_at)=expires_at"
+ ),
+ "ck_ws_ticket_consumed_at": (
+ "consumed_at IS NULL OR ("
+ "strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at) IS NOT NULL "
+ "AND strftime('%Y-%m-%dT%H:%M:%fZ', consumed_at)=consumed_at)"
+ ),
+ "ck_ws_ticket_time_order": (
+ "julianday(expires_at) > julianday(created_at) "
+ "AND (consumed_at IS NULL "
+ "OR julianday(consumed_at) < julianday(expires_at))"
+ ),
+ "ck_ws_ticket_source_shape": """
+ (
+ credential_kind='bearer'
+ AND bearer_subject IS NOT NULL
+ AND length(trim(bearer_subject)) > 0
+ AND bearer_subject=trim(bearer_subject)
+ AND bearer_jti IS NOT NULL
+ AND length(trim(bearer_jti)) > 0
+ AND bearer_jti=trim(bearer_jti)
+ AND bearer_expires_at IS NOT NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
+ ) IS NOT NULL
+ AND strftime(
+ '%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
+ )=bearer_expires_at
+ AND api_key_id IS NULL
+ AND required_scope IS NULL
+ )
+ OR
+ (
+ credential_kind='api_key'
+ AND bearer_subject IS NULL
+ AND bearer_jti IS NULL
+ AND bearer_expires_at IS NULL
+ AND api_key_id IS NOT NULL
+ AND length(trim(api_key_id)) > 0
+ AND api_key_id=trim(api_key_id)
+ AND required_scope='read'
+ )
+ """,
+ }
+ indexes = (
+ _IndexContract(
+ "idx_ws_tickets_api_key",
+ False,
+ "c",
+ False,
+ (("api_key_id", False, "BINARY"),),
+ ),
+ _IndexContract(
+ "idx_ws_tickets_campaign",
+ False,
+ "c",
+ False,
+ (("campaign_id", False, "BINARY"),),
+ ),
+ _IndexContract(
+ "idx_ws_tickets_expires",
+ False,
+ "c",
+ False,
+ (("expires_at", False, "BINARY"),),
+ ),
+ _IndexContract(
+ "idx_ws_tickets_user",
+ False,
+ "c",
+ False,
+ (("user_id", False, "BINARY"),),
+ ),
+ )
+ managed_primary_key_indexes = (
+ _ManagedPrimaryKeyIndexContract(
+ unique=True,
+ origin="pk",
+ partial=False,
+ structure=(
+ (0, 0, "ticket_hash", False, "BINARY", True),
+ (1, -1, None, False, "BINARY", False),
+ ),
+ schema_objects=(("index", _TICKET_TABLE, True),),
+ ),
+ )
+ attached_objects = (
+ _AttachedObjectContract(
+ "index",
+ "idx_ws_tickets_api_key",
+ _TICKET_TABLE,
+ "createindexidx_ws_tickets_api_key"
+ "onwebsocket_tickets(api_key_id)",
+ ),
+ _AttachedObjectContract(
+ "index",
+ "idx_ws_tickets_campaign",
+ _TICKET_TABLE,
+ "createindexidx_ws_tickets_campaign"
+ "onwebsocket_tickets(campaign_id)",
+ ),
+ _AttachedObjectContract(
+ "index",
+ "idx_ws_tickets_expires",
+ _TICKET_TABLE,
+ "createindexidx_ws_tickets_expires"
+ "onwebsocket_tickets(expires_at)",
+ ),
+ _AttachedObjectContract(
+ "index",
+ "idx_ws_tickets_user",
+ _TICKET_TABLE,
+ "createindexidx_ws_tickets_user"
+ "onwebsocket_tickets(user_id)",
+ ),
+ _AttachedObjectContract(
+ "table",
+ _TICKET_TABLE,
+ _TICKET_TABLE,
+ "ordinary-ticket-table",
+ ),
+ )
+ return _TicketContract(
+ columns=columns,
+ primary_key=("ticket_hash",),
+ foreign_keys=(
+ _ForeignKeyContract(
+ "api_key_id",
+ "api_keys",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ "NONE",
+ ),
+ _ForeignKeyContract(
+ "campaign_id",
+ "campaigns",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ "NONE",
+ ),
+ _ForeignKeyContract(
+ "user_id",
+ "users",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ "NONE",
+ ),
+ ),
+ checks=tuple(
+ sorted(
+ (name, _compact_sql(expression))
+ for name, expression in checks.items()
+ )
+ ),
+ indexes=indexes,
+ managed_primary_key_indexes=managed_primary_key_indexes,
+ attached_objects=attached_objects,
+ named_constraints=tuple(
+ sorted(_CHECK_NAMES + _FOREIGN_KEY_NAMES)
+ ),
+ canonical_table=True,
+ named_foreign_keys_bound=tuple(sorted(_FOREIGN_KEY_NAMES)),
+ )
+
+
+_EXPECTED_TICKET_CONTRACT = _expected_ticket_contract()
+
+
+def _schema_snapshot(path: Path) -> tuple[tuple[str, str, str], ...]:
+ connection = _connect(path)
+ try:
+ return tuple(
+ (
+ str(row["type"]),
+ str(row["name"]),
+ _compact_sql(str(row["sql"] or "")),
+ )
+ for row in connection.execute(
+ "SELECT type, name, sql FROM sqlite_master "
+ "WHERE name NOT LIKE 'sqlite_%' "
+ "ORDER BY type, name"
+ )
+ )
+ finally:
+ connection.close()
+
+
+def _complete_schema_snapshot(
+ path: Path,
+) -> tuple[tuple[str, str, str, str], ...]:
+ connection = _connect(path)
+ try:
+ return tuple(
+ (
+ str(row["type"]),
+ str(row["name"]),
+ str(row["tbl_name"]),
+ _compact_sql(str(row["sql"] or "")),
+ )
+ for row in connection.execute(
+ "SELECT type, name, tbl_name, sql FROM sqlite_schema "
+ "ORDER BY type, name, tbl_name",
+ )
+ )
+ finally:
+ connection.close()
+
+
+def _ticket_data_snapshot(path: Path) -> tuple[tuple[object, ...], ...]:
+ connection = _connect(path)
+ try:
+ return tuple(
+ tuple(row)
+ for row in connection.execute(
+ """
+ SELECT ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope, created_at, expires_at,
+ consumed_at
+ FROM websocket_tickets
+ ORDER BY ticket_hash
+ """
+ )
+ )
+ finally:
+ connection.close()
+
+
+def _non_ticket_snapshot(path: Path) -> tuple[tuple[str, str, str], ...]:
+ return tuple(
+ item
+ for item in _schema_snapshot(path)
+ if item[1] != _TICKET_TABLE
+ and item[1] not in _TICKET_INDEX_NAMES
+ and item[1] != "alembic_version"
+ )
+
+
+def _seed_parent_rows(connection: sqlite3.Connection) -> None:
+ connection.execute(
+ """
+ INSERT INTO users(
+ id, username, hashed_password, role, is_active, created_by
+ ) VALUES(?, ?, ?, ?, 1, ?)
+ """,
+ (
+ "ticket-user",
+ "ticket-user-name",
+ "synthetic-password-hash",
+ "operator",
+ "system",
+ ),
+ )
+ connection.execute(
+ "INSERT INTO campaigns(id, name, operator) VALUES(?, ?, ?)",
+ ("ticket-campaign", "Ticket campaign", "ticket-user-name"),
+ )
+ connection.execute(
+ """
+ INSERT INTO api_keys(
+ id, user_id, name, key_hash, key_prefix, scopes, is_active
+ ) VALUES(?, ?, ?, ?, ?, ?, 1)
+ """,
+ (
+ "ticket-api-key",
+ "ticket-user",
+ "Ticket key",
+ "0" * 64,
+ "synthetic",
+ "read",
+ ),
+ )
+ connection.commit()
+
+
+def _parent_row_count(connection: sqlite3.Connection) -> int:
+ row = connection.execute(
+ """
+ SELECT
+ (SELECT COUNT(*) FROM users)
+ + (SELECT COUNT(*) FROM campaigns)
+ + (SELECT COUNT(*) FROM api_keys)
+ """
+ ).fetchone()
+ return int(row[0]) if row is not None else -1
+
+
+def _insert_bearer_ticket(
+ connection: sqlite3.Connection,
+ *,
+ digest_character: str = "a",
+ campaign_id: str = "ticket-campaign",
+ credential_kind: str = "bearer",
+ subject: str | None = "ticket-user-name",
+ created_at: str = "2026-01-01T00:00:00.000Z",
+ expires_at: str = "2026-01-01T00:00:30.000Z",
+ consumed_at: str | None = None,
+) -> None:
+ connection.execute(
+ """
+ INSERT INTO websocket_tickets(
+ ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope, created_at, expires_at, consumed_at
+ ) VALUES(?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?)
+ """,
+ (
+ digest_character * 64,
+ campaign_id,
+ "ticket-user",
+ credential_kind,
+ subject,
+ "synthetic-jti",
+ "2026-01-01T00:05:00.000Z",
+ created_at,
+ expires_at,
+ consumed_at,
+ ),
+ )
+
+
+def _insert_api_key_ticket(
+ connection: sqlite3.Connection,
+ *,
+ digest_character: str = "b",
+ required_scope: str = "read",
+) -> None:
+ connection.execute(
+ """
+ INSERT INTO websocket_tickets(
+ ticket_hash, campaign_id, user_id, credential_kind,
+ bearer_subject, bearer_jti, bearer_expires_at,
+ api_key_id, required_scope, created_at, expires_at, consumed_at
+ ) VALUES(?, ?, ?, 'api_key', NULL, NULL, NULL, ?, ?, ?, ?, NULL)
+ """,
+ (
+ digest_character * 64,
+ "ticket-campaign",
+ "ticket-user",
+ "ticket-api-key",
+ required_scope,
+ "2026-01-01T00:00:00.000Z",
+ "2026-01-01T00:00:30.000Z",
+ ),
+ )
+
+
+def _sqlite_rejects(
+ connection: sqlite3.Connection,
+ operation: Callable[[], None],
+) -> bool:
+ rejected = False
+ try:
+ operation()
+ except sqlite3.IntegrityError:
+ rejected = True
+ connection.rollback()
+ reusable_row = connection.execute("SELECT 1").fetchone()
+ reusable = reusable_row is not None and int(reusable_row[0]) == 1
+ return rejected and reusable
+
+
+def _exercise_ticket_enforcement(path: Path) -> bool:
+ connection = _connect(path)
+ try:
+ _seed_parent_rows(connection)
+ _insert_bearer_ticket(connection)
+ _insert_api_key_ticket(connection)
+ connection.commit()
+ valid_count = int(
+ connection.execute(
+ "SELECT COUNT(*) FROM websocket_tickets"
+ ).fetchone()[0]
+ )
+ cases = (
+ lambda: _insert_bearer_ticket(
+ connection,
+ digest_character="x",
+ ),
+ lambda: _insert_bearer_ticket(
+ connection,
+ digest_character="c",
+ credential_kind="unknown",
+ ),
+ lambda: _insert_bearer_ticket(
+ connection,
+ digest_character="d",
+ subject="",
+ ),
+ lambda: _insert_bearer_ticket(
+ connection,
+ digest_character="e",
+ campaign_id="missing-campaign",
+ ),
+ lambda: _insert_bearer_ticket(
+ connection,
+ digest_character="f",
+ created_at="2026-01-01 00:00:00",
+ ),
+ lambda: _insert_bearer_ticket(
+ connection,
+ digest_character="1",
+ expires_at="2025-12-31T23:59:59.000Z",
+ ),
+ lambda: _insert_bearer_ticket(
+ connection,
+ digest_character="2",
+ consumed_at="2026-01-01T00:00:30.000Z",
+ ),
+ lambda: _insert_api_key_ticket(
+ connection,
+ digest_character="3",
+ required_scope="write",
+ ),
+ )
+ rejected = tuple(_sqlite_rejects(connection, case) for case in cases)
+ unchanged_count = int(
+ connection.execute(
+ "SELECT COUNT(*) FROM websocket_tickets"
+ ).fetchone()[0]
+ )
+ connection.execute(
+ "DELETE FROM api_keys WHERE id=?",
+ ("ticket-api-key",),
+ )
+ connection.commit()
+ api_key_ticket_removed = (
+ int(
+ connection.execute(
+ "SELECT COUNT(*) FROM websocket_tickets "
+ "WHERE credential_kind='api_key'"
+ ).fetchone()[0]
+ )
+ == 0
+ )
+ return (
+ valid_count == 2
+ and all(rejected)
+ and unchanged_count == 2
+ and api_key_ticket_removed
+ )
+ finally:
+ connection.close()
+
+
+def _replace_named_check(
+ table_sql: str,
+ name: str,
+ replacement: str | None,
+) -> str:
+ match = re.search(
+ rf"\bCONSTRAINT\s+{re.escape(name)}\s+CHECK\s*\(",
+ table_sql,
+ flags=re.IGNORECASE,
+ )
+ if match is None:
+ raise RuntimeError("Ticket mutation target was absent")
+ _expression, close_index = _parenthesized_sql(
+ table_sql,
+ match.end() - 1,
+ )
+ if replacement is None:
+ return table_sql[:match.start()] + table_sql[close_index + 1:]
+ return (
+ table_sql[:match.start()]
+ + f"CONSTRAINT {name} CHECK ({replacement})"
+ + table_sql[close_index + 1:]
+ )
+
+
+def _replace_required(
+ value: str,
+ pattern: str,
+ replacement: str,
+) -> str:
+ updated, count = re.subn(
+ pattern,
+ replacement,
+ value,
+ count=1,
+ flags=re.IGNORECASE | re.DOTALL,
+ )
+ if count != 1:
+ raise RuntimeError("Ticket mutation target was absent")
+ return updated
+
+
+def _remove_required_scope_column(table_sql: str) -> str:
+ updated = _replace_required(
+ table_sql,
+ r"\brequired_scope\s+TEXT\s*,",
+ "",
+ )
+ match = re.search(
+ r"\bCONSTRAINT\s+ck_ws_ticket_source_shape\s+CHECK\s*\(",
+ updated,
+ flags=re.IGNORECASE,
+ )
+ if match is None:
+ raise RuntimeError("Ticket mutation target was absent")
+ expression, _close_index = _parenthesized_sql(
+ updated,
+ match.end() - 1,
+ )
+ expression = re.sub(
+ r"\s+AND\s+required_scope\s+IS\s+NULL",
+ "",
+ expression,
+ flags=re.IGNORECASE,
+ )
+ expression = re.sub(
+ r"\s+AND\s+required_scope\s*=\s*'read'",
+ "",
+ expression,
+ flags=re.IGNORECASE,
+ )
+ return _replace_named_check(
+ updated,
+ "ck_ws_ticket_source_shape",
+ expression,
+ )
+
+
+def _rebuild_ticket_table(
+ path: Path,
+ transform: Callable[[str], str],
+) -> None:
+ connection = _connect(path)
+ try:
+ connection.execute("PRAGMA foreign_keys=OFF")
+ table_row = connection.execute(
+ "SELECT sql FROM sqlite_master "
+ "WHERE type='table' AND name=?",
+ (_TICKET_TABLE,),
+ ).fetchone()
+ if table_row is None:
+ raise RuntimeError("Ticket mutation table was absent")
+ table_sql = str(table_row[0])
+ index_sql = tuple(
+ str(row[0])
+ for row in connection.execute(
+ "SELECT sql FROM sqlite_master "
+ "WHERE type='index' AND tbl_name=? AND sql IS NOT NULL "
+ "ORDER BY name",
+ (_TICKET_TABLE,),
+ )
+ )
+ mutated_sql = transform(table_sql)
+ if mutated_sql == table_sql:
+ raise RuntimeError("Ticket mutation did not change the catalog")
+ connection.execute("BEGIN IMMEDIATE")
+ connection.execute(
+ "ALTER TABLE websocket_tickets "
+ "RENAME TO websocket_tickets_original"
+ )
+ connection.execute(mutated_sql)
+ connection.execute("DROP TABLE websocket_tickets_original")
+ for statement in index_sql:
+ connection.execute(statement)
+ connection.commit()
+ connection.execute("PRAGMA foreign_keys=ON")
+ except BaseException:
+ connection.rollback()
+ raise
+ finally:
+ connection.close()
+
+
+def _mutate_ticket_schema(path: Path, variant: str) -> None:
+ if variant == "hash-glob-class":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_named_check(
+ sql,
+ "ck_ws_ticket_hash",
+ "length(ticket_hash)=64 "
+ "AND ticket_hash NOT GLOB '*[^0-9a-e]*'",
+ ),
+ )
+ return
+ if variant == "check-body":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_named_check(
+ sql,
+ "ck_ws_ticket_kind",
+ "credential_kind IN ('bearer', 'api_key', 'unknown')",
+ ),
+ )
+ return
+ if variant == "missing-check":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_named_check(
+ sql,
+ "ck_ws_ticket_kind",
+ None,
+ ),
+ )
+ return
+ if variant == "extra-check":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: sql.rstrip()[:-1]
+ + ", CONSTRAINT ck_ws_ticket_extra CHECK (1=1))",
+ )
+ return
+ if variant == "missing-column":
+ _rebuild_ticket_table(path, _remove_required_scope_column)
+ return
+ if variant == "extra-column":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(consumed_at\s+TEXT\s*,)",
+ r"\1 unexpected_state TEXT,",
+ ),
+ )
+ return
+ if variant == "hidden-column":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(consumed_at\s+TEXT\s*,)",
+ (
+ r"\1 unexpected_generated TEXT "
+ "GENERATED ALWAYS AS (credential_kind) VIRTUAL,"
+ ),
+ ),
+ )
+ return
+ if variant == "quoted-table":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"^CREATE\s+TABLE\s+websocket_tickets",
+ 'CREATE TABLE "websocket_tickets"',
+ ),
+ )
+ return
+ if variant == "quoted-check-identifier":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_named_check(
+ sql,
+ "ck_ws_ticket_kind",
+ '"credential_kind" IN (\'bearer\', \'api_key\')',
+ ),
+ )
+ return
+ if variant == "wrong-pk":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(ticket_hash\s+TEXT\s+NOT\s+NULL)\s+PRIMARY\s+KEY",
+ r"\1",
+ ),
+ )
+ return
+ if variant == "wrong-fk-target":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(CONSTRAINT\s+fk_ws_ticket_campaign\s+"
+ r"REFERENCES\s+)campaigns(\s*\(\s*id\s*\))",
+ r"\1users\2",
+ ),
+ )
+ return
+ if variant == "wrong-fk-action":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(CONSTRAINT\s+fk_ws_ticket_campaign\s+"
+ r"REFERENCES\s+campaigns\s*\(\s*id\s*\)\s+"
+ r"ON\s+DELETE\s+)CASCADE",
+ r"\1RESTRICT",
+ ),
+ )
+ return
+ if variant == "wrong-fk-update":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(CONSTRAINT\s+fk_ws_ticket_campaign\s+"
+ r"REFERENCES\s+campaigns\s*\(\s*id\s*\)\s+)"
+ r"ON\s+DELETE\s+CASCADE",
+ r"\1ON UPDATE CASCADE ON DELETE CASCADE",
+ ),
+ )
+ return
+ if variant == "wrong-type":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(bearer_expires_at\s+)TEXT",
+ r"\1BLOB",
+ ),
+ )
+ return
+ if variant == "wrong-default":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(created_at\s+TEXT\s+NOT\s+NULL)",
+ r"\1 DEFAULT '2026-01-01T00:00:00.000Z'",
+ ),
+ )
+ return
+ if variant == "wrong-nullability":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(created_at\s+TEXT)\s+NOT\s+NULL",
+ r"\1",
+ ),
+ )
+ return
+ if variant == "collation":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(bearer_subject\s+TEXT)",
+ r"\1 COLLATE NOCASE",
+ ),
+ )
+ return
+ if variant == "conflict-policy":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(ticket_hash\s+TEXT\s+NOT\s+NULL\s+PRIMARY\s+KEY)",
+ r"\1 ON CONFLICT REPLACE",
+ ),
+ )
+ return
+ if variant == "deferred-fk":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(CONSTRAINT\s+fk_ws_ticket_campaign\s+"
+ r"REFERENCES\s+campaigns\s*\(\s*id\s*\)\s+"
+ r"ON\s+DELETE\s+CASCADE)",
+ r"\1 DEFERRABLE INITIALLY DEFERRED",
+ ),
+ )
+ return
+ if variant == "immediate-fk":
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(CONSTRAINT\s+fk_ws_ticket_campaign\s+"
+ r"REFERENCES\s+campaigns\s*\(\s*id\s*\)\s+"
+ r"ON\s+DELETE\s+CASCADE)",
+ r"\1 DEFERRABLE INITIALLY IMMEDIATE",
+ ),
+ )
+ return
+
+ connection = _connect(path)
+ try:
+ if variant == "missing-index":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ elif variant == "wrong-index-column":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_expires "
+ "ON websocket_tickets(user_id)"
+ )
+ elif variant == "wrong-index-order":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_expires "
+ "ON websocket_tickets(user_id, expires_at)"
+ )
+ elif variant == "wrong-index-uniqueness":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ connection.execute(
+ "CREATE UNIQUE INDEX idx_ws_tickets_expires "
+ "ON websocket_tickets(expires_at)"
+ )
+ elif variant == "duplicate-index":
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_expires_duplicate "
+ "ON websocket_tickets(expires_at)"
+ )
+ elif variant == "extra-index":
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_extra "
+ "ON websocket_tickets(credential_kind)"
+ )
+ elif variant == "partial-index":
+ connection.execute("DROP INDEX idx_ws_tickets_expires")
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_expires "
+ "ON websocket_tickets(expires_at) "
+ "WHERE consumed_at IS NULL"
+ )
+ elif variant == "expression-index":
+ connection.execute("DROP INDEX idx_ws_tickets_user")
+ connection.execute(
+ "CREATE INDEX idx_ws_tickets_user "
+ "ON websocket_tickets(lower(user_id))"
+ )
+ elif variant == "consumption-reset-trigger":
+ connection.execute(
+ """
+ CREATE TRIGGER ws_ticket_restore_consumed
+ AFTER UPDATE OF consumed_at ON websocket_tickets
+ WHEN NEW.consumed_at IS NOT NULL
+ BEGIN
+ UPDATE websocket_tickets
+ SET consumed_at=NULL
+ WHERE ticket_hash=NEW.ticket_hash;
+ END
+ """
+ )
+ elif variant == "unexpected-insert-trigger":
+ connection.execute(
+ """
+ CREATE TRIGGER ws_ticket_unexpected_insert
+ AFTER INSERT ON websocket_tickets
+ BEGIN
+ SELECT 1;
+ END
+ """
+ )
+ else:
+ raise RuntimeError("Unknown ticket schema mutation")
+ connection.commit()
+ finally:
+ connection.close()
+
+
+async def _runtime_bootstrap(path: Path) -> bool:
+ uri = f"file:{path.resolve().as_posix()}?mode=rwc"
+ database = AresDatabase(uri)
+ await database.connect()
+ try:
+ repeated = await database.connect()
+ return repeated is database
+ finally:
+ await database.close()
+
+
+def test_migration_head_is_real_empty_base_to_0007() -> None:
+ with _temporary_database("empty-head") as path:
+ initially_empty = _application_tables(path) == ()
+ initial_revision_absent = _version(path) is None
+ _upgrade(path, "0007")
+ revision_is_current = _version(path) == "0007"
+ exact_contract = _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ enforcement_holds = _exercise_ticket_enforcement(path)
+
+ _require_fixed(
+ initially_empty and initial_revision_absent,
+ "fresh migration database was not empty",
+ )
+ _require_fixed(SCHEMA_VERSION == 7, "SQLite schema version is not seven")
+ _require_fixed(revision_is_current, "Alembic head is not revision 0007")
+ _require_fixed(
+ exact_contract,
+ "fresh revision 0007 ticket fingerprint diverged",
+ )
+ _require_fixed(
+ enforcement_holds,
+ "fresh revision 0007 enforcement diverged",
+ )
+
+
+def test_sqlite_0006_to_0007_to_0006_to_0007_preserves_parent_data() -> None:
+ with _temporary_database("round-trip") as path:
+ _upgrade(path, "0006")
+ parent_before = _non_ticket_snapshot(path)
+ connection = _connect(path)
+ try:
+ _seed_parent_rows(connection)
+ parent_count_before = _parent_row_count(connection)
+ finally:
+ connection.close()
+
+ _upgrade(path, "0007")
+ upgraded_exact = _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ connection = _connect(path)
+ try:
+ _insert_bearer_ticket(connection)
+ connection.commit()
+ finally:
+ connection.close()
+
+ _downgrade(path, "0006")
+ parent_after = _non_ticket_snapshot(path)
+ connection = _connect(path)
+ try:
+ parent_count_after = _parent_row_count(connection)
+ ticket_objects_absent = (
+ connection.execute(
+ "SELECT COUNT(*) FROM sqlite_master "
+ "WHERE name=? OR name IN (?, ?, ?, ?)",
+ (_TICKET_TABLE, *_TICKET_INDEX_NAMES),
+ ).fetchone()[0]
+ == 0
+ )
+ finally:
+ connection.close()
+ downgraded_exact = (
+ _version(path) == "0006"
+ and parent_after == parent_before
+ and parent_count_after == parent_count_before
+ and ticket_objects_absent
+ )
+
+ _upgrade(path, "0007")
+ reupgraded_exact = (
+ _version(path) == "0007"
+ and _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ )
+ connection = _connect(path)
+ try:
+ final_parent_count = _parent_row_count(connection)
+ finally:
+ connection.close()
+
+ _require_fixed(upgraded_exact, "revision 0007 upgrade was incomplete")
+ _require_fixed(
+ downgraded_exact,
+ "revision 0007 downgrade changed parent-owned state",
+ )
+ _require_fixed(
+ reupgraded_exact and final_parent_count == parent_count_before,
+ "revision 0007 re-upgrade did not converge",
+ )
+
+
+def test_runtime_bootstrap_and_alembic_have_exact_ticket_parity() -> None:
+ with _temporary_database("migration") as migration_path:
+ with _temporary_database("runtime") as runtime_path:
+ _upgrade(migration_path, "0007")
+ repeated_is_stable = asyncio.run(
+ _runtime_bootstrap(runtime_path)
+ )
+ migration_contract = _ticket_contract(migration_path)
+ runtime_contract = _ticket_contract(runtime_path)
+ both_exact = (
+ migration_contract == _EXPECTED_TICKET_CONTRACT
+ and runtime_contract == _EXPECTED_TICKET_CONTRACT
+ and migration_contract == runtime_contract
+ )
+
+ _require_fixed(
+ both_exact,
+ "runtime and migration ticket fingerprints diverged",
+ )
+ _require_fixed(
+ repeated_is_stable,
+ "repeated runtime initialization was not stable",
+ )
+
+
+async def test_runtime_rejects_consumption_reset_trigger_and_recovers() -> None:
+ with _temporary_database("consumption-reset-trigger") as path:
+ await _runtime_bootstrap(path)
+ connection = _connect(path)
+ try:
+ _seed_parent_rows(connection)
+ _insert_bearer_ticket(
+ connection,
+ digest_character="c",
+ expires_at="2099-01-01T00:00:30.000Z",
+ )
+ connection.commit()
+ finally:
+ connection.close()
+ _mutate_ticket_schema(path, "consumption-reset-trigger")
+
+ connection = _connect(path)
+ try:
+ first_cursor = connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET consumed_at=strftime(
+ '%Y-%m-%dT%H:%M:%fZ', 'now'
+ )
+ WHERE ticket_hash=?
+ AND consumed_at IS NULL
+ AND julianday(expires_at) > julianday('now')
+ """,
+ ("c" * 64,),
+ )
+ first_changed = first_cursor.rowcount
+ second_cursor = connection.execute(
+ """
+ UPDATE websocket_tickets
+ SET consumed_at=strftime(
+ '%Y-%m-%dT%H:%M:%fZ', 'now'
+ )
+ WHERE ticket_hash=?
+ AND consumed_at IS NULL
+ AND julianday(expires_at) > julianday('now')
+ """,
+ ("c" * 64,),
+ )
+ second_changed = second_cursor.rowcount
+ consumed_row = connection.execute(
+ "SELECT consumed_at IS NULL FROM websocket_tickets "
+ "WHERE ticket_hash=?",
+ ("c" * 64,),
+ ).fetchone()
+ connection.commit()
+ finally:
+ connection.close()
+ trigger_permits_replay = (
+ first_changed == 1
+ and second_changed == 1
+ and consumed_row is not None
+ and bool(consumed_row[0])
+ )
+ independent_oracle_rejects = (
+ _ticket_contract(path) != _EXPECTED_TICKET_CONTRACT
+ )
+ catalog_before = _complete_schema_snapshot(path)
+ data_before = _ticket_data_snapshot(path)
+
+ database = AresDatabase(
+ f"file:{path.resolve().as_posix()}?mode=rwc"
+ )
+ failure_type: type[BaseException] | None = None
+ failure_message_fixed = False
+ try:
+ await database.connect()
+ except Exception as exc:
+ failure_type = type(exc)
+ failure_message_fixed = (
+ str(exc) == "Incompatible WebSocket ticket schema"
+ )
+ finally:
+ await database.close()
+
+ catalog_after = _complete_schema_snapshot(path)
+ data_after = _ticket_data_snapshot(path)
+ connection = _connect(path)
+ try:
+ trigger_count = int(
+ connection.execute(
+ "SELECT COUNT(*) FROM sqlite_schema "
+ "WHERE type='trigger' AND tbl_name=?",
+ (_TICKET_TABLE,),
+ ).fetchone()[0]
+ )
+ connection.execute(
+ "DROP TRIGGER ws_ticket_restore_consumed"
+ )
+ connection.commit()
+ finally:
+ connection.close()
+ contract_recovers = (
+ _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ )
+
+ recovered = AresDatabase(
+ f"file:{path.resolve().as_posix()}?mode=rwc"
+ )
+ await recovered.connect()
+ try:
+ issued = await recovered.issue_websocket_ticket(
+ "ticket-campaign",
+ ApiKeyTicketSource(
+ user_id="ticket-user",
+ api_key_id="ticket-api-key",
+ ),
+ )
+ if issued is None:
+ pytest.fail(
+ "ticket issue failed after trigger removal",
+ pytrace=False,
+ )
+ raw_ticket, _ttl = issued
+ first_handle = await recovered.consume_websocket_ticket(
+ raw_ticket,
+ "ticket-campaign",
+ )
+ second_handle = await recovered.consume_websocket_ticket(
+ raw_ticket,
+ "ticket-campaign",
+ )
+ ordinary_single_use = (
+ first_handle is not None and second_handle is None
+ )
+ finally:
+ await recovered.close()
+
+ _require_fixed(
+ trigger_permits_replay and independent_oracle_rejects,
+ "consumption reset trigger was not security-authentic",
+ )
+ _require_fixed(
+ failure_type is RuntimeError and failure_message_fixed,
+ "consumption reset trigger was not rejected safely",
+ )
+ _require_fixed(
+ catalog_before == catalog_after
+ and data_before == data_after
+ and trigger_count == 1,
+ "trigger rejection changed ticket catalog or data",
+ )
+ _require_fixed(
+ contract_recovers and ordinary_single_use,
+ "trigger removal did not restore one-time consumption",
+ )
+
+
+ "variant",
+ [
+ "hash-glob-class",
+ "check-body",
+ "missing-check",
+ "extra-check",
+ "missing-column",
+ "extra-column",
+ "hidden-column",
+ "quoted-table",
+ "quoted-check-identifier",
+ "wrong-pk",
+ "wrong-fk-target",
+ "wrong-fk-action",
+ "wrong-fk-update",
+ "wrong-type",
+ "wrong-default",
+ "wrong-nullability",
+ "collation",
+ "conflict-policy",
+ "deferred-fk",
+ "immediate-fk",
+ "missing-index",
+ "wrong-index-column",
+ "wrong-index-order",
+ "wrong-index-uniqueness",
+ "duplicate-index",
+ "extra-index",
+ "partial-index",
+ "expression-index",
+ "consumption-reset-trigger",
+ "unexpected-insert-trigger",
+ ],
+)
+async def test_near_compatible_runtime_schema_is_rejected_without_mutation(
+ variant: str,
+) -> None:
+ with _temporary_database(f"mutation-{variant}") as path:
+ await _runtime_bootstrap(path)
+ _mutate_ticket_schema(path, variant)
+ before = _schema_snapshot(path)
+ database = AresDatabase(
+ f"file:{path.resolve().as_posix()}?mode=rwc"
+ )
+ failure_type: type[BaseException] | None = None
+ failure_message_fixed = False
+ try:
+ await database.connect()
+ except Exception as exc:
+ failure_type = type(exc)
+ failure_message_fixed = (
+ str(exc) == "Incompatible WebSocket ticket schema"
+ )
+ finally:
+ await database.close()
+ after = _schema_snapshot(path)
+
+ _require_fixed(
+ failure_type is RuntimeError and failure_message_fixed,
+ "incompatible ticket schema was not rejected safely",
+ )
+ _require_fixed(
+ before == after,
+ "failed ticket schema validation mutated the catalog",
+ )
+
+
+async def test_partial_runtime_schema_is_rejected_without_mutation() -> None:
+ with _temporary_database("partial") as path:
+ connection = _connect(path)
+ try:
+ connection.execute(
+ "CREATE TABLE websocket_tickets("
+ "ticket_hash TEXT PRIMARY KEY)"
+ )
+ connection.commit()
+ finally:
+ connection.close()
+ before = _schema_snapshot(path)
+ database = AresDatabase(
+ f"file:{path.resolve().as_posix()}?mode=rwc"
+ )
+ failure_type: type[BaseException] | None = None
+ failure_message_fixed = False
+ try:
+ await database.connect()
+ except Exception as exc:
+ failure_type = type(exc)
+ failure_message_fixed = (
+ str(exc) == "Incompatible WebSocket ticket schema"
+ )
+ finally:
+ await database.close()
+ after = _schema_snapshot(path)
+
+ _require_fixed(
+ failure_type is RuntimeError and failure_message_fixed,
+ "partial ticket schema was not rejected safely",
+ )
+ _require_fixed(
+ before == after,
+ "partial ticket rejection mutated the catalog",
+ )
+
+
+async def test_explicit_no_action_fk_remains_semantically_equivalent() -> None:
+ with _temporary_database("explicit-no-action") as path:
+ await _runtime_bootstrap(path)
+ _rebuild_ticket_table(
+ path,
+ lambda sql: _replace_required(
+ sql,
+ r"(CONSTRAINT\s+fk_ws_ticket_campaign\s+"
+ r"REFERENCES\s+campaigns\s*\(\s*id\s*\)\s+)"
+ r"ON\s+DELETE\s+CASCADE",
+ r"\1ON UPDATE NO ACTION ON DELETE CASCADE",
+ ),
+ )
+ before_is_exact = (
+ _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ )
+ database = AresDatabase(
+ f"file:{path.resolve().as_posix()}?mode=rwc"
+ )
+ await database.connect()
+ try:
+ after_is_exact = (
+ _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ )
+ finally:
+ await database.close()
+
+ _require_fixed(
+ before_is_exact and after_is_exact,
+ "explicit NO ACTION changed the logical ticket contract",
+ )
+
+
+def test_revision_0007_rejects_an_unsupported_dialect() -> None:
+ migration = importlib.import_module(
+ "migrations.versions.0007_add_websocket_tickets"
+ )
+ failure_type: type[BaseException] | None = None
+ failure_message_fixed = False
+ try:
+ migration._timestamp_type("unsupported")
+ except Exception as exc:
+ failure_type = type(exc)
+ failure_message_fixed = (
+ str(exc) == "Unsupported WebSocket ticket migration dialect"
+ )
+ _require_fixed(
+ failure_type is RuntimeError and failure_message_fixed,
+ "revision 0007 accepted an unsupported dialect",
+ )