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 refresh token families

Mafifrizi756578a5f75e
diff --git a/QUICKSTART.md b/QUICKSTART.md
index 8a9939a..1b04e96 100644
--- a/QUICKSTART.md
+++ b/QUICKSTART.md
@@ -445,3 +445,9 @@ SQLite or PostgreSQL database requires adoption, stop all workers and follow
[`docs/database-migrations.md`](docs/database-migrations.md). Do not run a blind
`alembic stamp`: only audited unversioned generations 6 and 7 are supported, and
SQLite adoption requires a retained verified backup.
+
+The current managed head is revision `0009`. Upgrading to it installs
+authoritative refresh-token families and deliberately invalidates existing
+browser bearer sessions. Stop every worker, take the required backup, upgrade,
+deploy the matching backend and frontend together, and have operators sign in
+again. Revision `0009` is forward-only; do not run mixed `0008`/`0009` workers.
diff --git a/README.md b/README.md
index 73ac5ff..7f652cf 100644
--- a/README.md
+++ b/README.md
@@ -271,8 +271,10 @@ See [docs/modules.md](docs/modules.md).
### Security Controls
-- JWT access tokens with refresh-token rotation.
-- Token revocation on logout.
+- Database-authoritative JWT access with one refresh-token family per login,
+ one-time rotation, strict replay-family revocation, and no JWT role authority.
+- Current-device and all-device logout plus immediate epoch revocation after
+ password, role, or activation security events.
- API key lifecycle with revoked-key removal from dashboard lists.
- RBAC roles: team lead, operator, recon, reporter.
- Encrypted data handling for sensitive credential material.
@@ -625,7 +627,9 @@ Persistent databases are Alembic-managed. Existing
unversioned generation-6/7 databases require the explicit verified adoption
workflow; startup never stamps them automatically. See
[`docs/database-migrations.md`](docs/database-migrations.md) before upgrading a
-deployment.
+deployment. Revision `0009` deliberately resets existing bearer sessions into
+revoked rollout families; plan an atomic backend/frontend maintenance window
+and require users to sign in again.
---
diff --git a/ares/api/rbac.py b/ares/api/rbac.py
index 95c3346..8554606 100644
--- a/ares/api/rbac.py
+++ b/ares/api/rbac.py
@@ -29,6 +29,7 @@ from typing import Any
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from ares.core.logger import get_logger
+from ares.core.token_sessions import is_canonical_family_id
from ares.db.websocket_tickets import BearerTicketSource
logger = get_logger("ares.api.rbac")
@@ -127,6 +128,8 @@ async def resolve_bearer_principal(
return PrincipalDecision(PrincipalDecisionStatus.INVALID)
subject = payload.get("sub")
+ family_id = payload.get("sid")
+ auth_epoch = payload.get("ver")
jti = payload.get("jti")
expires_at = payload.get("exp")
if (
@@ -134,6 +137,11 @@ async def resolve_bearer_principal(
or not subject.strip()
or not isinstance(jti, str)
or not jti.strip()
+ or not isinstance(family_id, str)
+ or not is_canonical_family_id(family_id)
+ or isinstance(auth_epoch, bool)
+ or not isinstance(auth_epoch, int)
+ or auth_epoch < 1
or isinstance(expires_at, bool)
or not isinstance(expires_at, (int, float))
):
@@ -151,7 +159,12 @@ async def resolve_bearer_principal(
return PrincipalDecision(PrincipalDecisionStatus.BACKEND_UNAVAILABLE)
try:
- row = await db.resolve_access_token_principal(subject, jti)
+ row = await db.resolve_access_token_principal(
+ subject,
+ jti,
+ family_id,
+ auth_epoch,
+ )
except Exception as exc:
logger.warning(
"auth_backend_principal_lookup_failed",
@@ -186,6 +199,8 @@ async def resolve_bearer_principal(
subject=subject,
jti=jti,
expires_at=source_expiry,
+ family_id=family_id,
+ auth_epoch=auth_epoch,
),
),
)
diff --git a/ares/api/server.py b/ares/api/server.py
index 10f29b9..e89c16f 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -62,6 +62,11 @@ from ares.core.config import AresSettings, get_settings
from ares.core.engine import AresEngine
from ares.core.logger import get_logger
from ares.core.security import create_access_token
+from ares.core.token_sessions import (
+ RefreshRotationStatus,
+ SessionIssueStatus,
+ SessionRevocationStatus,
+)
from ares.modules.base import normalize_module_metadata
from ares.core.tracing import get_current_trace_id, instrument_fastapi, setup_tracing
from ares.db.database import AresDatabase
@@ -702,7 +707,6 @@ async def generic_exception_handler(request: Request, exc: Exception) -> JSONRes
"unhandled_exception",
path=request.url.path,
method=request.method,
- exc=str(exc)[:200],
exc_type=type(exc).__name__,
)
return JSONResponse(
@@ -724,6 +728,8 @@ class TokenResponse(BaseModel):
token_type: str = "bearer" # noqa: S105 - OAuth token type, not a secret
expires_in: int = 3600
role: str = ""
+ refresh_generation: int
+ session_coordination_key: str
class RefreshRequest(BaseModel):
@@ -755,27 +761,32 @@ async def login(
if len(form.password) > 128:
raise HTTPException(status_code=400, detail="Password too long")
- user = await db.verify_user(form.username, form.password)
- if not user:
- await db.audit(
- "system",
- "login_failed",
- f"username={form.username}",
+ def _token_factory(claims: Mapping[str, Any]) -> str:
+ return create_access_token(
+ data=dict(claims),
+ secret_key=settings.secret_key_value,
+ algorithm=settings.ares_jwt_algorithm,
+ expires_minutes=settings.ares_jwt_expire_minutes,
)
- raise HTTPException(401, "Invalid credentials")
- access_token = create_access_token(
- data={"sub": user["username"], "role": user["role"]},
- secret_key=settings.secret_key_value,
- algorithm=settings.ares_jwt_algorithm,
- expires_minutes=settings.ares_jwt_expire_minutes,
- )
- refresh_token = await db.create_refresh_token(user["id"])
- await db.audit(user["username"], "login_success")
+ try:
+ result = await db.create_login_session(
+ form.username,
+ form.password,
+ _token_factory,
+ )
+ except Exception as exc:
+ logger.warning("login_transaction_failed", error_type=type(exc).__name__)
+ raise HTTPException(503, "Authentication service unavailable") from None
+ if result.status is not SessionIssueStatus.ISSUED or result.session is None:
+ raise HTTPException(401, "Invalid credentials")
+ session = result.session
return TokenResponse(
- access_token=access_token,
- refresh_token=refresh_token,
- role=user["role"],
+ access_token=session.access_token,
+ refresh_token=session.refresh_token,
+ role=session.role,
+ refresh_generation=session.refresh_generation,
+ session_coordination_key=session.coordination_key,
expires_in=settings.ares_jwt_expire_minutes * 60,
)
@@ -796,20 +807,28 @@ async def refresh_access_token(
"Too many refresh attempts. Try again in 60s.",
headers={"Retry-After": "60"},
)
- user, new_refresh = await db.rotate_refresh_token(body.refresh_token)
- if not user:
- raise HTTPException(401, "Refresh token invalid or expired")
+ def _token_factory(claims: Mapping[str, Any]) -> str:
+ return create_access_token(
+ data=dict(claims),
+ secret_key=settings.secret_key_value,
+ algorithm=settings.ares_jwt_algorithm,
+ expires_minutes=settings.ares_jwt_expire_minutes,
+ )
- access_token = create_access_token(
- data={"sub": user["username"], "role": user["role"]},
- secret_key=settings.secret_key_value,
- algorithm=settings.ares_jwt_algorithm,
- expires_minutes=settings.ares_jwt_expire_minutes,
- )
+ try:
+ result = await db.rotate_refresh_session(body.refresh_token, _token_factory)
+ except Exception as exc:
+ logger.warning("refresh_transaction_failed", error_type=type(exc).__name__)
+ raise HTTPException(503, "Authentication service unavailable") from None
+ if result.status is not RefreshRotationStatus.ROTATED or result.session is None:
+ raise HTTPException(401, "Refresh token invalid or expired")
+ session = result.session
return TokenResponse(
- access_token=access_token,
- refresh_token=new_refresh,
- role=user["role"],
+ access_token=session.access_token,
+ refresh_token=session.refresh_token,
+ role=session.role,
+ refresh_generation=session.refresh_generation,
+ session_coordination_key=session.coordination_key,
expires_in=settings.ares_jwt_expire_minutes * 60,
)
@@ -821,35 +840,46 @@ async def logout(
settings: AresSettings = Depends(get_settings),
db: AresDatabase = Depends(get_db),
) -> dict[str, str]:
- """Revoke all refresh tokens + blacklist the current access token jti."""
- user = await db.get_user(actor.username)
- if user:
- await db.revoke_all_refresh_tokens(user["id"])
- # Also revoke the current access token by jti so it cannot be reused
- # within its remaining 60-minute window
- token = request.headers.get("Authorization", "").removeprefix("Bearer ").strip()
- if token:
-
- from ares.core.security import decode_access_token
-
- payload = decode_access_token(
- token,
- settings.secret_key_value,
- settings.ares_jwt_algorithm,
- )
- if payload and payload.get("jti"):
- import datetime as _dt
-
- exp_ts = payload.get("exp", 0)
- exp_iso = (
- _dt.datetime.fromtimestamp(exp_ts, tz=_dt.timezone.utc).strftime(
- "%Y-%m-%d %H:%M:%S"
- )
- if exp_ts
- else ""
- )
- await db.revoke_access_token(payload["jti"], user["id"], exp_iso)
- await db.audit(actor.username, "logout")
+ """Revoke only the current bearer family; API keys are unaffected."""
+ del request, settings
+ source = actor.websocket_ticket_source
+ if actor.is_api_key or source is None:
+ return {"status": "ok"}
+ try:
+ result = await db.revoke_current_session(
+ user_id=source.user_id,
+ family_id=source.family_id,
+ jti=source.jti,
+ expires_at=source.expires_at,
+ )
+ except Exception as exc:
+ logger.warning("logout_current_failed", error_type=type(exc).__name__)
+ raise HTTPException(503, "Authentication service unavailable") from None
+ if result.status is SessionRevocationStatus.INVALID:
+ raise HTTPException(401, "Not authenticated")
+ return {"status": "ok"}
+
+
[email protected]("/auth/logout-all", tags=["auth"])
+async def logout_all(
+ actor: AuthenticatedUser = Depends(require_any_auth()), # noqa: B008
+ db: AresDatabase = Depends(get_db), # noqa: B008
+) -> dict[str, str]:
+ """Revoke every bearer family by incrementing the user's auth epoch."""
+ source = actor.websocket_ticket_source
+ if actor.is_api_key or source is None:
+ return {"status": "ok"}
+ try:
+ result = await db.revoke_all_sessions(
+ user_id=source.user_id,
+ jti=source.jti,
+ expires_at=source.expires_at,
+ )
+ except Exception as exc:
+ logger.warning("logout_all_failed", error_type=type(exc).__name__)
+ raise HTTPException(503, "Authentication service unavailable") from None
+ if result.status is SessionRevocationStatus.INVALID:
+ raise HTTPException(401, "Not authenticated")
return {"status": "ok"}
@@ -935,30 +965,16 @@ async def change_password(
raise HTTPException(401, "Current password incorrect")
from ares.core.security import hash_password
- await db.update_password(user["id"], hash_password(body.new_password))
- await db.revoke_all_refresh_tokens(user["id"])
+ del request, settings
+ changed = await db.apply_user_security_event(
+ user_id=user["id"],
+ reason="password_change",
+ new_password_hash=hash_password(body.new_password),
+ )
+ if not changed:
+ raise HTTPException(401, "Not authenticated")
# Revoke the current access token by jti — same as logout() —
# so the old token cannot be reused within its remaining expiry window.
- token = request.headers.get("Authorization", "").removeprefix("Bearer ").strip()
- if token:
- import datetime as _dt
-
- from ares.core.security import decode_access_token
-
- payload = decode_access_token(
- token, settings.secret_key_value, settings.ares_jwt_algorithm
- )
- if payload and payload.get("jti"):
- exp_ts = payload.get("exp", 0)
- exp_iso = (
- _dt.datetime.fromtimestamp(exp_ts, tz=_dt.timezone.utc).strftime(
- "%Y-%m-%d %H:%M:%S"
- )
- if exp_ts
- else ""
- )
- await db.revoke_access_token(payload["jti"], user["id"], exp_iso)
- await db.audit(actor.username, "password_changed")
return {"status": "ok", "note": "All existing sessions revoked"}
diff --git a/ares/core/security.py b/ares/core/security.py
index dfb7680..66a3801 100644
--- a/ares/core/security.py
+++ b/ares/core/security.py
@@ -123,7 +123,22 @@ def create_access_token(
algorithm: str = "HS256", # override with ARES_JWT_ALGORITHM=RS256
expires_minutes: int = 60,
) -> str:
+ family_id = data.get("sid")
+ auth_epoch = data.get("ver")
+ from ares.core.token_sessions import is_canonical_family_id
+
+ if (family_id is None) != (auth_epoch is None):
+ raise ValueError("invalid access token claims")
+ if family_id is not None and (
+ not is_canonical_family_id(family_id)
+ or isinstance(auth_epoch, bool)
+ or not isinstance(auth_epoch, int)
+ or auth_epoch < 1
+ ):
+ raise ValueError("invalid access token claims")
payload = data.copy()
+ if family_id is not None:
+ payload.pop("role", None)
payload["exp"] = datetime.now(timezone.utc) + timedelta(minutes=expires_minutes)
payload["iat"] = datetime.now(timezone.utc)
payload["jti"] = secrets.token_hex(16) # unique token ID for revocation
@@ -140,8 +155,11 @@ def decode_access_token(
key = _load_jwt_key(secret_key, algorithm, private=False)
# For HS256 algorithms=[algorithm] is required; for RS256 PyJWT handles it
return jwt.decode(token, key, algorithms=[algorithm])
- except InvalidTokenError as e:
- logger.warning("security_jwt_decode_failed", e=e)
+ except InvalidTokenError as exc:
+ logger.warning(
+ "security_jwt_decode_failed",
+ error_type=type(exc).__name__,
+ )
return None
diff --git a/ares/core/token_sessions.py b/ares/core/token_sessions.py
new file mode 100644
index 0000000..3218c24
--- /dev/null
+++ b/ares/core/token_sessions.py
@@ -0,0 +1,202 @@
+"""Immutable contracts for authoritative refresh-token families."""
+from __future__ import annotations
+
+import base64
+import hashlib
+import hmac
+import re
+import secrets
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from datetime import datetime
+from enum import Enum
+from typing import Any, Final, Protocol
+
+FAMILY_ABSOLUTE_LIFETIME_DAYS: Final[int] = 30
+FAMILY_RETENTION_DAYS: Final[int] = 30
+REFRESH_TOKEN_RANDOM_BYTES: Final[int] = 48
+
+_FAMILY_ID_RE: Final[re.Pattern[str]] = re.compile(r"[A-Za-z0-9_-]{43}\Z")
+_REFRESH_HASH_RE: Final[re.Pattern[str]] = re.compile(r"[0-9a-f]{64}\Z")
+_COORDINATION_DOMAIN: Final[bytes] = b"ARES-REFRESH-COORDINATION-V1\0"
+
+
+class RefreshFamilyState(str, Enum):
+ ACTIVE = "active"
+ REVOKED = "revoked"
+
+
+class RefreshTokenState(str, Enum):
+ ACTIVE = "active"
+ CONSUMED = "consumed"
+ RETIRED = "retired"
+
+
+class RefreshRevocationReason(str, Enum):
+ REPLAY = "replay"
+ LOGOUT_CURRENT = "logout_current"
+ LOGOUT_ALL = "logout_all"
+ PASSWORD_CHANGE = "password_change" # noqa: S105 - fixed event identifier
+ PASSWORD_RESET = "password_reset" # noqa: S105 - fixed event identifier
+ ROLE_CHANGE = "role_change"
+ USER_STATUS_CHANGE = "user_status_change"
+ ROLLOUT_RESET = "rollout_reset"
+ EXPIRED = "expired"
+ OPERATOR_REVOKE = "operator_revoke"
+
+
+class SessionIssueStatus(str, Enum):
+ ISSUED = "issued"
+ INVALID = "invalid"
+ BACKEND_UNAVAILABLE = "backend_unavailable"
+
+
+class RefreshRotationStatus(str, Enum):
+ ROTATED = "rotated"
+ INVALID = "invalid"
+ REPLAYED = "replayed"
+ BACKEND_UNAVAILABLE = "backend_unavailable"
+
+
+class SessionRevocationStatus(str, Enum):
+ REVOKED = "revoked"
+ ALREADY_REVOKED = "already_revoked"
+ INVALID = "invalid"
+ BACKEND_UNAVAILABLE = "backend_unavailable"
+
+
+class AccessTokenFactory(Protocol):
+ """Build one access token from already-authoritative claims."""
+
+ def __call__(self, claims: Mapping[str, Any]) -> str: ...
+
+
+def generate_family_id() -> str:
+ value = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode("ascii")
+ if not is_canonical_family_id(value):
+ raise RuntimeError("family identifier generation failed")
+ return value
+
+
+def is_canonical_family_id(value: object) -> bool:
+ if not isinstance(value, str) or _FAMILY_ID_RE.fullmatch(value) is None:
+ return False
+ try:
+ decoded = base64.urlsafe_b64decode(value + "=")
+ except (ValueError, TypeError):
+ return False
+ canonical = base64.urlsafe_b64encode(decoded).rstrip(b"=").decode("ascii")
+ return len(decoded) == 32 and hmac.compare_digest(canonical, value)
+
+
+def require_family_id(value: object) -> str:
+ if not is_canonical_family_id(value):
+ raise ValueError("invalid family identifier")
+ return value
+
+
+def generate_refresh_token() -> str:
+ return secrets.token_urlsafe(REFRESH_TOKEN_RANDOM_BYTES)
+
+
+def hash_refresh_token(raw_token: str) -> str:
+ if not isinstance(raw_token, str) or not raw_token:
+ raise ValueError("invalid refresh token")
+ return hashlib.sha256(raw_token.encode("utf-8")).hexdigest()
+
+
+def is_canonical_refresh_hash(value: object) -> bool:
+ return isinstance(value, str) and _REFRESH_HASH_RE.fullmatch(value) is not None
+
+
+def session_coordination_key(family_id: str) -> str:
+ canonical = require_family_id(family_id)
+ digest = hashlib.sha256(_COORDINATION_DOMAIN + canonical.encode("ascii")).digest()
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class BearerFamilyAuthority:
+ user_id: str = field(repr=False)
+ subject: str = field(repr=False)
+ family_id: str = field(repr=False)
+ auth_epoch: int = field(repr=False)
+ role: str
+ absolute_expires_at: datetime = field(repr=False)
+
+ def __post_init__(self) -> None:
+ object.__setattr__(self, "family_id", require_family_id(self.family_id))
+ if isinstance(self.auth_epoch, bool) or self.auth_epoch < 1:
+ raise ValueError("invalid authentication epoch")
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class IssuedTokenSession:
+ access_token: str = field(repr=False)
+ refresh_token: str = field(repr=False)
+ user_id: str = field(repr=False)
+ subject: str = field(repr=False)
+ family_id: str = field(repr=False)
+ auth_epoch: int = field(repr=False)
+ refresh_generation: int
+ role: str
+
+ def __post_init__(self) -> None:
+ object.__setattr__(self, "family_id", require_family_id(self.family_id))
+ if (
+ not self.access_token
+ or not self.refresh_token
+ or not self.user_id
+ or not self.subject
+ ):
+ raise ValueError("invalid issued session")
+ if isinstance(self.auth_epoch, bool) or self.auth_epoch < 1:
+ raise ValueError("invalid authentication epoch")
+ if isinstance(self.refresh_generation, bool) or self.refresh_generation < 0:
+ raise ValueError("invalid refresh generation")
+
+ @property
+ def coordination_key(self) -> str:
+ return session_coordination_key(self.family_id)
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class SessionIssueResult:
+ status: SessionIssueStatus
+ session: IssuedTokenSession | None = field(default=None, repr=False)
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class RefreshRotationResult:
+ status: RefreshRotationStatus
+ session: IssuedTokenSession | None = field(default=None, repr=False)
+
+
+@dataclass(frozen=True, slots=True, eq=False)
+class SessionRevocationResult:
+ status: SessionRevocationStatus
+
+
+__all__ = [
+ "AccessTokenFactory",
+ "BearerFamilyAuthority",
+ "FAMILY_ABSOLUTE_LIFETIME_DAYS",
+ "FAMILY_RETENTION_DAYS",
+ "IssuedTokenSession",
+ "RefreshFamilyState",
+ "RefreshRevocationReason",
+ "RefreshRotationResult",
+ "RefreshRotationStatus",
+ "RefreshTokenState",
+ "SessionIssueResult",
+ "SessionIssueStatus",
+ "SessionRevocationResult",
+ "SessionRevocationStatus",
+ "generate_family_id",
+ "generate_refresh_token",
+ "hash_refresh_token",
+ "is_canonical_family_id",
+ "is_canonical_refresh_hash",
+ "require_family_id",
+ "session_coordination_key",
+]
diff --git a/ares/db/database.py b/ares/db/database.py
index f7f3377..b095f7e 100644
--- a/ares/db/database.py
+++ b/ares/db/database.py
@@ -18,6 +18,21 @@ from urllib.parse import unquote
import aiosqlite
from ares.core.logger import get_logger
+from ares.core.token_sessions import (
+ FAMILY_ABSOLUTE_LIFETIME_DAYS,
+ FAMILY_RETENTION_DAYS,
+ AccessTokenFactory,
+ IssuedTokenSession,
+ RefreshRotationResult,
+ RefreshRotationStatus,
+ SessionIssueResult,
+ SessionIssueStatus,
+ SessionRevocationResult,
+ SessionRevocationStatus,
+ generate_family_id,
+ generate_refresh_token,
+ hash_refresh_token,
+)
from ares.db.websocket_tickets import (
ApiKeyTicketSource,
BearerTicketSource,
@@ -41,6 +56,7 @@ from ares.core.security import DataEncryptor, hash_password, verify_password
from ares.db.schema import CREATE_TABLES, SCHEMA_VERSION
_TicketResultT = TypeVar("_TicketResultT")
+_FamilyResultT = TypeVar("_FamilyResultT")
_WEBSOCKET_TICKET_COLUMNS = (
(0, "ticket_hash", "TEXT", 1, None, 1, 0),
@@ -55,11 +71,31 @@ _WEBSOCKET_TICKET_COLUMNS = (
(9, "created_at", "TEXT", 1, None, 0, 0),
(10, "expires_at", "TEXT", 1, None, 0, 0),
(11, "consumed_at", "TEXT", 0, None, 0, 0),
+ (12, "bearer_family_id", "TEXT", 0, None, 0, 0),
+ (13, "bearer_auth_epoch", "INTEGER", 0, None, 0, 0),
)
_WEBSOCKET_TICKET_FOREIGN_KEYS = (
(0, "api_key_id", "api_keys", "id", "NO ACTION", "CASCADE", "NONE"),
+ (
+ 0,
+ "bearer_family_id",
+ "refresh_token_families",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ "NONE",
+ ),
(0, "campaign_id", "campaigns", "id", "NO ACTION", "CASCADE", "NONE"),
(0, "user_id", "users", "id", "NO ACTION", "CASCADE", "NONE"),
+ (
+ 1,
+ "user_id",
+ "refresh_token_families",
+ "user_id",
+ "NO ACTION",
+ "CASCADE",
+ "NONE",
+ ),
)
_WEBSOCKET_TICKET_CHECKS = {
"ck_ws_ticket_hash": """
@@ -106,6 +142,12 @@ _WEBSOCKET_TICKET_CHECKS = {
AND strftime(
'%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
)=bearer_expires_at
+ AND bearer_family_id IS NOT NULL
+ AND length(bearer_family_id)=43
+ AND bearer_family_id NOT GLOB '*[^A-Za-z0-9_-]*'
+ AND bearer_auth_epoch IS NOT NULL
+ AND typeof(bearer_auth_epoch)='integer'
+ AND bearer_auth_epoch >= 1
AND api_key_id IS NULL
AND required_scope IS NULL
)
@@ -115,6 +157,8 @@ _WEBSOCKET_TICKET_CHECKS = {
AND bearer_subject IS NULL
AND bearer_jti IS NULL
AND bearer_expires_at IS NULL
+ AND bearer_family_id IS NULL
+ AND bearer_auth_epoch IS NULL
AND api_key_id IS NOT NULL
AND length(trim(api_key_id)) > 0
AND api_key_id=trim(api_key_id)
@@ -126,6 +170,7 @@ _WEBSOCKET_TICKET_FOREIGN_KEY_NAMES = {
"fk_ws_ticket_campaign",
"fk_ws_ticket_user",
"fk_ws_ticket_api_key",
+ "fk_ws_ticket_bearer_family",
}
_WEBSOCKET_TICKET_NAMED_FOREIGN_KEYS = {
"fk_ws_ticket_campaign": (
@@ -149,6 +194,13 @@ _WEBSOCKET_TICKET_NAMED_FOREIGN_KEYS = {
"NO ACTION",
"CASCADE",
),
+ "fk_ws_ticket_bearer_family": (
+ "bearer_family_id,user_id",
+ "refresh_token_families",
+ "id,user_id",
+ "NO ACTION",
+ "CASCADE",
+ ),
}
@@ -318,9 +370,9 @@ def _extract_named_foreign_keys(
if name not in _WEBSOCKET_TICKET_FOREIGN_KEY_NAMES:
continue
table_level = re.search(
- r"foreignkey\(([a-z_][a-z0-9_]*)\)"
+ r"foreignkey\(([a-z_][a-z0-9_]*(?:,[a-z_][a-z0-9_]*)*)\)"
r"references([a-z_][a-z0-9_]*)"
- r"\(([a-z_][a-z0-9_]*)\)",
+ r"\(([a-z_][a-z0-9_]*(?:,[a-z_][a-z0-9_]*)*)\)",
fragment,
)
if table_level is not None:
@@ -714,11 +766,11 @@ class AresDatabase:
if ownership.diagnostic.startswith("ARES-M2B-ADOPTION-READY:"):
raise RuntimeError("SQLite database adoption is required")
- if ownership.diagnostic == "ARES-M2B-ALREADY-MANAGED:0008":
+ if ownership.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":
return
if ownership.exit_code == AdoptionExit.MIGRATION_REQUIRED:
if ownership.predecessor not in {
- f"{revision:04d}" for revision in range(1, 8)
+ f"{revision:04d}" for revision in range(1, 9)
}:
raise RuntimeError(
"Invalid managed SQLite database metadata"
@@ -736,7 +788,7 @@ class AresDatabase:
raise RuntimeError(
"SQLite managed initialization failed"
) from None
- if managed.diagnostic != "ARES-M2B-ALREADY-MANAGED:0008":
+ if managed.diagnostic != "ARES-M2B-ALREADY-MANAGED:0009":
raise RuntimeError("SQLite managed initialization failed")
return
@@ -885,6 +937,14 @@ class AresDatabase:
"onwebsocket_tickets(user_id)",
}
),
+ "idx_ws_tickets_bearer_family": frozenset(
+ {
+ "createindexidx_ws_tickets_bearer_family"
+ "onwebsocket_tickets(bearer_family_id)",
+ "createindexifnotexistsidx_ws_tickets_bearer_family"
+ "onwebsocket_tickets(bearer_family_id)",
+ }
+ ),
}
if primary_index_name in expected_index_definitions:
raise RuntimeError("Incompatible WebSocket ticket schema")
@@ -1046,6 +1106,15 @@ class AresDatabase:
(1, -1, None, 0, "BINARY", 0),
),
),
+ "idx_ws_tickets_bearer_family": (
+ 0,
+ "c",
+ 0,
+ (
+ (0, 12, "bearer_family_id", 0, "BINARY", 1),
+ (1, -1, None, 0, "BINARY", 0),
+ ),
+ ),
}
if (
primary_index != expected_primary_index
@@ -1740,20 +1809,30 @@ class AresDatabase:
self,
subject: str,
jti: str,
+ family_id: str,
+ auth_epoch: int,
) -> dict[str, Any] | None:
- """Resolve current user eligibility and JTI status in one read snapshot."""
+ """Resolve bearer, family, epoch, and JTI authority read-only."""
connection = self._require_connected()
async with connection.execute(
- """SELECT u.id, u.username, u.role
+ """SELECT u.id, u.username, u.role, u.auth_epoch
FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.user_id=u.id
+ AND f.id=?
WHERE u.username=?
AND u.is_active=1
+ AND u.auth_epoch=?
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND julianday(f.absolute_expires_at) > julianday('now')
AND NOT EXISTS (
SELECT 1
FROM revoked_access_tokens AS rat
WHERE rat.jti=?
)""",
- (subject, jti),
+ (family_id, subject, auth_epoch, jti),
) as cur:
row = await cur.fetchone()
return dict(row) if row else None
@@ -2082,10 +2161,11 @@ class AresDatabase:
INSERT INTO websocket_tickets (
ticket_hash, campaign_id, user_id, credential_kind,
bearer_subject, bearer_jti, bearer_expires_at,
+ bearer_family_id, bearer_auth_epoch,
api_key_id, required_scope, created_at, expires_at,
consumed_at
)
- SELECT ?, c.id, u.id, 'bearer', u.username, ?, ?,
+ SELECT ?, c.id, u.id, 'bearer', u.username, ?, ?, ?, ?,
NULL, NULL,
strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),
strftime(
@@ -2095,10 +2175,17 @@ class AresDatabase:
),
NULL
FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.id=? AND f.user_id=u.id
JOIN campaigns AS c ON c.id=?
WHERE u.id=?
AND u.username=?
AND u.is_active=1
+ AND u.auth_epoch=?
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND julianday(f.absolute_expires_at) > julianday('now')
AND u.role IN (
'team_lead', 'operator', 'recon', 'reporter'
)
@@ -2117,9 +2204,13 @@ class AresDatabase:
ticket_hash,
source.jti,
source_expiry,
+ source.family_id,
+ source.auth_epoch,
+ source.family_id,
campaign_id,
source.user_id,
source.subject,
+ source.auth_epoch,
source_expiry,
source.jti,
),
@@ -2131,10 +2222,12 @@ class AresDatabase:
INSERT INTO websocket_tickets (
ticket_hash, campaign_id, user_id, credential_kind,
bearer_subject, bearer_jti, bearer_expires_at,
+ bearer_family_id, bearer_auth_epoch,
api_key_id, required_scope, created_at, expires_at,
consumed_at
)
SELECT ?, c.id, u.id, 'api_key', NULL, NULL, NULL,
+ NULL, NULL,
ak.id, 'read',
strftime('%Y-%m-%dT%H:%M:%fZ', 'now'),
strftime(
@@ -2215,6 +2308,35 @@ class AresDatabase:
'%Y-%m-%dT%H:%M:%fZ', expires_at
)=expires_at
AND julianday(expires_at) > julianday('now')
+ AND (
+ credential_kind='api_key'
+ OR EXISTS (
+ SELECT 1
+ FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.id=websocket_tickets.bearer_family_id
+ AND f.user_id=u.id
+ WHERE u.id=websocket_tickets.user_id
+ AND u.username=websocket_tickets.bearer_subject
+ AND u.is_active=1
+ AND u.auth_epoch=
+ websocket_tickets.bearer_auth_epoch
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND julianday(f.absolute_expires_at) >
+ julianday('now')
+ AND julianday(
+ websocket_tickets.bearer_expires_at
+ ) > julianday('now')
+ AND NOT EXISTS (
+ SELECT 1
+ FROM revoked_access_tokens AS rat
+ WHERE rat.jti=
+ websocket_tickets.bearer_jti
+ )
+ )
+ )
""",
(ticket_hash, campaign_id),
) as cursor:
@@ -2225,6 +2347,7 @@ class AresDatabase:
"""
SELECT campaign_id, user_id, credential_kind,
bearer_subject, bearer_jti, bearer_expires_at,
+ bearer_family_id, bearer_auth_epoch,
api_key_id, required_scope
FROM websocket_tickets
WHERE ticket_hash=?
@@ -2247,6 +2370,8 @@ class AresDatabase:
bearer_subject=row["bearer_subject"],
bearer_jti=row["bearer_jti"],
bearer_expires_at=bearer_expiry,
+ bearer_family_id=row["bearer_family_id"],
+ bearer_auth_epoch=row["bearer_auth_epoch"],
api_key_id=row["api_key_id"],
required_scope=row["required_scope"],
)
@@ -2264,6 +2389,8 @@ class AresDatabase:
handle.bearer_subject is None
or handle.bearer_jti is None
or handle.bearer_expires_at is None
+ or handle.bearer_family_id is None
+ or handle.bearer_auth_epoch is None
):
return None
source_expiry = format_sqlite_utc(
@@ -2273,10 +2400,17 @@ class AresDatabase:
"""
SELECT u.id, u.username, u.role
FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.id=? AND f.user_id=u.id
JOIN campaigns AS c ON c.id=?
WHERE u.id=?
AND u.username=?
AND u.is_active=1
+ AND u.auth_epoch=?
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND julianday(f.absolute_expires_at) > julianday('now')
AND u.role IN (
'team_lead', 'operator', 'recon', 'reporter'
)
@@ -2292,9 +2426,11 @@ class AresDatabase:
)
""",
(
+ handle.bearer_family_id,
handle.campaign_id,
handle.user_id,
handle.bearer_subject,
+ handle.bearer_auth_epoch,
source_expiry,
handle.bearer_jti,
),
@@ -2383,7 +2519,173 @@ class AresDatabase:
# ── Refresh Tokens (v5) ───────────────────────────────────────────────────
+ @staticmethod
+ def _family_timestamps() -> tuple[str, str, str]:
+ created = datetime.now(timezone.utc)
+ expires = created + timedelta(days=FAMILY_ABSOLUTE_LIFETIME_DAYS)
+ retain = expires + timedelta(days=FAMILY_RETENTION_DAYS)
+ return (
+ format_sqlite_utc(created),
+ format_sqlite_utc(expires),
+ format_sqlite_utc(retain),
+ )
+
+ async def _run_refresh_family_transaction(
+ self,
+ operation: Callable[[aiosqlite.Connection], Awaitable[_FamilyResultT]],
+ ) -> _FamilyResultT:
+ async with self._lifecycle_lock:
+ self._require_connected()
+ tx = await self._open_refresh_rotation_connection()
+ tx.row_factory = aiosqlite.Row
+ started = False
+ committed = False
+ cancellation_baseline = 0
+ caught_cancellations = [0]
+ try:
+ await tx.execute("PRAGMA foreign_keys = ON")
+ await tx.execute("BEGIN IMMEDIATE")
+ started = True
+ result = await operation(tx)
+ cancellation_baseline = _cancel_count()
+ commit_task = asyncio.create_task(
+ self._commit_refresh_rotation(tx),
+ name="ares-sqlite-family-commit",
+ )
+ await _await_task_completion(
+ commit_task,
+ cancellation_baseline=cancellation_baseline,
+ caught_cancellations=caught_cancellations,
+ )
+ committed = True
+ started = False
+ except BaseException:
+ if started and not committed:
+ rollback_baseline = _cancel_count()
+ rollback_cancellations = [0]
+ await self._finish_refresh_rotation_cleanup(
+ tx.rollback(),
+ "family-rollback",
+ cancellation_baseline=rollback_baseline,
+ caught_cancellations=rollback_cancellations,
+ )
+ raise
+ finally:
+ close_baseline = cancellation_baseline if committed else _cancel_count()
+ close_cancellations = caught_cancellations if committed else [0]
+ await self._finish_refresh_rotation_cleanup(
+ tx.close(),
+ "family-close",
+ cancellation_baseline=close_baseline,
+ caught_cancellations=close_cancellations,
+ )
+ if committed:
+ _remove_suppressed_cancellations(
+ cancellation_baseline=cancellation_baseline,
+ caught_cancellations=caught_cancellations[0],
+ )
+ return result
+
+ async def _insert_initial_family_token(
+ self,
+ tx: aiosqlite.Connection,
+ *,
+ user_id: str,
+ auth_epoch: int,
+ ) -> tuple[str, str]:
+ family_id = generate_family_id()
+ raw_token = generate_refresh_token()
+ token_hash = hash_refresh_token(raw_token)
+ created, expires, retain = self._family_timestamps()
+ await tx.execute(
+ "INSERT INTO refresh_token_families("
+ "id,user_id,auth_epoch,state,created_at,absolute_expires_at,retain_until) "
+ "VALUES(?,?,?,'active',?,?,?)",
+ (family_id, user_id, auth_epoch, created, expires, retain),
+ )
+ await tx.execute(
+ "INSERT INTO refresh_tokens("
+ "id,user_id,is_revoked,expires_at,created_at,family_id,parent_id,"
+ "generation,state,revoked_at) VALUES(?,?,0,?,?,?,NULL,0,'active',NULL)",
+ (token_hash, user_id, expires, created, family_id),
+ )
+ return family_id, raw_token
+
async def create_refresh_token(
+ self, user_id: str, expires_days: int = FAMILY_ABSOLUTE_LIFETIME_DAYS
+ ) -> str:
+ if expires_days != FAMILY_ABSOLUTE_LIFETIME_DAYS:
+ raise ValueError("refresh lifetime is fixed")
+
+ async def _create(tx: aiosqlite.Connection) -> str:
+ async with tx.execute(
+ "SELECT auth_epoch FROM users WHERE id=? AND is_active=1",
+ (user_id,),
+ ) as cursor:
+ row = await cursor.fetchone()
+ if row is None:
+ raise ValueError("invalid refresh owner")
+ _, raw_token = await self._insert_initial_family_token(
+ tx, user_id=user_id, auth_epoch=int(row["auth_epoch"])
+ )
+ return raw_token
+
+ return await self._run_refresh_family_transaction(_create)
+
+ async def create_login_session(
+ self,
+ username: str,
+ password: str,
+ token_factory: AccessTokenFactory,
+ ) -> SessionIssueResult:
+ async def _login(tx: aiosqlite.Connection) -> SessionIssueResult:
+ async with tx.execute(
+ "SELECT id,username,hashed_password,role,is_active,auth_epoch "
+ "FROM users WHERE username=?",
+ (username,),
+ ) as cursor:
+ row = await cursor.fetchone()
+ if row is None or int(row["is_active"]) != 1 or not verify_password(
+ password, row["hashed_password"]
+ ):
+ return SessionIssueResult(SessionIssueStatus.INVALID)
+ family_id, raw_token = await self._insert_initial_family_token(
+ tx,
+ user_id=row["id"],
+ auth_epoch=int(row["auth_epoch"]),
+ )
+ access_token = token_factory(
+ {
+ "sub": row["username"],
+ "sid": family_id,
+ "ver": int(row["auth_epoch"]),
+ }
+ )
+ await tx.execute(
+ "UPDATE users SET last_login=? WHERE id=?",
+ (format_sqlite_utc(datetime.now(timezone.utc)), row["id"]),
+ )
+ await tx.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','login_family_created','')"
+ )
+ return SessionIssueResult(
+ SessionIssueStatus.ISSUED,
+ IssuedTokenSession(
+ access_token=access_token,
+ refresh_token=raw_token,
+ user_id=row["id"],
+ subject=row["username"],
+ family_id=family_id,
+ auth_epoch=int(row["auth_epoch"]),
+ refresh_generation=0,
+ role=row["role"],
+ ),
+ )
+
+ return await self._run_refresh_family_transaction(_login)
+
+ async def _legacy_create_refresh_token(
self, user_id: str, expires_days: int = 30
) -> str:
import hashlib
@@ -2417,6 +2719,33 @@ class AresDatabase:
(token_hash, user_id, expires_at),
)
+ async def _insert_family_successor(
+ self,
+ tx: aiosqlite.Connection,
+ *,
+ token_hash: str,
+ user_id: str,
+ expires_at: str,
+ created_at: str,
+ family_id: str,
+ parent_id: str,
+ generation: int,
+ ) -> None:
+ await tx.execute(
+ "INSERT INTO refresh_tokens("
+ "id,user_id,is_revoked,expires_at,created_at,family_id,parent_id,"
+ "generation,state,revoked_at) VALUES(?,?,0,?,?,?,?,?,'active',NULL)",
+ (
+ token_hash,
+ user_id,
+ expires_at,
+ created_at,
+ family_id,
+ parent_id,
+ generation,
+ ),
+ )
+
async def _commit_refresh_rotation(
self,
tx: aiosqlite.Connection,
@@ -2451,8 +2780,129 @@ class AresDatabase:
error_type=type(cleanup_error).__name__,
)
+ async def rotate_refresh_session(
+ self,
+ old_token: str,
+ token_factory: AccessTokenFactory,
+ ) -> RefreshRotationResult:
+ old_hash = hash_refresh_token(old_token)
+
+ async def _rotate(tx: aiosqlite.Connection) -> RefreshRotationResult:
+ async with tx.execute(
+ "SELECT rt.id,rt.user_id,rt.family_id,rt.generation,rt.state,"
+ "rt.expires_at,f.state AS family_state,f.auth_epoch,"
+ "f.absolute_expires_at,u.username,u.role,u.is_active,"
+ "u.auth_epoch AS user_epoch FROM refresh_tokens AS rt "
+ "JOIN refresh_token_families AS f "
+ "ON f.id=rt.family_id AND f.user_id=rt.user_id "
+ "JOIN users AS u ON u.id=rt.user_id WHERE rt.id=?",
+ (old_hash,),
+ ) as cursor:
+ row = await cursor.fetchone()
+ if row is None:
+ return RefreshRotationResult(RefreshRotationStatus.INVALID)
+
+ now_dt = datetime.now(timezone.utc)
+ now = format_sqlite_utc(now_dt)
+ if row["state"] != "active":
+ if row["family_state"] == "active":
+ retain = format_sqlite_utc(
+ max(parse_sqlite_utc(row["absolute_expires_at"]), now_dt)
+ + timedelta(days=FAMILY_RETENTION_DAYS)
+ )
+ await tx.execute(
+ "UPDATE refresh_token_families SET state='revoked',"
+ "revoked_at=?,revoke_reason='replay',retain_until=? "
+ "WHERE id=? AND state='active'",
+ (now, retain, row["family_id"]),
+ )
+ await tx.execute(
+ "UPDATE refresh_tokens SET state='retired',is_revoked=1,"
+ "revoked_at=? WHERE family_id=? AND state='active'",
+ (now, row["family_id"]),
+ )
+ await tx.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','refresh_replay_family_revoked','')"
+ )
+ return RefreshRotationResult(RefreshRotationStatus.REPLAYED)
+
+ if (
+ row["family_state"] != "active"
+ or int(row["is_active"]) != 1
+ or int(row["auth_epoch"]) != int(row["user_epoch"])
+ or row["expires_at"] <= now
+ or row["absolute_expires_at"] <= now
+ ):
+ return RefreshRotationResult(RefreshRotationStatus.INVALID)
+
+ async with tx.execute(
+ "UPDATE refresh_tokens SET state='consumed',is_revoked=1,used_at=? "
+ "WHERE id=? AND state='active' AND is_revoked=0",
+ (now, old_hash),
+ ) as cursor:
+ if cursor.rowcount != 1:
+ return RefreshRotationResult(RefreshRotationStatus.REPLAYED)
+
+ raw_child = generate_refresh_token()
+ child_hash = hash_refresh_token(raw_child)
+ generation = int(row["generation"]) + 1
+ await self._insert_family_successor(
+ tx,
+ token_hash=child_hash,
+ user_id=row["user_id"],
+ expires_at=row["absolute_expires_at"],
+ created_at=now,
+ family_id=row["family_id"],
+ parent_id=old_hash,
+ generation=generation,
+ )
+ access_token = token_factory(
+ {
+ "sub": row["username"],
+ "sid": row["family_id"],
+ "ver": int(row["auth_epoch"]),
+ }
+ )
+ await tx.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','refresh_rotated','')"
+ )
+ return RefreshRotationResult(
+ RefreshRotationStatus.ROTATED,
+ IssuedTokenSession(
+ access_token=access_token,
+ refresh_token=raw_child,
+ user_id=row["user_id"],
+ subject=row["username"],
+ family_id=row["family_id"],
+ auth_epoch=int(row["auth_epoch"]),
+ refresh_generation=generation,
+ role=row["role"],
+ ),
+ )
+
+ return await self._run_refresh_family_transaction(_rotate)
+
async def rotate_refresh_token(
self, old_token: str
+ ) -> tuple[dict[str, Any] | None, str | None]:
+ result = await self.rotate_refresh_session(old_token, lambda _: "compat-access")
+ if result.status is not RefreshRotationStatus.ROTATED or result.session is None:
+ return None, None
+ return (
+ {
+ "id": result.session.user_id,
+ "username": result.session.subject,
+ "role": result.session.role,
+ "family_id": result.session.family_id,
+ "auth_epoch": result.session.auth_epoch,
+ },
+ result.session.refresh_token,
+ )
+
+ async def _legacy_rotate_refresh_token(
+ self, old_token: str
) -> tuple[dict[str, Any] | None, str | None]:
async with self._lifecycle_lock:
return await self._rotate_refresh_token_locked(old_token)
@@ -2633,7 +3083,161 @@ class AresDatabase:
) as cur:
return await cur.fetchone() is not None
+ @staticmethod
+ async def _revoke_family_rows(
+ tx: aiosqlite.Connection,
+ *,
+ user_id: str,
+ reason: str,
+ family_id: str | None = None,
+ ) -> int:
+ now_dt = datetime.now(timezone.utc)
+ now = format_sqlite_utc(now_dt)
+ if family_id is None:
+ cursor = await tx.execute(
+ "SELECT id,absolute_expires_at FROM refresh_token_families "
+ "WHERE user_id=? AND state='active'",
+ (user_id,),
+ )
+ else:
+ cursor = await tx.execute(
+ "SELECT id,absolute_expires_at FROM refresh_token_families "
+ "WHERE user_id=? AND state='active' AND id=?",
+ (user_id, family_id),
+ )
+ async with cursor:
+ rows = await cursor.fetchall()
+ for row in rows:
+ retain = format_sqlite_utc(
+ max(parse_sqlite_utc(row["absolute_expires_at"]), now_dt)
+ + timedelta(days=FAMILY_RETENTION_DAYS)
+ )
+ await tx.execute(
+ "UPDATE refresh_token_families SET state='revoked',revoked_at=?,"
+ "revoke_reason=?,retain_until=? WHERE id=? AND state='active'",
+ (now, reason, retain, row["id"]),
+ )
+ await tx.execute(
+ "UPDATE refresh_tokens SET state='retired',is_revoked=1,revoked_at=? "
+ "WHERE family_id=? AND state='active'",
+ (now, row["id"]),
+ )
+ return len(rows)
+
+ async def revoke_current_session(
+ self,
+ *,
+ user_id: str,
+ family_id: str,
+ jti: str,
+ expires_at: datetime,
+ ) -> SessionRevocationResult:
+ async def _revoke(tx: aiosqlite.Connection) -> SessionRevocationResult:
+ async with tx.execute(
+ "SELECT 1 FROM refresh_token_families WHERE id=? AND user_id=?",
+ (family_id, user_id),
+ ) as cursor:
+ known = await cursor.fetchone() is not None
+ if not known:
+ return SessionRevocationResult(SessionRevocationStatus.INVALID)
+ changed = await self._revoke_family_rows(
+ tx,
+ user_id=user_id,
+ family_id=family_id,
+ reason="logout_current",
+ )
+ await tx.execute(
+ "INSERT OR IGNORE INTO revoked_access_tokens(jti,user_id,expires_at) "
+ "VALUES(?,?,?)",
+ (jti, user_id, format_sqlite_utc(expires_at)),
+ )
+ if changed:
+ await tx.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','logout_current','')"
+ )
+ return SessionRevocationResult(SessionRevocationStatus.REVOKED)
+ return SessionRevocationResult(SessionRevocationStatus.ALREADY_REVOKED)
+
+ return await self._run_refresh_family_transaction(_revoke)
+
+ async def revoke_all_sessions(
+ self,
+ *,
+ user_id: str,
+ jti: str,
+ expires_at: datetime,
+ ) -> SessionRevocationResult:
+ async def _revoke(tx: aiosqlite.Connection) -> SessionRevocationResult:
+ async with tx.execute(
+ "UPDATE users SET auth_epoch=auth_epoch+1 "
+ "WHERE id=? AND is_active=1",
+ (user_id,),
+ ) as cursor:
+ if cursor.rowcount != 1:
+ return SessionRevocationResult(SessionRevocationStatus.INVALID)
+ await self._revoke_family_rows(
+ tx, user_id=user_id, reason="logout_all"
+ )
+ await tx.execute(
+ "INSERT OR IGNORE INTO revoked_access_tokens(jti,user_id,expires_at) "
+ "VALUES(?,?,?)",
+ (jti, user_id, format_sqlite_utc(expires_at)),
+ )
+ await tx.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','logout_all','')"
+ )
+ return SessionRevocationResult(SessionRevocationStatus.REVOKED)
+
+ return await self._run_refresh_family_transaction(_revoke)
+
+ async def apply_user_security_event(
+ self,
+ *,
+ user_id: str,
+ reason: str,
+ new_password_hash: str | None = None,
+ new_role: str | None = None,
+ is_active: bool | None = None,
+ ) -> bool:
+ if reason not in {"password_change", "password_reset", "role_change", "user_status_change"}:
+ raise ValueError("invalid security event")
+
+ async def _apply(tx: aiosqlite.Connection) -> bool:
+ async with tx.execute(
+ "UPDATE users SET auth_epoch=auth_epoch+1,"
+ "hashed_password=COALESCE(?,hashed_password),"
+ "role=COALESCE(?,role),is_active=COALESCE(?,is_active) "
+ "WHERE id=?",
+ (
+ new_password_hash,
+ new_role,
+ None if is_active is None else int(is_active),
+ user_id,
+ ),
+ ) as cursor:
+ if cursor.rowcount != 1:
+ return False
+ await self._revoke_family_rows(tx, user_id=user_id, reason=reason)
+ await tx.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system',?,'')",
+ (reason,),
+ )
+ return True
+
+ return await self._run_refresh_family_transaction(_apply)
+
async def revoke_all_refresh_tokens(self, user_id: str) -> None:
+ async def _revoke(tx: aiosqlite.Connection) -> None:
+ await self._revoke_family_rows(
+ tx, user_id=user_id, reason="operator_revoke"
+ )
+
+ await self._run_refresh_family_transaction(_revoke)
+
+ async def _legacy_revoke_all_refresh_tokens(self, user_id: str) -> None:
await self._conn.execute(
"UPDATE refresh_tokens SET is_revoked=1 WHERE user_id=?", (user_id,)
)
@@ -2716,9 +3320,8 @@ class AresDatabase:
async def purge_expired_tokens(self) -> int:
async with self._conn.execute(
- "DELETE FROM refresh_tokens WHERE is_revoked=1 OR "
- "(julianday(expires_at) IS NOT NULL AND "
- "julianday(expires_at) < julianday('now', '-7 days'))"
+ "DELETE FROM refresh_token_families "
+ "WHERE julianday(retain_until) <= julianday('now')"
) as cur:
n = cur.rowcount
await self._conn.commit()
diff --git a/ares/db/migrations/adoption.py b/ares/db/migrations/adoption.py
index 473f8b7..c143571 100644
--- a/ares/db/migrations/adoption.py
+++ b/ares/db/migrations/adoption.py
@@ -66,7 +66,7 @@ SUPPORTED_GENERATIONS: Final[tuple[RuntimeGeneration, ...]] = (
)
_KNOWN_REVISIONS: Final[frozenset[str]] = frozenset(
- f"{value:04d}" for value in range(1, 9)
+ f"{value:04d}" for value in range(1, 10)
)
_REVISION_FILES: Final[tuple[str, ...]] = (
"0001_initial_schema.py",
@@ -77,6 +77,7 @@ _REVISION_FILES: Final[tuple[str, ...]] = (
"0006_rename_cracked_value_to_enc.py",
"0007_add_websocket_tickets.py",
"0008_reconcile_schema_parity.py",
+ "0009_refresh_token_families.py",
)
_LOCK_KEY: Final[int] = int.from_bytes(
hashlib.sha256(b"ARES-M2B-ADOPTION-LOCK-V1").digest()[:8],
@@ -86,10 +87,10 @@ _LOCK_KEY: Final[int] = int.from_bytes(
_FIXED_DIAGNOSTICS: Final[frozenset[str]] = frozenset(
{
"ARES-M2B-EMPTY-DATABASE",
- "ARES-M2B-ALREADY-MANAGED:0008",
+ "ARES-M2B-ALREADY-MANAGED:0009",
"ARES-M2B-MIGRATION-REQUIRED",
- "ARES-M2B-ADOPTED:SQLITE:0008",
- "ARES-M2B-ADOPTED:POSTGRESQL:0008",
+ "ARES-M2B-ADOPTED:SQLITE:0009",
+ "ARES-M2B-ADOPTED:POSTGRESQL:0009",
"ARES-M2B-RESTORED:SQLITE",
"ARES-M2B-E02:USAGE",
"ARES-M2B-E03:CONFIGURATION",
@@ -123,7 +124,7 @@ def _failure(exit_code: AdoptionExit, diagnostic: str) -> AdoptionFailure:
def _revision_module() -> Any:
- return import_module("migrations.versions.0008_reconcile_schema_parity")
+ return import_module("migrations.versions.0009_refresh_token_families")
@contextlib.contextmanager
@@ -155,14 +156,14 @@ def migration_config(connection: Connection | None = None) -> Iterator[Config]:
if connection is not None:
cfg.attributes["connection"] = connection
script = ScriptDirectory.from_config(cfg)
- if script.get_heads() != ["0008"]:
+ if script.get_heads() != ["0009"]:
raise _failure(
AdoptionExit.CONFIGURATION,
"ARES-M2B-E03:CONFIGURATION",
)
revisions = tuple(script.walk_revisions(base="base", head="heads"))
if tuple(item.revision for item in reversed(revisions)) != tuple(
- f"{value:04d}" for value in range(1, 9)
+ f"{value:04d}" for value in range(1, 10)
):
raise _failure(
AdoptionExit.CONFIGURATION,
@@ -256,7 +257,7 @@ def _is_empty(connection: Connection) -> bool:
def inspect_connection(connection: Connection) -> AdoptionResult:
"""Classify one catalog without mutation or external dynamic diagnostics."""
revision = _version_revision(connection)
- if revision == "0008":
+ if revision == "0009":
try:
_revision_module().verify_managed_catalog(connection)
except (RuntimeError, sa.exc.SQLAlchemyError):
@@ -266,7 +267,7 @@ def inspect_connection(connection: Connection) -> AdoptionResult:
) from None
return AdoptionResult(
AdoptionExit.OK,
- "ARES-M2B-ALREADY-MANAGED:0008",
+ "ARES-M2B-ALREADY-MANAGED:0009",
)
if revision is not None:
return AdoptionResult(
@@ -293,7 +294,7 @@ def inspect_connection(connection: Connection) -> AdoptionResult:
def verify_managed_connection(connection: Connection) -> AdoptionResult:
result = inspect_connection(connection)
- if result.diagnostic == "ARES-M2B-ALREADY-MANAGED:0008":
+ if result.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":
return result
if result.exit_code == AdoptionExit.MIGRATION_REQUIRED:
raise _failure(
@@ -336,7 +337,7 @@ def _run_canonical_adoption(
try:
with migration_config(connection) as cfg:
command.stamp(cfg, predecessor)
- command.upgrade(cfg, "0008")
+ command.upgrade(cfg, "0009")
finally:
if marked_sqlite:
connection.info.pop(adoption_marker, None)
@@ -622,7 +623,7 @@ def inspect_sqlite_database(path: str | Path) -> AdoptionResult:
def adopt_sqlite(path: Path, backup: Path) -> AdoptionResult:
initial = inspect_sqlite_database(path)
- if initial.diagnostic == "ARES-M2B-ALREADY-MANAGED:0008":
+ if initial.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":
return initial
_adoption_predecessor(initial)
backup_digest = _create_sqlite_backup(path, backup)
@@ -665,7 +666,7 @@ def adopt_sqlite(path: Path, backup: Path) -> AdoptionResult:
rollback_proven = False
raise
_durable(path)
- return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:SQLITE:0008")
+ return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:SQLITE:0009")
except (asyncio.CancelledError, KeyboardInterrupt, SystemExit, GeneratorExit):
raise
except AdoptionFailure:
@@ -773,7 +774,7 @@ async def _postgres_operation(url: URL, operation: str) -> AdoptionResult:
"ARES-M2B-E07:OWNERSHIP-BUSY",
)
classified = await connection.run_sync(_sync_inspect)
- if classified.diagnostic == "ARES-M2B-ALREADY-MANAGED:0008":
+ if classified.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009":
already_managed = True
else:
predecessor = _adoption_predecessor(classified)
@@ -791,9 +792,9 @@ async def _postgres_operation(url: URL, operation: str) -> AdoptionResult:
if already_managed:
return AdoptionResult(
AdoptionExit.OK,
- "ARES-M2B-ALREADY-MANAGED:0008",
+ "ARES-M2B-ALREADY-MANAGED:0009",
)
- return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:POSTGRESQL:0008")
+ return AdoptionResult(AdoptionExit.OK, "ARES-M2B-ADOPTED:POSTGRESQL:0009")
finally:
await engine.dispose()
diff --git a/ares/db/postgres.py b/ares/db/postgres.py
index d699d96..ddafb2c 100644
--- a/ares/db/postgres.py
+++ b/ares/db/postgres.py
@@ -38,6 +38,21 @@ from typing import Any
from ares.core.logger import get_logger
from ares.core.security import DataEncryptor, hash_password, verify_password
+from ares.core.token_sessions import (
+ FAMILY_ABSOLUTE_LIFETIME_DAYS,
+ FAMILY_RETENTION_DAYS,
+ AccessTokenFactory,
+ IssuedTokenSession,
+ RefreshRotationResult,
+ RefreshRotationStatus,
+ SessionIssueResult,
+ SessionIssueStatus,
+ SessionRevocationResult,
+ SessionRevocationStatus,
+ generate_family_id,
+ generate_refresh_token,
+ hash_refresh_token,
+)
from ares.db.websocket_tickets import (
ApiKeyTicketSource,
BearerTicketSource,
@@ -577,31 +592,31 @@ def _is_postgres_ticket_relation_diagnostic(invariant: str) -> bool:
_POSTGRES_TICKET_CENSUS_FIELDS = (
("r", (("m", 0x3FF, 3), ("a", 0x3FF, 3), ("x", 0x3FF, 3),
("n", 0x3FF, 3), ("g", 0x1, 1))),
- ("c", (("m", 0xFFF, 3), ("e", 0x1, 1), ("o", 0xFFF, 3),
- ("t", 0xFFF, 3), ("u", 0xFFF, 3), ("d", 0xFFF, 3),
- ("l", 0xFFF, 3), ("i", 0xFFF, 3), ("a", 0xFFF, 3),
- ("x", 0xFFF, 3), ("g", 0x1, 1))),
- ("q", (("m", 0x7FFF, 4), ("e", 0x1, 1), ("t", 0x7FFF, 4),
- ("v", 0x7FFF, 4), ("f", 0x7FFF, 4), ("d", 0x7FFF, 4),
- ("s", 0x7FFF, 4), ("b", 0x7FFF, 4), ("a", 0x7FFF, 4),
- ("x", 0x7FFF, 4), ("g", 0x1, 1))),
+ ("c", (("m", 0x3FFF, 4), ("e", 0x1, 1), ("o", 0x3FFF, 4),
+ ("t", 0x3FFF, 4), ("u", 0x3FFF, 4), ("d", 0x3FFF, 4),
+ ("l", 0x3FFF, 4), ("i", 0x3FFF, 4), ("a", 0x3FFF, 4),
+ ("x", 0x3FFF, 4), ("g", 0x1, 1))),
+ ("q", (("m", 0xFFFF, 4), ("e", 0x1, 1), ("t", 0xFFFF, 4),
+ ("v", 0xFFFF, 4), ("f", 0xFFFF, 4), ("d", 0xFFFF, 4),
+ ("s", 0xFFFF, 4), ("b", 0xFFFF, 4), ("a", 0xFFFF, 4),
+ ("x", 0xFFFF, 4), ("g", 0x1, 1))),
("p", (("l", 0x1, 1), ("r", 0x1, 1), ("n", 0x1, 1),
("i", 0x1, 1), ("a", 0x1, 1), ("x", 0x1, 1),
("g", 0x1, 1))),
("h", (("t", 0x7FF, 3), ("v", 0x7FF, 3), ("f", 0x7FF, 3),
("d", 0x7FF, 3), ("s", 0x7FF, 3), ("a", 0x7FF, 3),
("x", 0x7FF, 3), ("g", 0x1, 1))),
- ("f", (("l", 0x7, 1), ("s", 0x7, 1), ("t", 0x7, 1),
- ("r", 0x7, 1), ("u", 0x7, 1), ("d", 0x7, 1),
- ("i", 0x7, 1), ("a", 0x7, 1), ("x", 0x7, 1),
+ ("f", (("l", 0xF, 1), ("s", 0xF, 1), ("t", 0xF, 1),
+ ("r", 0xF, 1), ("u", 0xF, 1), ("d", 0xF, 1),
+ ("i", 0xF, 1), ("a", 0xF, 1), ("x", 0xF, 1),
("g", 0x1, 1))),
- ("i", (("m", 0x1F, 2), ("e", 0x1, 1), ("o", 0x1F, 2),
- ("b", 0x1F, 2), ("u", 0x1F, 2), ("p", 0x1F, 2),
- ("v", 0x1F, 2), ("r", 0x1F, 2), ("l", 0x1F, 2),
- ("k", 0x1F, 2), ("n", 0x1F, 2), ("c", 0x1F, 2),
- ("d", 0x1F, 2), ("a", 0x1F, 2), ("j", 0x1F, 2),
- ("s", 0x1F, 2), ("t", 0x1F, 2), ("y", 0x1F, 2),
- ("h", 0x1F, 2), ("x", 0x1F, 2), ("g", 0x1, 1))),
+ ("i", (("m", 0x3F, 2), ("e", 0x1, 1), ("o", 0x3F, 2),
+ ("b", 0x3F, 2), ("u", 0x3F, 2), ("p", 0x3F, 2),
+ ("v", 0x3F, 2), ("r", 0x3F, 2), ("l", 0x3F, 2),
+ ("k", 0x3F, 2), ("n", 0x3F, 2), ("c", 0x3F, 2),
+ ("d", 0x3F, 2), ("a", 0x3F, 2), ("j", 0x3F, 2),
+ ("s", 0x3F, 2), ("t", 0x3F, 2), ("y", 0x3F, 2),
+ ("h", 0x3F, 2), ("x", 0x3F, 2), ("g", 0x1, 1))),
("o", (("m", 0x3, 1), ("e", 0x1, 1), ("x", 0x3, 1),
("g", 0x1, 1))),
("z", (("q", 0x7F, 2), ("x", 0x7F, 2))),
@@ -826,13 +841,13 @@ def _is_postgres_q78_failure(value: str) -> bool:
_POSTGRES_Q78_SPLIT_INDEX_FIELDS = (
- ("m", 0x1F, 2), ("e", 0x1, 1), ("o", 0x1F, 2),
- ("b", 0x1F, 2), ("u", 0x1F, 2), ("p", 0x1F, 2),
- ("v", 0x1F, 2), ("r", 0x1F, 2), ("l", 0x1F, 2),
- ("k", 0x1F, 2), ("n", 0x1F, 2), ("c", 0x1F, 2),
- ("d", 0x1F, 2), ("a", 0x1F, 2), ("j", 0x1F, 2),
- ("s", 0x1F, 2), ("t", 0x1F, 2), ("y", 0x1F, 2),
- ("h", 0x1F, 2), ("x", 0x1F, 2), ("g", 0x1, 1),
+ ("m", 0x3F, 2), ("e", 0x1, 1), ("o", 0x3F, 2),
+ ("b", 0x3F, 2), ("u", 0x3F, 2), ("p", 0x3F, 2),
+ ("v", 0x3F, 2), ("r", 0x3F, 2), ("l", 0x3F, 2),
+ ("k", 0x3F, 2), ("n", 0x3F, 2), ("c", 0x3F, 2),
+ ("d", 0x3F, 2), ("a", 0x3F, 2), ("j", 0x3F, 2),
+ ("s", 0x3F, 2), ("t", 0x3F, 2), ("y", 0x3F, 2),
+ ("h", 0x3F, 2), ("x", 0x3F, 2), ("g", 0x1, 1),
)
@@ -874,7 +889,7 @@ def _postgres_q78_split_invariant(
)
if (
any(
- type(value) is not int or not 0 <= value <= 0x7
+ type(value) is not int or not 0 <= value <= 0xF
for value in scalar_values[:-1]
)
or type(query_failure) is not int
@@ -935,7 +950,7 @@ def _is_postgres_q78_split(value: str) -> bool:
if not encoded.startswith(marker, position):
return False
position += len(marker)
- allowed = "0123456789abcdef" if marker == "z=q" else "01234567"
+ allowed = "0123456789abcdef"
if position >= len(encoded) or encoded[position] not in allowed:
return False
scalars.append(int(encoded[position], 16))
@@ -979,6 +994,10 @@ def _postgres_q78_index_split_census(
"btree", False, False, True, True, True,
1, 1, ("api_key_id",), (0,), ("text_ops",), (True,), None, None,
),
+ "idx_ws_tickets_bearer_family": (
+ "btree", False, False, True, True, True,
+ 1, 1, ("bearer_family_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,
@@ -1001,7 +1020,7 @@ def _postgres_q78_index_split_census(
name: ordinal for ordinal, name in enumerate(expected_names)
}
if type(rows) not in {list, tuple}:
- section["x"] = 0x1F
+ section["x"] = 0x3F
return section, 1
actual_names: list[str] = []
actual: dict[str, tuple[object, ...]] = {}
@@ -1086,7 +1105,7 @@ def _postgres_q78_index_split_census(
if name == "websocket_tickets_pkey":
primary_index_oid = index_oid
except (KeyError, IndexError, TypeError, ValueError):
- section["x"] |= 0x1F
+ section["x"] |= 0x3F
continue
actual_name_set = set(actual_names)
for name in set(expected_names) - actual_name_set:
@@ -1283,7 +1302,7 @@ async def _postgres_q78_split_observation(
ORDER BY rel.relname
""",
schema_oid,
- ["api_keys", "campaigns", "users"],
+ ["api_keys", "campaigns", "refresh_token_families", "users"],
)
except asyncio.CancelledError:
raise
@@ -1323,8 +1342,13 @@ async def _postgres_q78_split_observation(
schema_shape = int(type(raw_schema) is not str)
schema_mismatch = int(type(raw_schema) is str and raw_schema != schema_name)
- expected_reference_names = ("api_keys", "campaigns", "users")
- reference_missing = 0x7
+ expected_reference_names = (
+ "api_keys",
+ "campaigns",
+ "refresh_token_families",
+ "users",
+ )
+ reference_missing = 0xF
reference_extra = 0
reference_order = 0
reference_binding = 0x7
@@ -1352,10 +1376,11 @@ async def _postgres_q78_split_observation(
expected_constraint_names = (
"fk_ws_ticket_api_key",
"fk_ws_ticket_campaign",
+ "fk_ws_ticket_bearer_family",
"fk_ws_ticket_user",
)
if type(constraint_rows) not in {list, tuple}:
- reference_binding = 0x7
+ reference_binding = 0xF
else:
constraints = {
str(row["conname"]): row for row in constraint_rows
@@ -1620,6 +1645,14 @@ class _PostgresStartupDiagnosticError(RuntimeError):
or _is_postgres_ticket_schema_census(
diagnostic_invariant
)
+ or (
+ diagnostic_invariant.startswith(
+ ("managed-check-", "managed-foreign-")
+ )
+ and len(diagnostic_invariant)
+ in {len("managed-check-00"), len("managed-foreign-00")}
+ and diagnostic_invariant[-2:].isdigit()
+ )
)
else "ownership-unclassified"
)
@@ -1743,9 +1776,9 @@ def _postgres_ticket_schema_error(
return error
-_POSTGRES_MANAGED_REVISION = "0008"
+_POSTGRES_MANAGED_REVISION = "0009"
_POSTGRES_OLDER_REVISIONS = frozenset(
- {"0001", "0002", "0003", "0004", "0005", "0006", "0007"}
+ {"0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008"}
)
_POSTGRES_MIGRATION_REQUIRED_ERROR = "PostgreSQL schema migration required"
_POSTGRES_MANAGED_SCHEMA_ERROR = "Incompatible managed PostgreSQL schema"
@@ -1772,6 +1805,7 @@ _POSTGRES_MANAGED_TABLES = frozenset(
"users",
"api_keys",
"refresh_tokens",
+ "refresh_token_families",
"revoked_access_tokens",
"rate_limit_events",
"websocket_tickets",
@@ -1803,6 +1837,26 @@ _POSTGRES_MANAGED_INDEXES = (
("api_keys", "idx_apikeys_prefix", ("key_prefix",)),
("refresh_tokens", "idx_refresh_user", ("user_id",)),
("refresh_tokens", "idx_refresh_exp", ("expires_at",)),
+ (
+ "refresh_token_families",
+ "idx_refresh_family_user_state_exp",
+ ("user_id", "state", "absolute_expires_at"),
+ ),
+ (
+ "refresh_token_families",
+ "idx_refresh_family_retain",
+ ("retain_until",),
+ ),
+ (
+ "refresh_tokens",
+ "idx_refresh_family_generation",
+ ("family_id", "generation"),
+ ),
+ (
+ "refresh_tokens",
+ "uq_refresh_token_one_active",
+ ("family_id",),
+ ),
("revoked_access_tokens", "idx_rat_expires", ("expires_at",)),
("rate_limit_events", "idx_rle_ip", ("ip_address",)),
("rate_limit_events", "idx_rle_timestamp", ("timestamp",)),
@@ -1820,6 +1874,11 @@ _POSTGRES_MANAGED_PRIMARY_KEYS = (
("users", "users_pkey", ("id",)),
("api_keys", "api_keys_pkey", ("id",)),
("refresh_tokens", "refresh_tokens_pkey", ("id",)),
+ (
+ "refresh_token_families",
+ "refresh_token_families_pkey",
+ ("id",),
+ ),
(
"revoked_access_tokens",
"revoked_access_tokens_pkey",
@@ -1919,11 +1978,54 @@ _POSTGRES_MANAGED_FOREIGN_KEYS = (
"CASCADE",
"c",
),
+ (
+ "refresh_token_families",
+ "fk_refresh_family_user",
+ ("user_id",),
+ "users",
+ ("id",),
+ "CASCADE",
+ "c",
+ ),
+ (
+ "refresh_tokens",
+ "fk_refresh_token_family_owner",
+ ("family_id", "user_id"),
+ "refresh_token_families",
+ ("id", "user_id"),
+ "CASCADE",
+ "c",
+ ),
+ (
+ "refresh_tokens",
+ "fk_refresh_token_parent",
+ ("family_id", "parent_id"),
+ "refresh_tokens",
+ ("family_id", "id"),
+ "CASCADE",
+ "c",
+ ),
)
_POSTGRES_MANAGED_UNIQUES = (
("hosts", "uq_hosts_campaign_ip", ("campaign_id", "ip_address")),
("users", "uq_users_username", ("username",)),
+ (
+ "refresh_token_families",
+ "uq_refresh_family_owner",
+ ("id", "user_id"),
+ ),
+ (
+ "refresh_tokens",
+ "uq_refresh_token_family_hash",
+ ("family_id", "id"),
+ ),
+ (
+ "refresh_tokens",
+ "uq_refresh_token_family_generation",
+ ("family_id", "generation"),
+ ),
+ ("refresh_tokens", "uq_refresh_token_parent", ("parent_id",)),
)
_POSTGRES_MANAGED_FINITE_CHECKS = (
@@ -1944,6 +2046,11 @@ _POSTGRES_MANAGED_FINITE_CHECKS = (
("refresh_tokens", "expires_at", False),
("refresh_tokens", "created_at", False),
("refresh_tokens", "used_at", True),
+ ("refresh_tokens", "revoked_at", True),
+ ("refresh_token_families", "created_at", False),
+ ("refresh_token_families", "absolute_expires_at", False),
+ ("refresh_token_families", "revoked_at", True),
+ ("refresh_token_families", "retain_until", False),
("rate_limit_events", "timestamp", False),
("revoked_access_tokens", "revoked_at", False),
("revoked_access_tokens", "expires_at", False),
@@ -1957,6 +2064,15 @@ def _postgres_finite_check_name(table: str, column: str) -> str:
return "ck_audit_log_timestamp_finite"
if table == "rate_limit_events":
return "ck_rate_limit_events_timestamp_finite"
+ if table == "refresh_tokens" and column == "revoked_at":
+ return "ck_refresh_token_revoked_finite"
+ if table == "refresh_token_families":
+ return {
+ "created_at": "ck_refresh_family_created_finite",
+ "absolute_expires_at": "ck_refresh_family_expires_finite",
+ "revoked_at": "ck_refresh_family_revoked_finite",
+ "retain_until": "ck_refresh_family_retain_finite",
+ }[column]
return f"ck_{table}_{column}_finite"
@@ -1976,10 +2092,14 @@ def _postgres_index_opclass(table: str, column: str) -> str:
if (table, column) in {
("module_runs", "completed_at"),
("refresh_tokens", "expires_at"),
+ ("refresh_token_families", "absolute_expires_at"),
+ ("refresh_token_families", "retain_until"),
("revoked_access_tokens", "expires_at"),
("rate_limit_events", "timestamp"),
}:
return "timestamptz_ops"
+ if (table, column) == ("refresh_tokens", "generation"):
+ return "int8_ops"
return "text_ops"
@@ -2803,10 +2923,15 @@ class PostgresDatabase:
raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)
for key, columns in expected_indexes.items():
actual = index_contract[key]
+ is_one_active = key == (
+ "refresh_tokens",
+ "uq_refresh_token_one_active",
+ )
+ expected_predicate = "(state = 'active'::text)" if is_one_active else None
if actual != (
columns,
- False,
- None,
+ is_one_active,
+ expected_predicate,
"i",
"p",
False,
@@ -3089,6 +3214,74 @@ class PostgresDatabase:
"ck_rate_limit_events_blocked_bool",
)
] = "CHECK (blocked = ANY (ARRAY[0, 1]))"
+ expected_checks.update(
+ {
+ ("users", "ck_users_auth_epoch"): (
+ "CHECK (auth_epoch >= 1)"
+ ),
+ ("refresh_token_families", "ck_refresh_family_id"): (
+ "CHECK (id ~ '^[A-Za-z0-9_-]{43}$'::text)"
+ ),
+ ("refresh_token_families", "ck_refresh_family_epoch"): (
+ "CHECK (auth_epoch >= 1)"
+ ),
+ ("refresh_token_families", "ck_refresh_family_state"): (
+ "CHECK (state = ANY (ARRAY['active'::text, 'revoked'::text]))"
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_revocation_shape",
+ ): (
+ "CHECK (state = 'active'::text AND revoked_at IS NULL "
+ "AND revoke_reason IS NULL OR state = 'revoked'::text "
+ "AND revoked_at IS NOT NULL AND revoke_reason IS NOT NULL)"
+ ),
+ ("refresh_token_families", "ck_refresh_family_reason"): (
+ "CHECK (revoke_reason IS NULL OR (revoke_reason = ANY "
+ "(ARRAY['expired'::text, 'logout_all'::text, "
+ "'logout_current'::text, 'operator_revoke'::text, "
+ "'password_change'::text, 'password_reset'::text, "
+ "'replay'::text, 'role_change'::text, "
+ "'rollout_reset'::text, 'user_status_change'::text])))"
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_expiry_order",
+ ): "CHECK (absolute_expires_at > created_at)",
+ (
+ "refresh_token_families",
+ "ck_refresh_family_retention_order",
+ ): (
+ "CHECK (retain_until > absolute_expires_at AND "
+ "(revoked_at IS NULL OR retain_until > revoked_at))"
+ ),
+ ("refresh_tokens", "ck_refresh_token_hash"): (
+ "CHECK (id ~ '^[0-9a-f]{64}$'::text)"
+ ),
+ ("refresh_tokens", "ck_refresh_token_generation"): (
+ "CHECK (generation >= 0)"
+ ),
+ ("refresh_tokens", "ck_refresh_token_parent_shape"): (
+ "CHECK (generation = 0 AND parent_id IS NULL "
+ "OR generation > 0 AND parent_id IS NOT NULL)"
+ ),
+ ("refresh_tokens", "ck_refresh_token_state"): (
+ "CHECK (state = ANY (ARRAY['active'::text, "
+ "'consumed'::text, 'retired'::text]))"
+ ),
+ ("refresh_tokens", "ck_refresh_token_state_shape"): (
+ "CHECK (state = 'active'::text AND is_revoked = 0 "
+ "AND used_at IS NULL AND revoked_at IS NULL "
+ "OR state = 'consumed'::text AND is_revoked = 1 "
+ "AND used_at IS NOT NULL AND revoked_at IS NULL "
+ "OR state = 'retired'::text AND is_revoked = 1 "
+ "AND revoked_at IS NOT NULL)"
+ ),
+ ("refresh_tokens", "ck_refresh_token_expiry_order"): (
+ "CHECK (expires_at > created_at)"
+ ),
+ }
+ )
expected_keys = (
set(expected_foreign)
| set(expected_unique)
@@ -3118,7 +3311,12 @@ class PostgresDatabase:
raise RuntimeError(
_POSTGRES_MANAGED_SCHEMA_ERROR
) from None
- if not source_schema or common != (True, False, False):
+ expected_common = (
+ (True, True, True)
+ if key == ("refresh_tokens", "fk_refresh_token_parent")
+ else (True, False, False)
+ )
+ if not source_schema or common != expected_common:
raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)
if key in expected_checks:
@@ -3129,7 +3327,12 @@ class PostgresDatabase:
or remote_columns
or int(contract["constraint_index_oid"]) != 0
):
- raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)
+ ordinal = sorted(expected_checks).index(key)
+ raise _PostgresManagedSchemaError(
+ _POSTGRES_MANAGED_SCHEMA_ERROR,
+ diagnostic_stage="managed-validation",
+ diagnostic_invariant=f"managed-check-{ordinal:02d}",
+ ) from None
continue
if key in expected_foreign:
@@ -3145,6 +3348,8 @@ class PostgresDatabase:
f"REFERENCES {parent}({', '.join(expected_remote)}) "
f"ON DELETE {on_delete}"
)
+ if key == ("refresh_tokens", "fk_refresh_token_parent"):
+ expected_definition += " DEFERRABLE INITIALLY DEFERRED"
if (
str(contract["contype"]) != "f"
or definition != expected_definition
@@ -3204,16 +3409,27 @@ class PostgresDatabase:
raise RuntimeError(
_POSTGRES_MANAGED_SCHEMA_ERROR
) from None
+ reference_index_name = {
+ (
+ "refresh_tokens",
+ "fk_refresh_token_family_owner",
+ ): "uq_refresh_family_owner",
+ (
+ "refresh_tokens",
+ "fk_refresh_token_parent",
+ ): "uq_refresh_token_family_hash",
+ }.get(key, f"{parent}_pkey")
+ reference_is_primary = reference_index_name.endswith("_pkey")
if foreign_index_contract != (
foreign_index_contract[0],
source_schema,
- f"{parent}_pkey",
+ reference_index_name,
"i",
"p",
False,
"btree",
True,
- True,
+ reference_is_primary,
True,
True,
True,
@@ -3227,7 +3443,12 @@ class PostgresDatabase:
None,
None,
) or foreign_index_contract[0] <= 0:
- raise RuntimeError(_POSTGRES_MANAGED_SCHEMA_ERROR)
+ ordinal = sorted(expected_foreign).index(key)
+ raise _PostgresManagedSchemaError(
+ _POSTGRES_MANAGED_SCHEMA_ERROR,
+ diagnostic_stage="managed-validation",
+ diagnostic_invariant=f"managed-foreign-{ordinal:02d}",
+ ) from None
continue
columns = expected_unique[key]
@@ -3306,7 +3527,10 @@ class PostgresDatabase:
len(columns),
columns,
(0,) * len(columns),
- ("text_ops",) * len(columns),
+ tuple(
+ _postgres_index_opclass(key[0], column)
+ for column in columns
+ ),
("pg_catalog",) * len(columns),
(True,) * len(columns),
None,
@@ -3501,69 +3725,11 @@ class PostgresDatabase:
cause=exc,
) from None
else:
- self._record_startup_trace("fallback-entered")
- try:
- 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'
- )
- """
- )
- )
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- raise _postgres_startup_error(
- _POSTGRES_SCHEMA_VALIDATION_ERROR,
- stage="fallback-validation",
- invariant="ticket-relation-present",
- cause=exc,
- ) from None
- if ticket_table_exists:
- try:
- await self._validate_websocket_ticket_schema(conn)
- except _PostgresStartupDiagnosticError as exc:
- raise _postgres_restage_startup_error(
- exc,
- "fallback-validation",
- ) from None
- try:
- await conn.execute(_PG_CREATE_TABLES)
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- raise _postgres_startup_error(
- _POSTGRES_SCHEMA_VALIDATION_ERROR,
- stage="fallback-ddl",
- invariant=_postgres_fallback_failure_invariant(
- exc
- ),
- cause=exc,
- ) from None
- self._record_startup_trace("fallback-ddl-complete")
- try:
- await self._validate_websocket_ticket_schema(conn)
- except _PostgresStartupDiagnosticError as exc:
- raise _postgres_restage_startup_error(
- exc,
- "fallback-validation",
- ) from None
- except asyncio.CancelledError:
- raise
- except Exception as exc:
- raise _postgres_startup_error(
- _POSTGRES_SCHEMA_VALIDATION_ERROR,
- stage="fallback-validation",
- invariant="ticket-validation-unclassified",
- cause=exc,
- ) from None
+ raise _PostgresMigrationRequiredError(
+ _POSTGRES_MIGRATION_REQUIRED_ERROR,
+ diagnostic_stage="ownership",
+ diagnostic_invariant="ownership-unversioned",
+ )
logger.info("pg_schema_ready")
@staticmethod
@@ -3729,6 +3895,8 @@ class PostgresDatabase:
True,
None,
),
+ ("bearer_family_id", "text", False, "", "", True, None),
+ ("bearer_auth_epoch", "bigint", False, "", "", True, None),
]
if actual_columns != expected_columns:
census["c"] = _postgres_ticket_column_census(
@@ -3801,6 +3969,7 @@ class PostgresDatabase:
"ck_ws_ticket_source_shape",
"ck_ws_ticket_time_order",
"fk_ws_ticket_api_key",
+ "fk_ws_ticket_bearer_family",
"fk_ws_ticket_campaign",
"fk_ws_ticket_user",
"websocket_tickets_pkey",
@@ -3830,7 +3999,7 @@ class PostgresDatabase:
raise
except Exception:
q78_split = _postgres_q78_split_invariant(
- {field: (0x1F if field == "x" else 0)
+ {field: (0x3F if field == "x" else 0)
for field, _maximum, _width in _POSTGRES_Q78_SPLIT_INDEX_FIELDS},
primary_binding=1,
opclass_missing=3,
@@ -4061,6 +4230,11 @@ class PostgresDatabase:
"btree", False, False, True, True, True,
1, 1, ("api_key_id",), (0,), ("text_ops",), (True,), None, None,
),
+ "idx_ws_tickets_bearer_family": (
+ "btree", False, False, True, True, True,
+ 1, 1, ("bearer_family_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,
@@ -4140,6 +4314,11 @@ class PostgresDatabase:
"f",
"FOREIGN KEY (api_key_id) REFERENCES api_keys(id) ON DELETE CASCADE",
),
+ "fk_ws_ticket_bearer_family": (
+ "f",
+ "FOREIGN KEY (bearer_family_id, user_id) "
+ "REFERENCES refresh_token_families(id, user_id) ON DELETE CASCADE",
+ ),
}
for name, definition in expected_constraint_fragments.items():
row = actual_constraints.get(name)
@@ -4209,6 +4388,14 @@ class PostgresDatabase:
"fk_ws_ticket_api_key": (
("api_key_id",), referenced_schema, "api_keys", ("id",), "a", "c",
),
+ "fk_ws_ticket_bearer_family": (
+ ("bearer_family_id", "user_id"),
+ referenced_schema,
+ "refresh_token_families",
+ ("id", "user_id"),
+ "a",
+ "c",
+ ),
}
try:
referenced_rows = await _postgres_q78_isolated_call(
@@ -4221,7 +4408,7 @@ class PostgresDatabase:
AND rel.relname=ANY($2::text[])
""",
schema_oid,
- ["api_keys", "campaigns", "users"],
+ ["api_keys", "campaigns", "refresh_token_families", "users"],
)
except asyncio.CancelledError:
raise
@@ -4239,8 +4426,13 @@ class PostgresDatabase:
str(row["relname"]): int(row["relation_oid"])
for row in referenced_rows
}
- if set(referenced_oids) != {"api_keys", "campaigns", "users"}:
- census["f"]["i"] = 0x7
+ if set(referenced_oids) != {
+ "api_keys",
+ "campaigns",
+ "refresh_token_families",
+ "users",
+ }:
+ census["f"]["i"] = 0xF
rejected = True
for name, row in actual_constraints.items():
@@ -4363,12 +4555,17 @@ class PostgresDatabase:
"AND length(btrim(bearer_jti)) > 0 "
"AND bearer_jti = btrim(bearer_jti) "
"AND bearer_expires_at IS NOT NULL "
+ "AND bearer_family_id IS NOT NULL "
+ "AND bearer_auth_epoch IS NOT NULL "
+ "AND bearer_auth_epoch >= 1 "
"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 bearer_family_id IS NULL "
+ "AND bearer_auth_epoch IS NULL "
"AND api_key_id IS NOT NULL "
"AND length(btrim(api_key_id)) > 0 "
"AND api_key_id = btrim(api_key_id) "
@@ -4411,7 +4608,8 @@ class PostgresDatabase:
census["h"]["d"] |= bit
census["q"]["d"] |= constraint_bit
rejected = True
- if " ".join(str(row["definition"]).split()) != expected_definition:
+ actual_definition = " ".join(str(row["definition"]).split())
+ if actual_definition != expected_definition:
census["h"]["s"] |= bit
census["q"]["s"] |= constraint_bit
rejected = True
@@ -4919,6 +5117,8 @@ class PostgresDatabase:
self,
subject: str,
jti: str,
+ family_id: str,
+ auth_epoch: int,
) -> dict[str, Any] | None:
"""Resolve current user eligibility and JTI status in one read snapshot."""
pool = self._pool
@@ -4929,10 +5129,17 @@ class PostgresDatabase:
raise RuntimeError("Database pool is closing")
async with pool.acquire() as conn:
row = await conn.fetchrow(
- """SELECT u.id, u.username, u.role
+ """SELECT u.id, u.username, u.role, u.auth_epoch
FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.user_id=u.id AND f.id=$3
WHERE u.username=$1
AND u.is_active=1
+ AND u.auth_epoch=$4
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND f.absolute_expires_at > now()
AND NOT EXISTS (
SELECT 1
FROM revoked_access_tokens AS rat
@@ -4940,6 +5147,8 @@ class PostgresDatabase:
)""",
subject,
jti,
+ family_id,
+ auth_epoch,
)
return self._row_to_dict(row) if row else None
@@ -5088,15 +5297,23 @@ class PostgresDatabase:
INSERT INTO websocket_tickets(
ticket_hash, campaign_id, user_id,
credential_kind, bearer_subject, bearer_jti,
- bearer_expires_at, created_at, expires_at
+ bearer_expires_at, bearer_family_id,
+ bearer_auth_epoch, created_at, expires_at
)
- SELECT $1, c.id, u.id, 'bearer', $4, $5, $6,
+ SELECT $1, c.id, u.id, 'bearer', $4, $5, $6, $7, $8,
now(), now() + interval '30 seconds'
FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.id=$7 AND f.user_id=u.id
JOIN campaigns AS c ON c.id=$2
WHERE u.id=$3
AND u.username=$4
AND u.is_active=1
+ AND u.auth_epoch=$8
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND f.absolute_expires_at > now()
AND u.role IN ('team_lead','operator','recon','reporter')
AND $6 > now()
AND NOT EXISTS (
@@ -5115,6 +5332,8 @@ class PostgresDatabase:
source.subject,
source.jti,
source.expires_at,
+ source.family_id,
+ source.auth_epoch,
)
else:
row = await connection.fetchrow(
@@ -5180,9 +5399,35 @@ class PostgresDatabase:
AND campaign_id=$2
AND consumed_at IS NULL
AND expires_at > now()
+ AND (
+ credential_kind='api_key'
+ OR EXISTS (
+ SELECT 1
+ FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.id=websocket_tickets.bearer_family_id
+ AND f.user_id=u.id
+ WHERE u.id=websocket_tickets.user_id
+ AND u.username=websocket_tickets.bearer_subject
+ AND u.is_active=1
+ AND u.auth_epoch=
+ websocket_tickets.bearer_auth_epoch
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND f.absolute_expires_at > now()
+ AND websocket_tickets.bearer_expires_at > now()
+ AND NOT EXISTS (
+ SELECT 1
+ FROM revoked_access_tokens AS rat
+ WHERE rat.jti=websocket_tickets.bearer_jti
+ )
+ )
+ )
RETURNING campaign_id, user_id, credential_kind,
bearer_subject, bearer_jti,
- bearer_expires_at, api_key_id,
+ bearer_expires_at, bearer_family_id,
+ bearer_auth_epoch, api_key_id,
required_scope
""",
ticket_hash,
@@ -5198,6 +5443,8 @@ class PostgresDatabase:
bearer_subject=row["bearer_subject"],
bearer_jti=row["bearer_jti"],
bearer_expires_at=row["bearer_expires_at"],
+ bearer_family_id=row["bearer_family_id"],
+ bearer_auth_epoch=row["bearer_auth_epoch"],
api_key_id=row["api_key_id"],
required_scope=row["required_scope"],
)
@@ -5215,10 +5462,17 @@ class PostgresDatabase:
"""
SELECT u.id, u.username, u.role
FROM users AS u
+ JOIN refresh_token_families AS f
+ ON f.id=$6 AND f.user_id=u.id
JOIN campaigns AS c ON c.id=$1
WHERE u.id=$2
AND u.username=$3
AND u.is_active=1
+ AND u.auth_epoch=$7
+ AND f.auth_epoch=u.auth_epoch
+ AND f.state='active'
+ AND f.revoked_at IS NULL
+ AND f.absolute_expires_at > now()
AND u.role IN ('team_lead','operator','recon','reporter')
AND $4 > now()
AND NOT EXISTS (
@@ -5235,6 +5489,8 @@ class PostgresDatabase:
consumed.bearer_subject,
consumed.bearer_expires_at,
consumed.bearer_jti,
+ consumed.bearer_family_id,
+ consumed.bearer_auth_epoch,
)
else:
row = await connection.fetchrow(
@@ -5303,68 +5559,278 @@ class PostgresDatabase:
# ── 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
- expires_at = datetime.now(timezone.utc) + timedelta(days=expires_days)
+ @staticmethod
+ async def _insert_initial_family_token(
+ conn: Any,
+ *,
+ user_id: str,
+ auth_epoch: int,
+ ) -> tuple[str, str]:
+ family_id = generate_family_id()
+ raw_token = generate_refresh_token()
+ token_hash = hash_refresh_token(raw_token)
+ now = datetime.now(timezone.utc)
+ absolute_expiry = now + timedelta(days=FAMILY_ABSOLUTE_LIFETIME_DAYS)
+ retain_until = absolute_expiry + timedelta(days=FAMILY_RETENTION_DAYS)
+ await conn.execute(
+ "INSERT INTO refresh_token_families("
+ "id,user_id,auth_epoch,state,created_at,absolute_expires_at,"
+ "retain_until) VALUES($1,$2,$3,'active',$4,$5,$6)",
+ family_id,
+ user_id,
+ auth_epoch,
+ now,
+ absolute_expiry,
+ retain_until,
+ )
+ await conn.execute(
+ "INSERT INTO refresh_tokens("
+ "id,user_id,is_revoked,expires_at,created_at,family_id,parent_id,"
+ "generation,state) VALUES($1,$2,0,$3,$4,$5,NULL,0,'active')",
+ token_hash,
+ user_id,
+ absolute_expiry,
+ now,
+ family_id,
+ )
+ return family_id, raw_token
+
+ async def create_refresh_token(
+ self,
+ user_id: str,
+ expires_days: int = FAMILY_ABSOLUTE_LIFETIME_DAYS,
+ ) -> str:
+ if expires_days != FAMILY_ABSOLUTE_LIFETIME_DAYS:
+ raise ValueError("refresh lifetime is fixed")
async with self._pool.acquire() as conn:
async with conn.transaction():
- await _acquire_refresh_token_user_lock(conn, user_id)
+ row = await conn.fetchrow(
+ "SELECT auth_epoch FROM users WHERE id=$1 AND is_active=1 "
+ "FOR UPDATE",
+ user_id,
+ )
+ if row is None:
+ raise ValueError("invalid refresh owner")
+ _, raw_token = await self._insert_initial_family_token(
+ conn,
+ user_id=user_id,
+ auth_epoch=int(row["auth_epoch"]),
+ )
+ return raw_token
+
+ async def create_login_session(
+ self,
+ username: str,
+ password: str,
+ token_factory: AccessTokenFactory,
+ ) -> SessionIssueResult:
+ async with self._pool.acquire() as conn:
+ async with conn.transaction():
+ row = await conn.fetchrow(
+ "SELECT id,username,hashed_password,role,is_active,auth_epoch "
+ "FROM users WHERE username=$1 FOR UPDATE",
+ username,
+ )
+ if row is None or not bool(row["is_active"]) or not verify_password(
+ password,
+ row["hashed_password"],
+ ):
+ return SessionIssueResult(SessionIssueStatus.INVALID)
+ family_id, raw_token = await self._insert_initial_family_token(
+ conn,
+ user_id=row["id"],
+ auth_epoch=int(row["auth_epoch"]),
+ )
+ access_token = token_factory(
+ {
+ "sub": row["username"],
+ "sid": family_id,
+ "ver": int(row["auth_epoch"]),
+ }
+ )
+ await conn.execute(
+ "UPDATE users SET last_login=now() WHERE id=$1",
+ row["id"],
+ )
await conn.execute(
- "INSERT INTO refresh_tokens(id,user_id,expires_at) VALUES($1,$2,$3)",
- token_hash, user_id, expires_at, # store hash, not raw
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','login_family_created','')"
)
- return raw_token # client gets raw token; DB stores only SHA-256 hash
+ return SessionIssueResult(
+ SessionIssueStatus.ISSUED,
+ IssuedTokenSession(
+ access_token=access_token,
+ refresh_token=raw_token,
+ user_id=row["id"],
+ subject=row["username"],
+ family_id=family_id,
+ auth_epoch=int(row["auth_epoch"]),
+ refresh_generation=0,
+ role=row["role"],
+ ),
+ )
- async def rotate_refresh_token(self, old_token: str) -> tuple[dict | None, str | None]:
- old_hash = hashlib.sha256(old_token.encode()).hexdigest() # look up by hash
- user: dict[str, Any] | None = None
- new_raw: str | None = None
+ @staticmethod
+ async def _revoke_family_rows(
+ conn: Any,
+ *,
+ family_id: str,
+ reason: str,
+ ) -> bool:
+ family = await conn.fetchrow(
+ "SELECT absolute_expires_at,state FROM refresh_token_families "
+ "WHERE id=$1 FOR UPDATE",
+ family_id,
+ )
+ if family is None:
+ return False
+ if family["state"] == "active":
+ now = datetime.now(timezone.utc)
+ retain_until = max(family["absolute_expires_at"], now) + timedelta(
+ days=FAMILY_RETENTION_DAYS
+ )
+ await conn.execute(
+ "UPDATE refresh_token_families SET state='revoked',revoked_at=$2,"
+ "revoke_reason=$3,retain_until=$4 WHERE id=$1 AND state='active'",
+ family_id,
+ now,
+ reason,
+ retain_until,
+ )
+ await conn.execute(
+ "UPDATE refresh_tokens SET state='retired',is_revoked=1,"
+ "revoked_at=$2 WHERE family_id=$1 AND state='active'",
+ family_id,
+ now,
+ )
+ return True
+ return False
+
+ async def rotate_refresh_session(
+ self,
+ old_token: str,
+ token_factory: AccessTokenFactory,
+ ) -> RefreshRotationResult:
+ old_hash = hash_refresh_token(old_token)
async with self._pool.acquire() as conn:
async with conn.transaction():
- user_id = await conn.fetchval(
- "SELECT user_id FROM refresh_tokens WHERE id=$1",
+ token = await conn.fetchrow(
+ "SELECT family_id FROM refresh_tokens WHERE id=$1",
old_hash,
)
- if user_id is None:
- return None, None
-
- await _acquire_refresh_token_user_lock(conn, user_id)
+ if token is None:
+ return RefreshRotationResult(RefreshRotationStatus.INVALID)
row = await conn.fetchrow(
- """UPDATE refresh_tokens AS rt
- SET is_revoked=1, used_at=now()
- FROM users AS u
- WHERE rt.id=$1
- AND rt.user_id=$2
- AND rt.is_revoked=0
- AND rt.expires_at > now()
- AND u.id=rt.user_id
- AND u.is_active=1
- RETURNING u.id AS uid, u.username, u.role""",
+ "SELECT rt.user_id,rt.family_id,rt.generation,rt.state,"
+ "rt.expires_at,f.auth_epoch,f.state AS family_state,"
+ "f.absolute_expires_at,u.auth_epoch AS user_epoch,"
+ "u.username,u.role,u.is_active "
+ "FROM refresh_token_families AS f "
+ "JOIN refresh_tokens AS rt ON rt.family_id=f.id AND rt.id=$1 "
+ "JOIN users AS u ON u.id=f.user_id "
+ "WHERE f.id=$2 FOR UPDATE OF f,u,rt",
old_hash,
- user_id,
+ token["family_id"],
)
if row is None:
- return None, None
-
- new_raw = secrets.token_urlsafe(48)
- new_hash = hashlib.sha256(new_raw.encode()).hexdigest()
- expires_at = datetime.now(timezone.utc) + timedelta(days=30)
+ return RefreshRotationResult(RefreshRotationStatus.INVALID)
+ if row["state"] != "active":
+ await self._revoke_family_rows(
+ conn,
+ family_id=row["family_id"],
+ reason="replay",
+ )
+ await conn.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','refresh_replay','')"
+ )
+ return RefreshRotationResult(RefreshRotationStatus.REPLAYED)
+ if (
+ row["family_state"] != "active"
+ or not bool(row["is_active"])
+ or int(row["auth_epoch"]) != int(row["user_epoch"])
+ or row["expires_at"] <= datetime.now(timezone.utc)
+ or row["absolute_expires_at"] <= datetime.now(timezone.utc)
+ ):
+ return RefreshRotationResult(RefreshRotationStatus.INVALID)
+ updated = await conn.execute(
+ "UPDATE refresh_tokens SET state='consumed',is_revoked=1,"
+ "used_at=now() WHERE id=$1 AND state='active' AND is_revoked=0",
+ old_hash,
+ )
+ if updated != "UPDATE 1":
+ await self._revoke_family_rows(
+ conn,
+ family_id=row["family_id"],
+ reason="replay",
+ )
+ return RefreshRotationResult(RefreshRotationStatus.REPLAYED)
+ raw_child = generate_refresh_token()
+ child_hash = hash_refresh_token(raw_child)
+ generation = int(row["generation"]) + 1
await conn.execute(
- "INSERT INTO refresh_tokens(id,user_id,expires_at) VALUES($1,$2,$3)",
- new_hash, user_id, expires_at, # store hash
+ "INSERT INTO refresh_tokens("
+ "id,user_id,is_revoked,expires_at,created_at,family_id,parent_id,"
+ "generation,state) VALUES($1,$2,0,$3,now(),$4,$5,$6,'active')",
+ child_hash,
+ row["user_id"],
+ row["absolute_expires_at"],
+ row["family_id"],
+ old_hash,
+ generation,
)
- user = {
- "id": row["uid"],
- "username": row["username"],
- "role": row["role"],
- }
- if user is None or new_raw is None:
- return None, None
- return user, new_raw # return raw to client
+ access_token = token_factory(
+ {
+ "sub": row["username"],
+ "sid": row["family_id"],
+ "ver": int(row["auth_epoch"]),
+ }
+ )
+ await conn.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','refresh_rotated','')"
+ )
+ return RefreshRotationResult(
+ RefreshRotationStatus.ROTATED,
+ IssuedTokenSession(
+ access_token=access_token,
+ refresh_token=raw_child,
+ user_id=row["user_id"],
+ subject=row["username"],
+ family_id=row["family_id"],
+ auth_epoch=int(row["auth_epoch"]),
+ refresh_generation=generation,
+ role=row["role"],
+ ),
+ )
- async def revoke_access_token(self, jti: str, user_id: str, expires_at: str) -> None:
- parsed_expires_at = _parse_postgres_timestamptz(expires_at)
+ async def rotate_refresh_token(
+ self,
+ old_token: str,
+ ) -> tuple[dict[str, Any] | None, str | None]:
+ result = await self.rotate_refresh_session(old_token, lambda _claims: "compat")
+ if result.session is None:
+ return None, None
+ session = result.session
+ return {
+ "id": session.user_id,
+ "username": session.subject,
+ "role": session.role,
+ "family_id": session.family_id,
+ "auth_epoch": session.auth_epoch,
+ }, session.refresh_token
+
+ async def revoke_access_token(
+ self,
+ jti: str,
+ user_id: str,
+ expires_at: str | datetime,
+ ) -> None:
+ parsed_expires_at = (
+ expires_at
+ if isinstance(expires_at, datetime)
+ else _parse_postgres_timestamptz(expires_at)
+ )
async with self._pool.acquire() as conn:
await conn.execute(
"INSERT INTO revoked_access_tokens(jti,user_id,expires_at) VALUES($1,$2,$3) "
@@ -5384,15 +5850,155 @@ class PostgresDatabase:
async def revoke_all_refresh_tokens(self, user_id: str) -> None:
async with self._pool.acquire() as conn:
async with conn.transaction():
- await _acquire_refresh_token_user_lock(conn, user_id)
+ rows = await conn.fetch(
+ "SELECT id FROM refresh_token_families "
+ "WHERE user_id=$1 AND state='active' FOR UPDATE",
+ user_id,
+ )
+ for row in rows:
+ await self._revoke_family_rows(
+ conn,
+ family_id=row["id"],
+ reason="operator_revoke",
+ )
+
+ async def revoke_current_session(
+ self,
+ *,
+ user_id: str,
+ family_id: str,
+ jti: str,
+ expires_at: datetime,
+ ) -> SessionRevocationResult:
+ async with self._pool.acquire() as conn:
+ async with conn.transaction():
+ owner = await conn.fetchval(
+ "SELECT 1 FROM refresh_token_families "
+ "WHERE id=$1 AND user_id=$2 FOR UPDATE",
+ family_id,
+ user_id,
+ )
+ if owner is None:
+ return SessionRevocationResult(SessionRevocationStatus.INVALID)
+ changed = await self._revoke_family_rows(
+ conn,
+ family_id=family_id,
+ reason="logout_current",
+ )
+ await conn.execute(
+ "INSERT INTO revoked_access_tokens(jti,user_id,expires_at) "
+ "VALUES($1,$2,$3) ON CONFLICT(jti) DO NOTHING",
+ jti,
+ user_id,
+ expires_at,
+ )
+ if changed:
+ await conn.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','logout_current','')"
+ )
+ return SessionRevocationResult(
+ SessionRevocationStatus.REVOKED
+ if changed
+ else SessionRevocationStatus.ALREADY_REVOKED
+ )
+
+ async def revoke_all_sessions(
+ self,
+ *,
+ user_id: str,
+ jti: str,
+ expires_at: datetime,
+ ) -> SessionRevocationResult:
+ async with self._pool.acquire() as conn:
+ async with conn.transaction():
+ updated = await conn.fetchval(
+ "UPDATE users SET auth_epoch=auth_epoch+1 "
+ "WHERE id=$1 AND is_active=1 RETURNING auth_epoch",
+ user_id,
+ )
+ if updated is None:
+ return SessionRevocationResult(SessionRevocationStatus.INVALID)
+ rows = await conn.fetch(
+ "SELECT id FROM refresh_token_families "
+ "WHERE user_id=$1 AND state='active' FOR UPDATE",
+ user_id,
+ )
+ for row in rows:
+ await self._revoke_family_rows(
+ conn,
+ family_id=row["id"],
+ reason="logout_all",
+ )
+ await conn.execute(
+ "INSERT INTO revoked_access_tokens(jti,user_id,expires_at) "
+ "VALUES($1,$2,$3) ON CONFLICT(jti) DO NOTHING",
+ jti,
+ user_id,
+ expires_at,
+ )
+ await conn.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system','logout_all','')"
+ )
+ return SessionRevocationResult(SessionRevocationStatus.REVOKED)
+
+ async def apply_user_security_event(
+ self,
+ *,
+ user_id: str,
+ reason: str,
+ new_password_hash: str | None = None,
+ new_role: str | None = None,
+ is_active: bool | None = None,
+ ) -> bool:
+ if reason not in {
+ "password_change",
+ "password_reset",
+ "role_change",
+ "user_status_change",
+ }:
+ raise ValueError("invalid security event")
+ async with self._pool.acquire() as conn:
+ async with conn.transaction():
+ row = await conn.fetchrow(
+ "SELECT id FROM users WHERE id=$1 FOR UPDATE",
+ user_id,
+ )
+ if row is None:
+ return False
await conn.execute(
- "UPDATE refresh_tokens SET is_revoked=1 WHERE user_id=$1", user_id
+ "UPDATE users SET auth_epoch=auth_epoch+1,"
+ "hashed_password=COALESCE($2,hashed_password),"
+ "role=COALESCE($3,role),"
+ "is_active=COALESCE($4,is_active) WHERE id=$1",
+ user_id,
+ new_password_hash,
+ new_role,
+ is_active,
+ )
+ rows = await conn.fetch(
+ "SELECT id FROM refresh_token_families "
+ "WHERE user_id=$1 AND state='active' FOR UPDATE",
+ user_id,
)
+ for family in rows:
+ await self._revoke_family_rows(
+ conn,
+ family_id=family["id"],
+ reason=reason,
+ )
+ await conn.execute(
+ "INSERT INTO audit_log(actor,action,detail) VALUES("
+ "'auth-system',$1,'')",
+ reason,
+ )
+ return True
async def purge_expired_tokens(self) -> int:
async with self._pool.acquire() as conn:
result = await conn.execute(
- "DELETE FROM refresh_tokens WHERE is_revoked=1 OR expires_at < now() - interval '7 days'"
+ "DELETE FROM refresh_token_families WHERE retain_until <= now()"
)
await self.purge_expired_websocket_tickets()
# asyncpg returns "DELETE N" as a string
diff --git a/ares/db/schema.py b/ares/db/schema.py
index 4bb6a6f..0e81a1c 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 = 7
+SCHEMA_VERSION = 8
CREATE_TABLES = """
PRAGMA journal_mode = WAL;
@@ -169,7 +169,9 @@ CREATE TABLE IF NOT EXISTS users (
is_active INTEGER NOT NULL DEFAULT 1,
created_by TEXT NOT NULL DEFAULT 'system',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
- last_login TEXT
+ last_login TEXT,
+ auth_epoch INTEGER NOT NULL DEFAULT 1
+ CONSTRAINT ck_users_auth_epoch CHECK (auth_epoch >= 1)
);
CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
@@ -196,17 +198,142 @@ CREATE INDEX IF NOT EXISTS idx_apikeys_prefix ON api_keys(key_prefix);
-- ── Refresh Tokens (★ v5) ────────────────────────────────────────────────────
-- Opaque tokens stored in DB; rotated on each use (rotation security).
+CREATE TABLE IF NOT EXISTS refresh_token_families (
+ id TEXT NOT NULL PRIMARY KEY
+ CONSTRAINT ck_refresh_family_id CHECK (
+ length(id)=43
+ AND id NOT GLOB '*[^A-Za-z0-9_-]*'
+ ),
+ user_id TEXT NOT NULL
+ CONSTRAINT fk_refresh_family_user
+ REFERENCES users(id) ON DELETE CASCADE,
+ auth_epoch INTEGER NOT NULL
+ CONSTRAINT ck_refresh_family_epoch CHECK (auth_epoch >= 1),
+ state TEXT NOT NULL
+ CONSTRAINT ck_refresh_family_state CHECK (
+ state IN ('active','revoked')
+ ),
+ created_at TEXT NOT NULL,
+ absolute_expires_at TEXT NOT NULL,
+ revoked_at TEXT,
+ revoke_reason TEXT,
+ retain_until TEXT NOT NULL,
+ CONSTRAINT uq_refresh_family_owner UNIQUE (id,user_id),
+ CONSTRAINT ck_refresh_family_revocation_shape CHECK (
+ (state='active' AND revoked_at IS NULL AND revoke_reason IS NULL)
+ OR
+ (state='revoked' AND revoked_at IS NOT NULL AND revoke_reason IS NOT NULL)
+ ),
+ CONSTRAINT ck_refresh_family_reason CHECK (
+ revoke_reason IS NULL OR revoke_reason IN (
+ 'replay','logout_current','logout_all','password_change',
+ 'password_reset','role_change','user_status_change','rollout_reset',
+ 'expired','operator_revoke'
+ )
+ ),
+ CONSTRAINT ck_refresh_family_created_at_utc 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_refresh_family_absolute_expires_at_utc CHECK (
+ strftime('%Y-%m-%dT%H:%M:%fZ',absolute_expires_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ',absolute_expires_at)=absolute_expires_at
+ ),
+ CONSTRAINT ck_refresh_family_revoked_at_utc CHECK (
+ revoked_at IS NULL OR (
+ strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at)=revoked_at
+ )
+ ),
+ CONSTRAINT ck_refresh_family_retain_until_utc CHECK (
+ strftime('%Y-%m-%dT%H:%M:%fZ',retain_until) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ',retain_until)=retain_until
+ ),
+ CONSTRAINT ck_refresh_family_expiry_order CHECK (
+ absolute_expires_at > created_at
+ ),
+ CONSTRAINT ck_refresh_family_retention_order CHECK (
+ retain_until > absolute_expires_at
+ AND (revoked_at IS NULL OR retain_until > revoked_at)
+ )
+);
+
+CREATE INDEX IF NOT EXISTS idx_refresh_family_user_state_exp
+ ON refresh_token_families(user_id,state,absolute_expires_at);
+CREATE INDEX IF NOT EXISTS idx_refresh_family_retain
+ ON refresh_token_families(retain_until);
+
CREATE TABLE IF NOT EXISTS refresh_tokens (
- id TEXT PRIMARY KEY, -- random UUID = the token itself
- user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ id TEXT NOT NULL PRIMARY KEY
+ CONSTRAINT ck_refresh_token_hash CHECK (
+ length(id)=64 AND id NOT GLOB '*[^0-9a-f]*'
+ ),
+ user_id TEXT NOT NULL
+ CONSTRAINT fk_refresh_tokens_user
+ REFERENCES users(id) ON DELETE CASCADE,
is_revoked INTEGER NOT NULL DEFAULT 0,
expires_at TEXT NOT NULL,
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
- used_at TEXT -- NULL = never used
+ created_at TEXT NOT NULL,
+ used_at TEXT,
+ family_id TEXT NOT NULL,
+ parent_id TEXT,
+ generation INTEGER NOT NULL,
+ state TEXT NOT NULL,
+ revoked_at TEXT,
+ CONSTRAINT uq_refresh_token_family_hash UNIQUE (family_id,id),
+ CONSTRAINT uq_refresh_token_family_generation UNIQUE (family_id,generation),
+ CONSTRAINT uq_refresh_token_parent UNIQUE (parent_id),
+ CONSTRAINT fk_refresh_token_family_owner
+ FOREIGN KEY (family_id,user_id)
+ REFERENCES refresh_token_families(id,user_id) ON DELETE CASCADE,
+ CONSTRAINT fk_refresh_token_parent
+ FOREIGN KEY (family_id,parent_id)
+ REFERENCES refresh_tokens(family_id,id)
+ ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
+ CONSTRAINT ck_refresh_token_generation CHECK (generation >= 0),
+ CONSTRAINT ck_refresh_token_parent_shape CHECK (
+ (generation=0 AND parent_id IS NULL)
+ OR (generation>0 AND parent_id IS NOT NULL)
+ ),
+ CONSTRAINT ck_refresh_token_state CHECK (
+ state IN ('active','consumed','retired')
+ ),
+ CONSTRAINT ck_refresh_token_state_shape CHECK (
+ (state='active' AND is_revoked=0 AND used_at IS NULL AND revoked_at IS NULL)
+ OR
+ (state='consumed' AND is_revoked=1 AND used_at IS NOT NULL AND revoked_at IS NULL)
+ OR
+ (state='retired' AND is_revoked=1 AND revoked_at IS NOT NULL)
+ ),
+ CONSTRAINT ck_refresh_token_created_utc 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_refresh_token_expires_utc 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_refresh_token_used_utc CHECK (
+ used_at IS NULL OR (
+ strftime('%Y-%m-%dT%H:%M:%fZ',used_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ',used_at)=used_at
+ )
+ ),
+ CONSTRAINT ck_refresh_token_revoked_utc CHECK (
+ revoked_at IS NULL OR (
+ strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at) IS NOT NULL
+ AND strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at)=revoked_at
+ )
+ ),
+ CONSTRAINT ck_refresh_token_expiry_order CHECK (expires_at > created_at)
);
CREATE INDEX IF NOT EXISTS idx_refresh_user ON refresh_tokens(user_id);
CREATE INDEX IF NOT EXISTS idx_refresh_exp ON refresh_tokens(expires_at);
+CREATE UNIQUE INDEX IF NOT EXISTS uq_refresh_token_one_active
+ ON refresh_tokens(family_id) WHERE state='active';
+CREATE INDEX IF NOT EXISTS idx_refresh_family_generation
+ ON refresh_tokens(family_id,generation);
-- Revoked access token JTIs — allows early revocation before natural expiry (60 min TTL)
CREATE TABLE IF NOT EXISTS revoked_access_tokens (
@@ -244,6 +371,8 @@ CREATE TABLE IF NOT EXISTS websocket_tickets (
created_at TEXT NOT NULL,
expires_at TEXT NOT NULL,
consumed_at TEXT,
+ bearer_family_id TEXT,
+ bearer_auth_epoch INTEGER,
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
@@ -281,6 +410,12 @@ CREATE TABLE IF NOT EXISTS websocket_tickets (
AND strftime(
'%Y-%m-%dT%H:%M:%fZ', bearer_expires_at
)=bearer_expires_at
+ AND bearer_family_id IS NOT NULL
+ AND length(bearer_family_id)=43
+ AND bearer_family_id NOT GLOB '*[^A-Za-z0-9_-]*'
+ AND bearer_auth_epoch IS NOT NULL
+ AND typeof(bearer_auth_epoch)='integer'
+ AND bearer_auth_epoch >= 1
AND api_key_id IS NULL
AND required_scope IS NULL
)
@@ -290,12 +425,17 @@ CREATE TABLE IF NOT EXISTS websocket_tickets (
AND bearer_subject IS NULL
AND bearer_jti IS NULL
AND bearer_expires_at IS NULL
+ AND bearer_family_id IS NULL
+ AND bearer_auth_epoch 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'
)
- )
+ ),
+ CONSTRAINT fk_ws_ticket_bearer_family
+ FOREIGN KEY (bearer_family_id,user_id)
+ REFERENCES refresh_token_families(id,user_id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_ws_tickets_expires
ON websocket_tickets(expires_at);
@@ -305,6 +445,8 @@ 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);
+CREATE INDEX IF NOT EXISTS idx_ws_tickets_bearer_family
+ ON websocket_tickets(bearer_family_id);
"""
# ── Migration: v4 → v5 ────────────────────────────────────────────────────────
diff --git a/ares/db/websocket_tickets.py b/ares/db/websocket_tickets.py
index 5d065b0..681504d 100644
--- a/ares/db/websocket_tickets.py
+++ b/ares/db/websocket_tickets.py
@@ -8,6 +8,8 @@ from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
+from ares.core.token_sessions import require_family_id
+
WEBSOCKET_TICKET_TTL_SECONDS = 30
WEBSOCKET_TICKET_ENTROPY_BYTES = 32
WEBSOCKET_TICKET_PATTERN = re.compile(r"^[A-Za-z0-9_-]{43}$")
@@ -98,6 +100,8 @@ class BearerTicketSource:
subject: str = field(repr=False)
jti: str = field(repr=False)
expires_at: datetime = field(repr=False)
+ family_id: str = field(repr=False)
+ auth_epoch: int = field(repr=False)
def __post_init__(self) -> None:
object.__setattr__(
@@ -110,6 +114,9 @@ class BearerTicketSource:
object.__setattr__(
self, "expires_at", normalize_utc_datetime(self.expires_at)
)
+ object.__setattr__(self, "family_id", require_family_id(self.family_id))
+ if isinstance(self.auth_epoch, bool) or self.auth_epoch < 1:
+ raise ValueError("invalid bearer authentication epoch")
@property
def credential_kind(self) -> WebSocketTicketCredentialKind:
@@ -148,6 +155,8 @@ class ConsumedWebSocketTicket:
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)
+ bearer_family_id: str | None = field(default=None, repr=False)
+ bearer_auth_epoch: int | 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)
@@ -165,6 +174,8 @@ class ConsumedWebSocketTicket:
self.bearer_subject is None
or self.bearer_jti is None
or self.bearer_expires_at is None
+ or self.bearer_family_id is None
+ or self.bearer_auth_epoch is None
or self.api_key_id is not None
or self.required_scope is not None
):
@@ -184,6 +195,13 @@ class ConsumedWebSocketTicket:
"bearer_expires_at",
normalize_utc_datetime(self.bearer_expires_at),
)
+ object.__setattr__(
+ self,
+ "bearer_family_id",
+ require_family_id(self.bearer_family_id),
+ )
+ if isinstance(self.bearer_auth_epoch, bool) or self.bearer_auth_epoch < 1:
+ raise ValueError("invalid bearer authentication epoch")
elif self.credential_kind is WebSocketTicketCredentialKind.API_KEY:
if (
self.api_key_id is None
@@ -191,6 +209,8 @@ class ConsumedWebSocketTicket:
or self.bearer_subject is not None
or self.bearer_jti is not None
or self.bearer_expires_at is not None
+ or self.bearer_family_id is not None
+ or self.bearer_auth_epoch is not None
):
raise ValueError("invalid API-key ticket handle")
object.__setattr__(
diff --git a/docker/README.md b/docker/README.md
index 93214b0..ee75c86 100644
--- a/docker/README.md
+++ b/docker/README.md
@@ -44,3 +44,10 @@ and run the explicit verification/adoption workflow described in
adoption is serialized with a transaction-scoped advisory lock; SQLite adoption
requires exclusive ownership and a new durable backup target. Keep additive
migrations installed if the application image is rolled back.
+
+Revision `0009` introduces authoritative refresh-token families and forces a
+one-time browser reauthentication. Drain WebSockets and stop every old
+container before the database upgrade, then start the matching backend and
+frontend together. Mixed workers are unsupported because managed ownership is
+revision-exact. A container-image rollback does not downgrade the additive
+schema; return to a compatible forward image instead.
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 3939c9c..f44f622 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -29,16 +29,28 @@ username=alice&password=changeme
"refresh_token": "rt-...",
"token_type": "bearer",
"role": "operator",
+ "refresh_generation": 0,
+ "session_coordination_key": "non-secret-cross-tab-key",
"expires_in": 3600
}
```
+Each successful login creates an independent device/session family with a
+fixed 30-day absolute lifetime. Access JWTs carry the family identifier and
+current authentication epoch; authorization always resolves the current user,
+role, family, epoch, and JTI from the database. The JWT role claim is not an
+authority source.
+
---
### `POST /auth/refresh`
-Rotate refresh token. Old token is revoked; new access + refresh tokens issued.
-Rate limited per IP (same limit as `/auth/token`).
+Atomically consume the current refresh token and issue generation `n + 1` in
+the same family. Rate limited per IP (same limit as `/auth/token`). A known
+consumed-token replay, including a concurrent loser or retry after a lost
+response, revokes the complete family and returns the same fixed `401` as any
+invalid, expired, unknown, or revoked refresh token. No replacement token can
+be recovered; the user must sign in again.
```json
{ "refresh_token": "rt-..." }
@@ -48,7 +60,17 @@ Rate limited per IP (same limit as `/auth/token`).
### `POST /auth/logout`
-Revoke current access token (adds JTI to blacklist).
+Revoke the current bearer family and access-token JTI. Other device families
+remain active. API-key authentication is unchanged and this call is
+idempotently successful for API-key callers.
+
+---
+
+### `POST /auth/logout-all`
+
+Increment the current user's authentication epoch, revoke every bearer family,
+and revoke the caller's JTI. Existing bearer HTTP and WebSocket authority fails
+on its next database resolution. API keys remain outside bearer families.
---
diff --git a/docs/database-migrations.md b/docs/database-migrations.md
index e6a3a3f..430dee1 100644
--- a/docs/database-migrations.md
+++ b/docs/database-migrations.md
@@ -8,8 +8,8 @@ an existing unversioned catalog.
## Managed and unversioned databases
A managed database has one valid `alembic_version` relation and exactly one
-known revision row. Revision `0008` is current and forward-only. Managed
-revisions `0001` through `0007` use normal Alembic migration; malformed or
+known revision row. Revision `0009` is current and forward-only. Managed
+revisions `0001` through `0008` use normal Alembic migration; malformed or
unknown version metadata is rejected.
An unversioned database has no Alembic version relation. The adoption verifier
@@ -32,7 +32,7 @@ python -m ares.db.migrations verify-adoption
A supported unversioned catalog reports a fixed readiness identifier ending in
its proven predecessor (`0006` or `0007`). A current managed database reports
-`ARES-M2B-ALREADY-MANAGED:0008`. No version relation is created by verification.
+`ARES-M2B-ALREADY-MANAGED:0009`. No version relation is created by verification.
After adoption or normal migration, verify the managed contract:
@@ -78,7 +78,7 @@ python -m ares.db.migrations adopt --confirm-adoption --confirm-external-backup
PostgreSQL adoption uses one connection, one explicit transaction, and a stable
transaction-scoped advisory lock. Complete verification occurs under that lock;
-the proven predecessor is stamped and upgraded to `0008` on the same
+the proven predecessor is stamped and upgraded through `0009` on the same
connection. DDL, data, and version metadata roll back together on failure.
Concurrent adoption reports a fixed ownership-busy result. Objects in unrelated
schemas are not changed; unexpected objects in the selected schema are rejected.
@@ -106,5 +106,22 @@ already-managed result.
Diagnostics are fixed identifiers and never contain database URLs, credentials,
paths, schema identities, SQL, rows, digests, or exception text. Direct or blind
-`alembic stamp 0008` is unsupported. Application rollback does not remove
+`alembic stamp 0009` is unsupported. Application rollback does not remove
additive schema or migration history.
+
+## Revision 0009 token-family rollout
+
+Revision `0009` adds refresh-token families, one-time lineage, user
+authentication epochs, and bearer-family binding for WebSocket tickets. It is
+additive and forward-only. Existing canonical hashed refresh tokens and bearer
+tickets are preserved but deliberately moved into revoked `rollout_reset`
+families, so every existing browser bearer session must sign in again after the
+upgrade. Unsafe legacy refresh identifiers are rejected before revision
+advancement; they are never deleted or normalized.
+
+Revision `0009` must be deployed during an atomic maintenance window. Stop all
+old workers, back up the database, upgrade, deploy the matching backend and
+frontend, and require reauthentication. Workers that require exact revision
+`0008` cannot run against `0009`; mixed old/new workers are unsupported. A code
+rollback leaves the additive migration installed and requires a compatible
+forward deployment rather than a database downgrade.
diff --git a/docs/frontend.md b/docs/frontend.md
index f37a330..31e3b67 100644
--- a/docs/frontend.md
+++ b/docs/frontend.md
@@ -40,8 +40,18 @@ Then open `http://127.0.0.1:5173/dashboard/`.
- Refresh calls `POST /auth/refresh` with JSON `{ "refresh_token": "..." }`.
- Access tokens are held in memory.
- Refresh tokens are stored in `sessionStorage`; React output escaping and the
- FastAPI CSP reduce script injection risk.
-- Logout calls `POST /auth/logout` and clears local token state.
+ FastAPI CSP reduce script injection risk. This residual browser-token/XSS
+ exposure is intentionally deferred to the HttpOnly-cookie/CSRF conversion in
+ Phase 5B.2.
+- Logout calls `POST /auth/logout` and revokes only the current device family;
+ **Logout all devices** calls `POST /auth/logout-all`. Both clear local state
+ even when the remote request fails.
+- Refresh is single-flight within a tab and uses a non-secret family-derived
+ coordination key, generation counter, Web Locks, `localStorage`, and
+ `BroadcastChannel` for cross-tab exclusion/invalidation. Raw access or
+ refresh tokens are never posted across tabs or written to `localStorage`.
+ A tab that loses a refresh race discards its session and requires login; it
+ never retries a consumed predecessor.
- Each main campaign WebSocket connection first requests a 30-second,
single-use ticket with authenticated `POST
/campaigns/{campaign_id}/websocket-ticket`. The ticket exists only across the
@@ -78,7 +88,8 @@ Then open `http://127.0.0.1:5173/dashboard/`.
notifications from the current session.
- Notification state must not persist bodies, API keys, tokens, stack traces,
or raw payloads.
-- The topbar keeps the user identity and logout action.
+- The topbar keeps the user identity plus current-device and all-device logout
+ actions.
## Safety
@@ -99,6 +110,14 @@ campaign change, cleanup, or unmount. A same-session access-token refresh does
not invalidate that barrier. Navigating away closes the connection, so users
request a fresh ticket when they return.
+Every token response carries a refresh generation and non-secret coordination
+key. A response is installed only if it belongs to the captured session and is
+the exact next generation. Logout, account replacement, replay/family
+revocation, or peer-tab generation advancement increments the session revision,
+clears credentials, closes bearer-backed WebSockets through normal lifecycle
+handling, and prevents an infinite refresh loop. A same-family token refresh
+does not change identity until another tab wins it.
+
Production frontend and backend versions must roll out atomically, with
existing sockets drained. Mixed old/new versions are unsupported, and rollback
replaces both together while leaving additive migrations installed. Use
diff --git a/docs/security-model.md b/docs/security-model.md
index 83be187..618a0cc 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -152,7 +152,29 @@ authentication, campaign-ownership, WebSocket, credential-transport, or
deployment parity. Query-token exposure and its global live-WebSocket design
remain. Full retirement is the preferred final control.
-Tokens are issued by `POST /auth/token` with valid operator credentials (bcrypt-hashed password). Default expiry: 1 hour.
+Tokens are issued by `POST /auth/token` with valid operator credentials
+(bcrypt-hashed password). Each login creates an independent refresh-token
+family with one active token, a 30-day absolute lifetime, and no sliding
+extension. Only lowercase SHA-256 token hashes are stored. Access JWTs contain
+`sub`, `sid`, `ver`, `jti`, `iat`, and `exp`; they contain no role claim.
+Current database user status, role, authentication epoch, family state, and JTI
+are authoritative on every bearer resolution. Default access expiry is one
+hour.
+
+Refresh is a one-winner database transaction. The predecessor is consumed and
+exactly one child is inserted before commit; the raw child is returned only
+after commit. Reuse of a known consumed or revoked predecessor atomically
+revokes the complete family, including the committed winner after a concurrent
+or lost-response retry. Unknown random values reveal nothing and mutate
+nothing. `POST /auth/logout` revokes only the current family;
+`POST /auth/logout-all`, password changes/resets, role changes, and activation
+state changes increment the user epoch and revoke all families. Separate login
+families remain isolated, and API keys never enter refresh families.
+
+Family lineage is retained until 30 days after the later of family expiry or
+revocation. Fixed security audit actions record login-family creation,
+rotation, replay revocation, current/all-device logout, and account security
+events without token, hash, family, user, SQL, or exception values.
### Main WebSocket tickets
@@ -172,6 +194,12 @@ before protected events. This resolution is read-only and remains possible
after the ticket row expires or is purged. No registry entry retains a raw
ticket, bearer, API key, ticket hash, or original query string.
+Bearer-backed tickets also bind the user authentication epoch and refresh
+family. Family replay, logout, password/security events, expiry, or revocation
+therefore deny ticket consumption and terminate connected bearer sockets on
+the next heartbeat/event revalidation. API-key-backed tickets remain
+independent of refresh families.
+
Tickets remain visible to the browser and any upstream component that receives
the handshake URL, so production clients must initiate HTTPS/WSS directly.
The production nginx TLS log uses `$uri`, which omits query strings. Its
diff --git a/frontend/src/api/client.test.ts b/frontend/src/api/client.test.ts
index f32d991..a176b5e 100644
--- a/frontend/src/api/client.test.ts
+++ b/frontend/src/api/client.test.ts
@@ -39,6 +39,23 @@ function resetTestSessionStorage(): void {
}
}
+function installSession(
+ accessToken: string,
+ refreshToken: string,
+ coordinationKey = "coordination-a",
+ generation = 0
+): void {
+ const session = beginIdentityTransition();
+ const installed = installTokenPairIfCurrent(
+ session,
+ accessToken,
+ refreshToken,
+ coordinationKey,
+ generation
+ );
+ requireFixed(installed, "expected authoritative test session");
+}
+
describe("api client auth", () => {
beforeEach(() => {
clearTokens();
@@ -65,7 +82,9 @@ describe("api client auth", () => {
refresh_token: "refresh",
token_type: "bearer",
expires_in: 3600,
- role: "operator"
+ role: "operator",
+ refresh_generation: 0,
+ session_coordination_key: "coordination-a"
}),
{ status: 200 }
);
@@ -80,7 +99,7 @@ describe("api client auth", () => {
});
it("refreshes the access token from the stored refresh token", async () => {
- setRefreshToken("refresh-old");
+ installSession("access-old", "refresh-old");
const fetchMock = vi.fn(async (_path: string, init?: RequestInit) => {
expect(init?.method).toBe("POST");
const body = JSON.parse(String(init?.body)) as { refresh_token?: unknown };
@@ -92,7 +111,9 @@ describe("api client auth", () => {
refresh_token: "refresh-new",
token_type: "bearer",
expires_in: 3600,
- role: "operator"
+ role: "operator",
+ refresh_generation: 1,
+ session_coordination_key: "coordination-a"
}),
{ status: 200 }
);
@@ -107,7 +128,7 @@ describe("api client auth", () => {
});
it("clears tokens when refresh fails", async () => {
- setRefreshToken("expired-refresh");
+ installSession("expired-access", "expired-refresh");
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 401 })));
await expect(refreshAccessToken()).resolves.toBe(false);
@@ -121,7 +142,9 @@ describe("api client auth", () => {
refresh_token: "refresh",
token_type: "bearer",
expires_in: 3600,
- role: "operator"
+ role: "operator",
+ refresh_generation: 0,
+ session_coordination_key: "coordination-a"
}),
{ status: 200 }
)));
@@ -226,7 +249,9 @@ describe("api client auth", () => {
const installed = installTokenPairIfCurrent(
recoveredSession,
"access-after-read-failure",
- "refresh-after-read-failure"
+ "refresh-after-read-failure",
+ "coordination-recovered",
+ 0
);
requireFixed(installed, "expected valid token-pair recovery");
const recoveredAccessTokenCurrent = getAccessToken() === "access-after-read-failure";
@@ -240,7 +265,9 @@ describe("api client auth", () => {
const installed = installTokenPairIfCurrent(
activeSession,
"access-before-clear-failure",
- "refresh-before-clear-failure"
+ "refresh-before-clear-failure",
+ "coordination-clear",
+ 0
);
requireFixed(installed, "expected active session setup");
const beforeInvalidation = captureSession();
@@ -299,7 +326,9 @@ describe("api client auth", () => {
const recovered = installTokenPairIfCurrent(
recoveredSession,
"access-after-clear-failure",
- "refresh-after-clear-failure"
+ "refresh-after-clear-failure",
+ "coordination-recovered",
+ 0
);
requireFixed(recovered, "expected token-pair recovery after cleanup failure");
const recoveredAccessTokenCurrent = getAccessToken() === "access-after-clear-failure";
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index 5590c34..9f8b6a3 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -1,6 +1,6 @@
// Compatibility facade: existing feature imports continue to use this stable public API.
export { apiBlobRequest, apiRequest, ApiError, refreshAccessToken } from "./http";
-export { api, buildModuleRunPayload, campaignEventsPath, login, logout } from "./endpoints";
+export { api, buildModuleRunPayload, campaignEventsPath, login, logout, logoutAll } from "./endpoints";
export {
beginIdentityTransition,
captureSession,
@@ -9,6 +9,7 @@ export {
getRefreshToken,
invalidateSession,
isSessionCurrent,
+ readCoordinationRecord,
subscribeToSessionInvalidation,
setAccessToken,
setRefreshToken
diff --git a/frontend/src/api/endpoints.ts b/frontend/src/api/endpoints.ts
index 6662342..11bf343 100644
--- a/frontend/src/api/endpoints.ts
+++ b/frontend/src/api/endpoints.ts
@@ -31,7 +31,13 @@ export async function login(username: string, password: string): Promise<TokenRe
},
false
);
- if (!installTokenPairIfCurrent(loginSession, token.access_token, token.refresh_token)) {
+ if (!installTokenPairIfCurrent(
+ loginSession,
+ token.access_token,
+ token.refresh_token,
+ token.session_coordination_key,
+ token.refresh_generation
+ )) {
throw new ApiError(401, "Session changed");
}
return token;
@@ -41,6 +47,10 @@ export async function logout(): Promise<void> {
await apiRequest<{ status: string }>("/auth/logout", { method: "POST" }, false);
}
+export async function logoutAll(): Promise<void> {
+ await apiRequest<{ status: string }>("/auth/logout-all", { method: "POST" }, false);
+}
+
export function campaignEventsPath(campaignId: string, ticket: string): string {
return `/ws/campaigns/${encodeURIComponent(campaignId)}/events?ticket=${encodeURIComponent(ticket)}`;
}
diff --git a/frontend/src/api/http.test.ts b/frontend/src/api/http.test.ts
index 63189da..7e3e98f 100644
--- a/frontend/src/api/http.test.ts
+++ b/frontend/src/api/http.test.ts
@@ -21,19 +21,31 @@ function deferred<T>() {
return { promise, reject, resolve };
}
-function tokenResponse(accessToken: string, refreshToken: string): Response {
+function tokenResponse(
+ accessToken: string,
+ refreshToken: string,
+ generation = 1
+): Response {
return new Response(JSON.stringify({
access_token: accessToken,
refresh_token: refreshToken,
token_type: "bearer",
expires_in: 3600,
- role: "operator"
+ role: "operator",
+ refresh_generation: generation,
+ session_coordination_key: "coordination-a"
}), { status: 200 });
}
function installSession(accessToken = "access-a", refreshToken = "refresh-a"): void {
const session = beginIdentityTransition();
- if (!installTokenPairIfCurrent(session, accessToken, refreshToken)) {
+ if (!installTokenPairIfCurrent(
+ session,
+ accessToken,
+ refreshToken,
+ "coordination-a",
+ 0
+ )) {
throw new Error("test session setup failed");
}
}
@@ -331,7 +343,13 @@ describe("HTTP auth boundary", () => {
try {
await refreshStarted.promise;
const accountB = beginIdentityTransition();
- const installed = installTokenPairIfCurrent(accountB, "access-b", "refresh-b");
+ const installed = installTokenPairIfCurrent(
+ accountB,
+ "access-b",
+ "refresh-b",
+ "coordination-b",
+ 0
+ );
expect(installed).toBe(true);
releaseRefresh.resolve();
await expect(refresh).rejects.toMatchObject({ status: 401 });
@@ -371,7 +389,13 @@ describe("HTTP auth boundary", () => {
try {
await requestStarted.promise;
const accountB = beginIdentityTransition();
- const installed = installTokenPairIfCurrent(accountB, "access-b", "refresh-b");
+ const installed = installTokenPairIfCurrent(
+ accountB,
+ "access-b",
+ "refresh-b",
+ "coordination-b",
+ 0
+ );
expect(installed).toBe(true);
releaseRequest.resolve();
diff --git a/frontend/src/api/http.ts b/frontend/src/api/http.ts
index 0ddc6c5..9fa4de5 100644
--- a/frontend/src/api/http.ts
+++ b/frontend/src/api/http.ts
@@ -3,6 +3,7 @@ import {
captureSession,
invalidateSession,
isSessionCurrent,
+ readCoordinationRecord,
replaceTokenPairIfCurrent,
type SessionSnapshot
} from "./session";
@@ -46,7 +47,11 @@ interface RefreshFlight {
let refreshFlight: RefreshFlight | null = null;
async function performRefresh(snapshot: SessionSnapshot): Promise<boolean> {
- if (!snapshot.refreshToken) {
+ if (
+ !snapshot.refreshToken
+ || !snapshot.coordinationKey
+ || snapshot.refreshGeneration === null
+ ) {
return false;
}
@@ -61,11 +66,22 @@ async function performRefresh(snapshot: SessionSnapshot): Promise<boolean> {
return false;
}
const token = (await response.json()) as TokenResponse;
- if (!token.access_token || !token.refresh_token) {
+ if (
+ !token.access_token
+ || !token.refresh_token
+ || token.session_coordination_key !== snapshot.coordinationKey
+ || token.refresh_generation !== snapshot.refreshGeneration + 1
+ ) {
invalidateSession(snapshot);
return false;
}
- return replaceTokenPairIfCurrent(snapshot, token.access_token, token.refresh_token);
+ return replaceTokenPairIfCurrent(
+ snapshot,
+ token.access_token,
+ token.refresh_token,
+ token.session_coordination_key,
+ token.refresh_generation
+ );
} catch {
invalidateSession(snapshot);
return false;
@@ -73,7 +89,12 @@ async function performRefresh(snapshot: SessionSnapshot): Promise<boolean> {
}
export function refreshAccessToken(snapshot = captureSession()): Promise<boolean> {
- if (!snapshot.refreshToken) {
+ if (
+ !snapshot.refreshToken
+ || !snapshot.coordinationKey
+ || snapshot.refreshGeneration === null
+ ) {
+ invalidateSession(snapshot);
return Promise.resolve(false);
}
if (
@@ -89,7 +110,33 @@ export function refreshAccessToken(snapshot = captureSession()): Promise<boolean
refreshToken: snapshot.refreshToken,
promise: Promise.resolve(false)
};
- flight.promise = performRefresh(snapshot).finally(() => {
+ const execute = async () => {
+ const current = captureSession();
+ if (!isSessionCurrent(snapshot) || current.refreshToken !== snapshot.refreshToken) {
+ return false;
+ }
+ const shared = readCoordinationRecord();
+ if (
+ shared === null
+ || shared.key !== snapshot.coordinationKey
+ || shared.tombstone
+ || shared.generation !== snapshot.refreshGeneration
+ ) {
+ invalidateSession(snapshot);
+ return false;
+ }
+ return performRefresh(snapshot);
+ };
+ const lockManager = navigator.locks;
+ const coordinated: Promise<boolean> = (
+ lockManager
+ ? (async () => lockManager.request(
+ `ares-refresh:${snapshot.coordinationKey}`,
+ execute
+ ))()
+ : execute()
+ );
+ flight.promise = coordinated.finally(() => {
if (refreshFlight === flight) {
refreshFlight = null;
}
diff --git a/frontend/src/api/session.ts b/frontend/src/api/session.ts
index bdb6e4e..b3aa111 100644
--- a/frontend/src/api/session.ts
+++ b/frontend/src/api/session.ts
@@ -1,14 +1,63 @@
const REFRESH_TOKEN_KEY = "ares.refreshToken";
+const COORDINATION_KEY = "ares.sessionCoordination";
+const COORDINATION_CHANNEL = "ares.session-control";
let accessToken: string | null = null;
let sessionRevision = 0;
let refreshTokenSuppressed = false;
+let coordinationKey: string | null = null;
+let refreshGeneration: number | null = null;
const invalidationListeners = new Set<() => void>();
export interface SessionSnapshot {
readonly revision: number;
readonly accessToken: string | null;
readonly refreshToken: string | null;
+ readonly coordinationKey: string | null;
+ readonly refreshGeneration: number | null;
+}
+
+interface CoordinationRecord {
+ readonly key: string;
+ readonly generation: number;
+ readonly tombstone: boolean;
+}
+
+function publishCoordination(record: CoordinationRecord): void {
+ try {
+ localStorage.setItem(COORDINATION_KEY, JSON.stringify(record));
+ } catch {
+ // In-memory state remains fail-closed when cross-tab storage is unavailable.
+ }
+ try {
+ const channel = new BroadcastChannel(COORDINATION_CHANNEL);
+ channel.postMessage(record);
+ channel.close();
+ } catch {
+ // Web Locks plus local state still protect the current tab.
+ }
+}
+
+export function readCoordinationRecord(): CoordinationRecord | null {
+ try {
+ const value = JSON.parse(localStorage.getItem(COORDINATION_KEY) ?? "null") as unknown;
+ if (
+ typeof value !== "object"
+ || value === null
+ || !("key" in value)
+ || !("generation" in value)
+ || !("tombstone" in value)
+ || typeof value.key !== "string"
+ || typeof value.generation !== "number"
+ || !Number.isSafeInteger(value.generation)
+ || typeof value.tombstone !== "boolean"
+ ) {
+ return null;
+ }
+ return value as CoordinationRecord;
+ } catch {
+ return null;
+ }
}
function persistRefreshToken(token: string | null): boolean {
@@ -43,9 +92,23 @@ function persistRefreshToken(token: string | null): boolean {
}
}
-function writeTokenPair(nextAccessToken: string | null, nextRefreshToken: string | null): boolean {
+function writeTokenPair(
+ nextAccessToken: string | null,
+ nextRefreshToken: string | null,
+ nextCoordinationKey: string | null = null,
+ nextGeneration: number | null = null
+): boolean {
if (nextRefreshToken === null) {
accessToken = null;
+ if (coordinationKey !== null && refreshGeneration !== null) {
+ publishCoordination({
+ key: coordinationKey,
+ generation: refreshGeneration,
+ tombstone: true
+ });
+ }
+ coordinationKey = null;
+ refreshGeneration = null;
persistRefreshToken(null);
return true;
}
@@ -54,6 +117,15 @@ function writeTokenPair(nextAccessToken: string | null, nextRefreshToken: string
return false;
}
accessToken = nextAccessToken;
+ coordinationKey = nextCoordinationKey;
+ refreshGeneration = nextGeneration;
+ if (coordinationKey !== null && refreshGeneration !== null) {
+ publishCoordination({
+ key: coordinationKey,
+ generation: refreshGeneration,
+ tombstone: false
+ });
+ }
return true;
}
@@ -85,7 +157,9 @@ export function captureSession(): SessionSnapshot {
return {
revision: sessionRevision,
accessToken,
- refreshToken: getRefreshToken()
+ refreshToken: getRefreshToken(),
+ coordinationKey,
+ refreshGeneration
};
}
@@ -102,18 +176,27 @@ export function beginIdentityTransition(): SessionSnapshot {
export function installTokenPairIfCurrent(
snapshot: Pick<SessionSnapshot, "revision">,
nextAccessToken: string,
- nextRefreshToken: string
+ nextRefreshToken: string,
+ nextCoordinationKey: string | null = null,
+ nextGeneration: number | null = null
): boolean {
if (!isSessionCurrent(snapshot)) {
return false;
}
- return writeTokenPair(nextAccessToken, nextRefreshToken);
+ return writeTokenPair(
+ nextAccessToken,
+ nextRefreshToken,
+ nextCoordinationKey,
+ nextGeneration
+ );
}
export function replaceTokenPairIfCurrent(
snapshot: SessionSnapshot,
nextAccessToken: string,
- nextRefreshToken: string
+ nextRefreshToken: string,
+ nextCoordinationKey: string | null = snapshot.coordinationKey,
+ nextGeneration: number | null = snapshot.refreshGeneration
): boolean {
if (
!isSessionCurrent(snapshot)
@@ -121,7 +204,12 @@ export function replaceTokenPairIfCurrent(
) {
return false;
}
- return writeTokenPair(nextAccessToken, nextRefreshToken);
+ return writeTokenPair(
+ nextAccessToken,
+ nextRefreshToken,
+ nextCoordinationKey,
+ nextGeneration
+ );
}
export function clearTokens(): void {
@@ -151,3 +239,42 @@ export function subscribeToSessionInvalidation(listener: () => void): () => void
invalidationListeners.delete(listener);
};
}
+
+function applyPeerInvalidation(value: unknown): void {
+ if (
+ typeof value !== "object"
+ || value === null
+ || !("key" in value)
+ || !("generation" in value)
+ || !("tombstone" in value)
+ || value.key !== coordinationKey
+ || typeof value.generation !== "number"
+ || !Number.isSafeInteger(value.generation)
+ || typeof value.tombstone !== "boolean"
+ || refreshGeneration === null
+ || (!value.tombstone && value.generation <= refreshGeneration)
+ ) {
+ return;
+ }
+ sessionRevision += 1;
+ accessToken = null;
+ coordinationKey = null;
+ refreshGeneration = null;
+ persistRefreshToken(null);
+ for (const listener of [...invalidationListeners]) {
+ try {
+ listener();
+ } catch {
+ // A peer invalidation must settle every remaining subscriber.
+ }
+ }
+}
+
+try {
+ const peerChannel = new BroadcastChannel(COORDINATION_CHANNEL);
+ peerChannel.onmessage = (event: MessageEvent<unknown>) => {
+ applyPeerInvalidation(event.data);
+ };
+} catch {
+ // Lack of a safe channel is handled by the refresh fail-closed path.
+}
diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts
index ce24d92..24b94d7 100644
--- a/frontend/src/api/types.ts
+++ b/frontend/src/api/types.ts
@@ -6,6 +6,8 @@ export interface TokenResponse {
token_type: string;
expires_in: number;
role: Role;
+ refresh_generation: number;
+ session_coordination_key: string;
}
export interface UserProfile {
diff --git a/frontend/src/features/auth/AuthProvider.test.tsx b/frontend/src/features/auth/AuthProvider.test.tsx
index 6305f98..84515b6 100644
--- a/frontend/src/features/auth/AuthProvider.test.tsx
+++ b/frontend/src/features/auth/AuthProvider.test.tsx
@@ -52,16 +52,35 @@ function AuthProbe() {
return <span>{currentAuth.user?.username ?? "logged-out"}</span>;
}
-function tokenResponse(accessToken: string, refreshToken: string): Response {
+function tokenResponse(
+ accessToken: string,
+ refreshToken: string,
+ generation = 0,
+ coordinationKey = "coordination-a"
+): Response {
return new Response(JSON.stringify({
access_token: accessToken,
refresh_token: refreshToken,
token_type: "bearer",
expires_in: 3600,
- role: "operator"
+ role: "operator",
+ refresh_generation: generation,
+ session_coordination_key: coordinationKey
}), { status: 200 });
}
+function installStoredSession(refreshToken = "refresh-a"): void {
+ const session = beginIdentityTransition();
+ const installed = installTokenPairIfCurrent(
+ session,
+ "stale-access",
+ refreshToken,
+ "coordination-a",
+ 0
+ );
+ requireFixed(installed, "expected authoritative stored session");
+}
+
function profileResponse(username: string, role = "operator"): Response {
return new Response(JSON.stringify({ username, role }), { status: 200 });
}
@@ -196,7 +215,7 @@ describe("AuthProvider session isolation", () => {
it("cleans account state and exits loading when startup refresh fails", async () => {
const queryClient = createQueryClient();
- setRefreshToken("refresh-a");
+ installStoredSession();
seedAccountState(queryClient);
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 401 })));
@@ -225,11 +244,11 @@ describe("AuthProvider session isolation", () => {
it("cleans account state when startup profile resolution fails", async () => {
const queryClient = createQueryClient();
- setRefreshToken("refresh-a");
+ installStoredSession();
seedAccountState(queryClient);
vi.stubGlobal("fetch", vi.fn(async (path: string) => {
if (path === "/auth/refresh") {
- return tokenResponse("access-a", "refresh-b");
+ return tokenResponse("access-a", "refresh-b", 1);
}
if (path === "/auth/me") {
return new Response(null, { status: 503 });
@@ -295,7 +314,7 @@ describe("AuthProvider session isolation", () => {
if (path === "/auth/refresh") {
refreshStarted.resolve();
await releaseRefresh.promise;
- return tokenResponse("access-late", "refresh-late");
+ return tokenResponse("access-late", "refresh-late", 1);
}
if (path === "/auth/logout") {
return new Response(JSON.stringify({ status: "ok" }), { status: 200 });
@@ -340,7 +359,7 @@ describe("AuthProvider session isolation", () => {
if (path === "/auth/token") {
const username = new URLSearchParams(String(init?.body)).get("username");
return username === "bob"
- ? tokenResponse("access-b", "refresh-b")
+ ? tokenResponse("access-b", "refresh-b", 0, "coordination-b")
: tokenResponse("access-a", "refresh-a");
}
if (path === "/auth/me") {
@@ -354,7 +373,7 @@ describe("AuthProvider session isolation", () => {
refreshStarted.resolve();
await releaseRefresh.promise;
return outcome === "success"
- ? tokenResponse("access-a-late", "refresh-a-late")
+ ? tokenResponse("access-a-late", "refresh-a-late", 1)
: new Response(null, { status: 401 });
}
return new Response(null, { status: 404 });
@@ -434,7 +453,13 @@ describe("AuthProvider session isolation", () => {
provider.unmount();
if (sessionOwner === "newer session") {
const newerSession = beginIdentityTransition();
- const installed = installTokenPairIfCurrent(newerSession, "access-b", "refresh-b");
+ const installed = installTokenPairIfCurrent(
+ newerSession,
+ "access-b",
+ "refresh-b",
+ "coordination-b",
+ 0
+ );
requireFixed(installed, "expected newer session installation");
}
releaseProfile.resolve();
@@ -511,7 +536,7 @@ describe("AuthProvider session isolation", () => {
it("shares startup refresh under StrictMode and applies one current profile", async () => {
const queryClient = createQueryClient();
- setRefreshToken("refresh-a");
+ installStoredSession();
sessionStorage.setItem(
"ares.dashboard.principal",
JSON.stringify({ username: "alice", role: "operator" })
@@ -523,7 +548,7 @@ describe("AuthProvider session isolation", () => {
vi.stubGlobal("fetch", vi.fn(async (path: string) => {
if (path === "/auth/refresh") {
refreshCalls += 1;
- return tokenResponse("access-a", "refresh-b");
+ return tokenResponse("access-a", "refresh-b", 1);
}
if (path === "/auth/me") {
profileCalls += 1;
@@ -556,7 +581,7 @@ describe("AuthProvider session isolation", () => {
&& queryClient.getMutationCache().getAll().length === 0
&& sessionStorage.getItem("ares.dashboard.modules.search") === null
);
- return tokenResponse("access-b", "refresh-b");
+ return tokenResponse("access-b", "refresh-b", 0, "coordination-b");
}
return tokenResponse("access-a", "refresh-a");
}
@@ -634,7 +659,7 @@ describe("AuthProvider session isolation", () => {
return profileResponse("alice");
}
if (path === "/auth/refresh" && runtime) {
- return tokenResponse("access-b", "refresh-b");
+ return tokenResponse("access-b", "refresh-b", 1);
}
if (path === "/runtime" && runtime) {
const authorization = new Headers(init?.headers).get("Authorization");
diff --git a/frontend/src/features/auth/AuthProvider.tsx b/frontend/src/features/auth/AuthProvider.tsx
index bfd829c..b27d32b 100644
--- a/frontend/src/features/auth/AuthProvider.tsx
+++ b/frontend/src/features/auth/AuthProvider.tsx
@@ -9,6 +9,7 @@ import {
isSessionCurrent,
login as loginRequest,
logout as logoutRequest,
+ logoutAll as logoutAllRequest,
refreshAccessToken,
subscribeToSessionInvalidation
} from "../../api/client";
@@ -149,6 +150,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
} finally {
invalidateSession(logoutSession);
}
+ },
+ logoutAll: async () => {
+ const logoutSession = captureSession();
+ try {
+ await logoutAllRequest();
+ } catch {
+ // Local invalidation is mandatory even if remote revocation is unavailable.
+ } finally {
+ invalidateSession(logoutSession);
+ }
}
}),
[loading, ownsProviderLifecycle, resetLocalSession, user]
diff --git a/frontend/src/features/auth/authContext.ts b/frontend/src/features/auth/authContext.ts
index 64e3fff..733d2d4 100644
--- a/frontend/src/features/auth/authContext.ts
+++ b/frontend/src/features/auth/authContext.ts
@@ -6,6 +6,7 @@ export interface AuthState {
loading: boolean;
login: (username: string, password: string) => Promise<void>;
logout: () => Promise<void>;
+ logoutAll: () => Promise<void>;
}
export const AuthContext = createContext<AuthState | null>(null);
diff --git a/frontend/src/features/dashboard/DashboardPages.tsx b/frontend/src/features/dashboard/DashboardPages.tsx
index d9f43c6..8d0ef95 100644
--- a/frontend/src/features/dashboard/DashboardPages.tsx
+++ b/frontend/src/features/dashboard/DashboardPages.tsx
@@ -330,7 +330,7 @@ function formatRole(role?: string): string {
}
export function DashboardShell({ children }: { children: ReactNode }) {
- const { user, loading, logout } = useAuth();
+ const { user, loading, logout, logoutAll } = useAuth();
const navigate = useNavigate();
const writeDashboardSession = useDashboardSessionWriter();
const [selectedCampaignId, setSelectedCampaignId] = useSessionState("ares.dashboard.selectedCampaignId", "");
@@ -712,6 +712,9 @@ export function DashboardShell({ children }: { children: ReactNode }) {
<button className="btn btn-topbar" onClick={() => void logout()}>
<LogOut size={16} /> Logout
</button>
+ <button className="btn btn-topbar" onClick={() => void logoutAll()}>
+ <LogOut size={16} /> Logout all devices
+ </button>
</div>
</header>
<div className="content-shell">{children}</div>
diff --git a/migrations/versions/0009_refresh_token_families.py b/migrations/versions/0009_refresh_token_families.py
new file mode 100644
index 0000000..4f5d322
--- /dev/null
+++ b/migrations/versions/0009_refresh_token_families.py
@@ -0,0 +1,921 @@
+"""Add authoritative refresh-token families and bearer session authority.
+
+Revision ID: 0009
+Revises: 0008
+"""
+from __future__ import annotations
+
+import base64
+import hashlib
+import math
+import re
+from datetime import datetime, timedelta, timezone
+from importlib import import_module
+from typing import Any
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "0009"
+down_revision = "0008"
+branch_labels = None
+depends_on = None
+
+_HASH_RE = re.compile(r"[0-9a-f]{64}\Z")
+_ROLLOUT_REASONS = frozenset(
+ {
+ "replay",
+ "logout_current",
+ "logout_all",
+ "password_change",
+ "password_reset",
+ "role_change",
+ "user_status_change",
+ "rollout_reset",
+ "expired",
+ "operator_revoke",
+ }
+)
+
+_PREVIOUS = import_module("migrations.versions.0008_reconcile_schema_parity")
+classify_unversioned_catalog = _PREVIOUS.classify_unversioned_catalog
+_require_sqlite_alembic_version_relation = (
+ _PREVIOUS._require_sqlite_alembic_version_relation
+)
+_pg_validate_alembic_version_relation = (
+ _PREVIOUS._pg_validate_alembic_version_relation
+)
+
+_FAMILY_COLUMNS = (
+ "id",
+ "user_id",
+ "auth_epoch",
+ "state",
+ "created_at",
+ "absolute_expires_at",
+ "revoked_at",
+ "revoke_reason",
+ "retain_until",
+)
+_REFRESH_COLUMNS = (
+ "id",
+ "user_id",
+ "is_revoked",
+ "expires_at",
+ "created_at",
+ "used_at",
+ "family_id",
+ "parent_id",
+ "generation",
+ "state",
+ "revoked_at",
+)
+_TICKET_COLUMNS = (
+ "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",
+ "bearer_family_id",
+ "bearer_auth_epoch",
+)
+
+
+def _fail() -> None:
+ raise RuntimeError("revision-0009 preflight failed")
+
+
+def _dialect() -> str:
+ name = op.get_bind().dialect.name
+ if name not in {"sqlite", "postgresql"}:
+ _fail()
+ return name
+
+
+def _family_id(domain: bytes, value: str) -> str:
+ digest = hashlib.sha256(domain + value.encode("utf-8")).digest()
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+
+
+def _parse_time(value: object) -> datetime:
+ if isinstance(value, datetime):
+ parsed = value
+ elif isinstance(value, str) and value and value == value.strip():
+ candidate = value[:-1] + "+00:00" if value.endswith("Z") else value
+ try:
+ parsed = datetime.fromisoformat(candidate)
+ except ValueError:
+ _fail()
+ else:
+ _fail()
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ parsed = parsed.astimezone(timezone.utc)
+ if not math.isfinite(parsed.timestamp()):
+ _fail()
+ return parsed
+
+
+def _sqlite_time(value: datetime) -> str:
+ value = value.astimezone(timezone.utc)
+ return value.strftime("%Y-%m-%dT%H:%M:%S.") + f"{value.microsecond // 1000:03d}Z"
+
+
+def _db_time(value: datetime, dialect: str) -> datetime | str:
+ return value if dialect == "postgresql" else _sqlite_time(value)
+
+
+def _preflight() -> tuple[list[dict[str, Any]], list[dict[str, Any]], str]:
+ bind = op.get_bind()
+ dialect = _dialect()
+ inspector = sa.inspect(bind)
+ tables = set(inspector.get_table_names())
+ required = {"users", "refresh_tokens", "websocket_tickets", "alembic_version"}
+ if not required.issubset(tables) or "refresh_token_families" in tables:
+ _fail()
+
+ user_ids = {
+ str(row[0])
+ for row in bind.execute(sa.text("SELECT id FROM users")).fetchall()
+ if isinstance(row[0], str) and row[0]
+ }
+ refresh_rows: list[dict[str, Any]] = []
+ for row in bind.execute(
+ sa.text(
+ "SELECT id,user_id,is_revoked,expires_at,created_at,used_at "
+ "FROM refresh_tokens ORDER BY id"
+ )
+ ).mappings():
+ item = dict(row)
+ token_hash = item.get("id")
+ user_id = item.get("user_id")
+ revoked = item.get("is_revoked")
+ if (
+ not isinstance(token_hash, str)
+ or _HASH_RE.fullmatch(token_hash) is None
+ or not isinstance(user_id, str)
+ or user_id not in user_ids
+ or isinstance(revoked, bool)
+ or revoked not in {0, 1}
+ ):
+ _fail()
+ created = _parse_time(item.get("created_at"))
+ expires = _parse_time(item.get("expires_at"))
+ if expires <= created:
+ _fail()
+ used_raw = item.get("used_at")
+ used = _parse_time(used_raw) if used_raw is not None else None
+ if used is not None and used < created:
+ _fail()
+ item.update(created_at=created, expires_at=expires, used_at=used)
+ refresh_rows.append(item)
+
+ bearer_rows: list[dict[str, Any]] = []
+ for row in bind.execute(
+ sa.text(
+ "SELECT ticket_hash,user_id,created_at,expires_at,bearer_expires_at "
+ "FROM websocket_tickets WHERE credential_kind='bearer' "
+ "ORDER BY ticket_hash"
+ )
+ ).mappings():
+ item = dict(row)
+ if (
+ not isinstance(item.get("ticket_hash"), str)
+ or _HASH_RE.fullmatch(item["ticket_hash"]) is None
+ or not isinstance(item.get("user_id"), str)
+ or item["user_id"] not in user_ids
+ ):
+ _fail()
+ created = _parse_time(item.get("created_at"))
+ expires = _parse_time(item.get("expires_at"))
+ bearer_expires = _parse_time(item.get("bearer_expires_at"))
+ if expires <= created:
+ _fail()
+ item.update(
+ created_at=created,
+ expires_at=expires,
+ bearer_expires_at=bearer_expires,
+ )
+ bearer_rows.append(item)
+ return refresh_rows, bearer_rows, dialect
+
+
+def _timestamp_type(dialect: str) -> sa.types.TypeEngine[Any]:
+ return sa.DateTime(timezone=True) if dialect == "postgresql" else sa.Text()
+
+
+def _family_checks(dialect: str) -> tuple[sa.CheckConstraint, ...]:
+ identifier = (
+ "id ~ '^[A-Za-z0-9_-]{43}$'"
+ if dialect == "postgresql"
+ else "length(id)=43 AND id NOT GLOB '*[^A-Za-z0-9_-]*'"
+ )
+ checks: list[sa.CheckConstraint] = [
+ sa.CheckConstraint(identifier, name="ck_refresh_family_id"),
+ sa.CheckConstraint("auth_epoch >= 1", name="ck_refresh_family_epoch"),
+ sa.CheckConstraint(
+ "state IN ('active','revoked')", name="ck_refresh_family_state"
+ ),
+ sa.CheckConstraint(
+ "(state='active' AND revoked_at IS NULL AND revoke_reason IS NULL) OR "
+ "(state='revoked' AND revoked_at IS NOT NULL AND revoke_reason IS NOT NULL)",
+ name="ck_refresh_family_revocation_shape",
+ ),
+ sa.CheckConstraint(
+ "revoke_reason IS NULL OR revoke_reason IN ("
+ + ",".join(f"'{value}'" for value in sorted(_ROLLOUT_REASONS))
+ + ")",
+ name="ck_refresh_family_reason",
+ ),
+ ]
+ if dialect == "postgresql":
+ checks.extend(
+ [
+ sa.CheckConstraint(
+ "isfinite(created_at)", name="ck_refresh_family_created_finite"
+ ),
+ sa.CheckConstraint(
+ "isfinite(absolute_expires_at)",
+ name="ck_refresh_family_expires_finite",
+ ),
+ sa.CheckConstraint(
+ "revoked_at IS NULL OR isfinite(revoked_at)",
+ name="ck_refresh_family_revoked_finite",
+ ),
+ sa.CheckConstraint(
+ "isfinite(retain_until)", name="ck_refresh_family_retain_finite"
+ ),
+ ]
+ )
+ else:
+ for column in (
+ "created_at",
+ "absolute_expires_at",
+ "retain_until",
+ ):
+ checks.append(
+ sa.CheckConstraint(
+ f"strftime('%Y-%m-%dT%H:%M:%fZ',{column}) IS NOT NULL AND "
+ f"strftime('%Y-%m-%dT%H:%M:%fZ',{column})={column}",
+ name=f"ck_refresh_family_{column}_utc",
+ )
+ )
+ checks.append(
+ sa.CheckConstraint(
+ "revoked_at IS NULL OR "
+ "(strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at) IS NOT NULL AND "
+ "strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at)=revoked_at)",
+ name="ck_refresh_family_revoked_at_utc",
+ )
+ )
+ checks.extend(
+ [
+ sa.CheckConstraint(
+ "absolute_expires_at > created_at",
+ name="ck_refresh_family_expiry_order",
+ ),
+ sa.CheckConstraint(
+ "retain_until > absolute_expires_at AND "
+ "(revoked_at IS NULL OR retain_until > revoked_at)",
+ name="ck_refresh_family_retention_order",
+ ),
+ ]
+ )
+ return tuple(checks)
+
+
+def _create_family_table(dialect: str) -> None:
+ timestamp = _timestamp_type(dialect)
+ epoch_type: sa.types.TypeEngine[Any] = (
+ sa.BigInteger() if dialect == "postgresql" else sa.Integer()
+ )
+ op.create_table(
+ "refresh_token_families",
+ sa.Column("id", sa.Text(), primary_key=True, nullable=False),
+ sa.Column(
+ "user_id",
+ sa.Text(),
+ sa.ForeignKey(
+ "users.id", name="fk_refresh_family_user", ondelete="CASCADE"
+ ),
+ nullable=False,
+ ),
+ sa.Column("auth_epoch", epoch_type, nullable=False),
+ sa.Column("state", sa.Text(), nullable=False),
+ sa.Column("created_at", timestamp, nullable=False),
+ sa.Column("absolute_expires_at", timestamp, nullable=False),
+ sa.Column("revoked_at", timestamp),
+ sa.Column("revoke_reason", sa.Text()),
+ sa.Column("retain_until", timestamp, nullable=False),
+ sa.UniqueConstraint("id", "user_id", name="uq_refresh_family_owner"),
+ *_family_checks(dialect),
+ )
+ op.create_index(
+ "idx_refresh_family_user_state_exp",
+ "refresh_token_families",
+ ["user_id", "state", "absolute_expires_at"],
+ )
+ op.create_index(
+ "idx_refresh_family_retain",
+ "refresh_token_families",
+ ["retain_until"],
+ )
+
+
+def _add_user_epoch(dialect: str) -> None:
+ if dialect == "sqlite":
+ op.execute(
+ "ALTER TABLE users ADD COLUMN auth_epoch INTEGER NOT NULL "
+ "DEFAULT 1 CONSTRAINT ck_users_auth_epoch "
+ "CHECK (auth_epoch >= 1)"
+ )
+ return
+ epoch_type: sa.types.TypeEngine[Any] = (
+ sa.BigInteger()
+ )
+ with op.batch_alter_table("users") as batch:
+ batch.add_column(
+ sa.Column("auth_epoch", epoch_type, nullable=False, server_default="1")
+ )
+ batch.create_check_constraint("ck_users_auth_epoch", "auth_epoch >= 1")
+
+
+def _insert_family(
+ *,
+ family_id: str,
+ user_id: str,
+ created: datetime,
+ expires: datetime,
+ revoked: datetime,
+ dialect: str,
+) -> None:
+ retain = max(expires, revoked) + timedelta(days=30)
+ op.get_bind().execute(
+ sa.text(
+ "INSERT INTO refresh_token_families("
+ "id,user_id,auth_epoch,state,created_at,absolute_expires_at,"
+ "revoked_at,revoke_reason,retain_until) "
+ "VALUES(:id,:user_id,1,'revoked',:created,:expires,:revoked,"
+ "'rollout_reset',:retain)"
+ ),
+ {
+ "id": family_id,
+ "user_id": user_id,
+ "created": _db_time(created, dialect),
+ "expires": _db_time(expires, dialect),
+ "revoked": _db_time(revoked, dialect),
+ "retain": _db_time(retain, dialect),
+ },
+ )
+
+
+def _upgrade_refresh_tokens(
+ rows: list[dict[str, Any]], dialect: str, migration_time: datetime
+) -> None:
+ epoch_type: sa.types.TypeEngine[Any] = (
+ sa.BigInteger() if dialect == "postgresql" else sa.Integer()
+ )
+ timestamp = _timestamp_type(dialect)
+ with op.batch_alter_table("refresh_tokens") as batch:
+ batch.add_column(sa.Column("family_id", sa.Text()))
+ batch.add_column(sa.Column("parent_id", sa.Text()))
+ batch.add_column(sa.Column("generation", epoch_type))
+ batch.add_column(sa.Column("state", sa.Text()))
+ batch.add_column(sa.Column("revoked_at", timestamp))
+
+ bind = op.get_bind()
+ for row in rows:
+ family_id = _family_id(b"ARES-0009-LEGACY-REFRESH-V1\0", row["id"])
+ _insert_family(
+ family_id=family_id,
+ user_id=row["user_id"],
+ created=row["created_at"],
+ expires=row["expires_at"],
+ revoked=migration_time,
+ dialect=dialect,
+ )
+ state = "consumed" if row["used_at"] is not None else "retired"
+ bind.execute(
+ sa.text(
+ "UPDATE refresh_tokens SET family_id=:family,generation=0,"
+ "state=:state,is_revoked=1,created_at=:created,expires_at=:expires,"
+ "used_at=:used,revoked_at=:revoked WHERE id=:token_hash"
+ ),
+ {
+ "family": family_id,
+ "state": state,
+ "created": _db_time(row["created_at"], dialect),
+ "expires": _db_time(row["expires_at"], dialect),
+ "used": (
+ _db_time(row["used_at"], dialect)
+ if row["used_at"] is not None
+ else None
+ ),
+ "revoked": (
+ None if state == "consumed" else _db_time(migration_time, dialect)
+ ),
+ "token_hash": row["id"],
+ },
+ )
+
+ hash_check = (
+ "id ~ '^[0-9a-f]{64}$'"
+ if dialect == "postgresql"
+ else "length(id)=64 AND id NOT GLOB '*[^0-9a-f]*'"
+ )
+ checks: list[tuple[str, str]] = [
+ ("ck_refresh_token_hash", hash_check),
+ ("ck_refresh_token_generation", "generation >= 0"),
+ (
+ "ck_refresh_token_parent_shape",
+ "(generation=0 AND parent_id IS NULL) OR "
+ "(generation>0 AND parent_id IS NOT NULL)",
+ ),
+ (
+ "ck_refresh_token_state",
+ "state IN ('active','consumed','retired')",
+ ),
+ (
+ "ck_refresh_token_state_shape",
+ "(state='active' AND is_revoked=0 AND used_at IS NULL AND revoked_at IS NULL) OR "
+ "(state='consumed' AND is_revoked=1 AND used_at IS NOT NULL AND revoked_at IS NULL) OR "
+ "(state='retired' AND is_revoked=1 AND revoked_at IS NOT NULL)",
+ ),
+ ("ck_refresh_token_expiry_order", "expires_at > created_at"),
+ ]
+ if dialect == "postgresql":
+ checks.append(
+ (
+ "ck_refresh_token_revoked_finite",
+ "revoked_at IS NULL OR isfinite(revoked_at)",
+ )
+ )
+ else:
+ checks.extend(
+ [
+ (
+ "ck_refresh_token_created_utc",
+ "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_refresh_token_expires_utc",
+ "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_refresh_token_used_utc",
+ "used_at IS NULL OR "
+ "(strftime('%Y-%m-%dT%H:%M:%fZ',used_at) IS NOT NULL AND "
+ "strftime('%Y-%m-%dT%H:%M:%fZ',used_at)=used_at)",
+ ),
+ (
+ "ck_refresh_token_revoked_utc",
+ "revoked_at IS NULL OR "
+ "(strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at) IS NOT NULL AND "
+ "strftime('%Y-%m-%dT%H:%M:%fZ',revoked_at)=revoked_at)",
+ ),
+ ]
+ )
+
+ if dialect == "sqlite":
+ op.create_index(
+ "uq_refresh_token_family_hash_bootstrap",
+ "refresh_tokens",
+ ["family_id", "id"],
+ unique=True,
+ )
+
+ with op.batch_alter_table(
+ "refresh_tokens", recreate="always" if dialect == "sqlite" else "auto"
+ ) as batch:
+ batch.alter_column("family_id", existing_type=sa.Text(), nullable=False)
+ batch.alter_column("generation", existing_type=epoch_type, nullable=False)
+ batch.alter_column("state", existing_type=sa.Text(), nullable=False)
+ batch.create_unique_constraint(
+ "uq_refresh_token_family_hash", ["family_id", "id"]
+ )
+ batch.create_unique_constraint(
+ "uq_refresh_token_family_generation", ["family_id", "generation"]
+ )
+ batch.create_unique_constraint("uq_refresh_token_parent", ["parent_id"])
+ batch.create_foreign_key(
+ "fk_refresh_token_family_owner",
+ "refresh_token_families",
+ ["family_id", "user_id"],
+ ["id", "user_id"],
+ ondelete="CASCADE",
+ )
+ batch.create_foreign_key(
+ "fk_refresh_token_parent",
+ "refresh_tokens",
+ ["family_id", "parent_id"],
+ ["family_id", "id"],
+ ondelete="CASCADE",
+ deferrable=True,
+ initially="DEFERRED",
+ )
+ for name, expression in checks:
+ batch.create_check_constraint(name, expression)
+
+ if dialect == "sqlite":
+ op.drop_index(
+ "uq_refresh_token_family_hash_bootstrap",
+ table_name="refresh_tokens",
+ )
+
+ active_predicate = sa.text("state='active'")
+ op.create_index(
+ "uq_refresh_token_one_active",
+ "refresh_tokens",
+ ["family_id"],
+ unique=True,
+ sqlite_where=active_predicate,
+ postgresql_where=active_predicate,
+ )
+ op.create_index(
+ "idx_refresh_family_generation",
+ "refresh_tokens",
+ ["family_id", "generation"],
+ )
+
+
+_SQLITE_WEBSOCKET_TICKET_TABLE = """
+CREATE TABLE 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,
+ bearer_family_id TEXT,
+ bearer_auth_epoch INTEGER,
+ 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 bearer_family_id IS NOT NULL
+ AND length(bearer_family_id)=43
+ AND bearer_family_id NOT GLOB '*[^A-Za-z0-9_-]*'
+ AND bearer_auth_epoch IS NOT NULL
+ AND typeof(bearer_auth_epoch)='integer'
+ AND bearer_auth_epoch >= 1
+ 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 bearer_family_id IS NULL
+ AND bearer_auth_epoch 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'
+ )
+ ),
+ CONSTRAINT fk_ws_ticket_bearer_family
+ FOREIGN KEY (bearer_family_id,user_id)
+ REFERENCES refresh_token_families(id,user_id) ON DELETE CASCADE
+)
+"""
+
+_WEBSOCKET_TICKET_COLUMNS = (
+ "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",
+ "bearer_family_id",
+ "bearer_auth_epoch",
+)
+_WEBSOCKET_TICKET_COLUMN_LIST_SQL = ",".join(_WEBSOCKET_TICKET_COLUMNS)
+_WEBSOCKET_TICKET_COPY_TO_TEMP_SQL = ( # noqa: S608 - fixed identifiers
+ "CREATE TEMP TABLE ares_0009_websocket_ticket_rows AS SELECT " # noqa: S608
+ + _WEBSOCKET_TICKET_COLUMN_LIST_SQL
+ + " FROM websocket_tickets"
+)
+_WEBSOCKET_TICKET_COPY_FROM_TEMP_SQL = ( # noqa: S608 - fixed identifiers
+ "INSERT INTO websocket_tickets(" # noqa: S608
+ + _WEBSOCKET_TICKET_COLUMN_LIST_SQL
+ + ") SELECT "
+ + _WEBSOCKET_TICKET_COLUMN_LIST_SQL
+ + " FROM ares_0009_websocket_ticket_rows"
+)
+
+
+def _rebuild_sqlite_websocket_tickets() -> None:
+ bind = op.get_bind()
+ bind.execute(sa.text(_WEBSOCKET_TICKET_COPY_TO_TEMP_SQL))
+ bind.execute(sa.text("DROP TABLE websocket_tickets"))
+ bind.execute(sa.text(_SQLITE_WEBSOCKET_TICKET_TABLE))
+ bind.execute(sa.text(_WEBSOCKET_TICKET_COPY_FROM_TEMP_SQL))
+ for name, column in (
+ ("idx_ws_tickets_expires", "expires_at"),
+ ("idx_ws_tickets_user", "user_id"),
+ ("idx_ws_tickets_campaign", "campaign_id"),
+ ("idx_ws_tickets_api_key", "api_key_id"),
+ ("idx_ws_tickets_bearer_family", "bearer_family_id"),
+ ):
+ bind.execute(
+ sa.text(f"CREATE INDEX {name} ON websocket_tickets({column})")
+ )
+ bind.execute(sa.text("DROP TABLE ares_0009_websocket_ticket_rows"))
+
+
+def _upgrade_websocket_tickets(
+ rows: list[dict[str, Any]], dialect: str, migration_time: datetime
+) -> None:
+ epoch_type: sa.types.TypeEngine[Any] = (
+ sa.BigInteger() if dialect == "postgresql" else sa.Integer()
+ )
+ with op.batch_alter_table("websocket_tickets") as batch:
+ batch.add_column(sa.Column("bearer_family_id", sa.Text()))
+ batch.add_column(sa.Column("bearer_auth_epoch", epoch_type))
+
+ bind = op.get_bind()
+ grouped: dict[str, list[dict[str, Any]]] = {}
+ for row in rows:
+ grouped.setdefault(row["user_id"], []).append(row)
+ for user_id, user_rows in grouped.items():
+ family_id = _family_id(b"ARES-0009-LEGACY-WS-V1\0", user_id)
+ created = min(row["created_at"] for row in user_rows)
+ expires = max(
+ max(row["expires_at"], row["bearer_expires_at"])
+ for row in user_rows
+ )
+ if expires <= created:
+ expires = created + timedelta(seconds=1)
+ _insert_family(
+ family_id=family_id,
+ user_id=user_id,
+ created=created,
+ expires=expires,
+ revoked=migration_time,
+ dialect=dialect,
+ )
+ bind.execute(
+ sa.text(
+ "UPDATE websocket_tickets SET bearer_family_id=:family,"
+ "bearer_auth_epoch=1 WHERE credential_kind='bearer' AND user_id=:user_id"
+ ),
+ {"family": family_id, "user_id": user_id},
+ )
+
+ trim_function = "btrim" if dialect == "postgresql" else "trim"
+ epoch_type_guard = (
+ "" if dialect == "postgresql" else "AND typeof(bearer_auth_epoch)='integer'"
+ )
+ bearer_time_guard = (
+ ""
+ if dialect == "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
+ """
+ )
+ 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_time_guard}
+ AND bearer_family_id IS NOT NULL
+ AND bearer_auth_epoch IS NOT NULL
+ {epoch_type_guard}
+ AND bearer_auth_epoch >= 1
+ 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 bearer_family_id IS NULL
+ AND bearer_auth_epoch 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'
+ )
+ """
+ if dialect == "sqlite":
+ _rebuild_sqlite_websocket_tickets()
+ return
+ with op.batch_alter_table(
+ "websocket_tickets", recreate="always" if dialect == "sqlite" else "auto"
+ ) as batch:
+ batch.drop_constraint("ck_ws_ticket_source_shape", type_="check")
+ batch.create_check_constraint("ck_ws_ticket_source_shape", source_shape)
+ batch.create_foreign_key(
+ "fk_ws_ticket_bearer_family",
+ "refresh_token_families",
+ ["bearer_family_id", "user_id"],
+ ["id", "user_id"],
+ ondelete="CASCADE",
+ )
+ op.create_index(
+ "idx_ws_tickets_bearer_family",
+ "websocket_tickets",
+ ["bearer_family_id"],
+ )
+
+
+def _column_names(inspector: sa.Inspector, table: str) -> tuple[str, ...]:
+ return tuple(str(item["name"]) for item in inspector.get_columns(table))
+
+
+def verify_managed_catalog(bind: Any) -> None:
+ """Verify the revision-0009 additions on the canonical revision-0008 set."""
+ dialect = bind.dialect.name
+ if dialect not in {"sqlite", "postgresql"}:
+ _fail()
+ if dialect == "sqlite":
+ _require_sqlite_alembic_version_relation(bind, "0009")
+ expected_tables = set(_PREVIOUS._SQLITE_COLUMNS) | {
+ "alembic_version",
+ "refresh_token_families",
+ }
+ else:
+ _pg_validate_alembic_version_relation(bind, "0009")
+ expected_tables = set(
+ _PREVIOUS._PG_REQUIRED_TABLES | _PREVIOUS._PG_OPTIONAL_TABLES
+ ) | {"alembic_version", "refresh_token_families"}
+ relation_rows = bind.execute(
+ sa.text(
+ """
+ SELECT relation.relname, relation.relkind::text
+ FROM pg_class AS relation
+ JOIN pg_namespace AS namespace
+ ON namespace.oid=relation.relnamespace
+ WHERE namespace.nspname=current_schema()
+ AND relation.relname=ANY(:names)
+ """
+ ),
+ {
+ "names": sorted(
+ expected_tables
+ | {"audit_log_id_seq", "rate_limit_events_id_seq"}
+ )
+ },
+ ).fetchall()
+ expected_relations = {(name, "r") for name in expected_tables}
+ expected_relations.update(
+ {
+ ("audit_log_id_seq", "S"),
+ ("rate_limit_events_id_seq", "S"),
+ }
+ )
+ if {
+ (str(row[0]), str(row[1])) for row in relation_rows
+ } != expected_relations:
+ _fail()
+ inspector = sa.inspect(bind)
+ actual_tables = set(inspector.get_table_names())
+ if (
+ dialect == "sqlite" and actual_tables != expected_tables
+ ) or (
+ dialect == "postgresql"
+ and not expected_tables.issubset(actual_tables)
+ ):
+ _fail()
+ if _column_names(inspector, "refresh_token_families") != _FAMILY_COLUMNS:
+ _fail()
+ if _column_names(inspector, "refresh_tokens") != _REFRESH_COLUMNS:
+ _fail()
+ if _column_names(inspector, "websocket_tickets") != _TICKET_COLUMNS:
+ _fail()
+ user_columns = _column_names(inspector, "users")
+ if user_columns[-1:] != ("auth_epoch",) or user_columns.count(
+ "auth_epoch"
+ ) != 1:
+ _fail()
+ family_indexes = {
+ str(item["name"]): (
+ tuple(str(value) for value in item["column_names"]),
+ bool(item["unique"]),
+ )
+ for item in inspector.get_indexes("refresh_token_families")
+ if item.get("duplicates_constraint") is None
+ }
+ required_family_indexes = {
+ "idx_refresh_family_user_state_exp": (
+ ("user_id", "state", "absolute_expires_at"),
+ False,
+ ),
+ "idx_refresh_family_retain": (("retain_until",), False),
+ }
+ if family_indexes != required_family_indexes:
+ _fail()
+ refresh_indexes = {
+ str(item["name"]): tuple(
+ str(value) for value in item["column_names"]
+ )
+ for item in inspector.get_indexes("refresh_tokens")
+ }
+ if refresh_indexes.get("uq_refresh_token_one_active") != ("family_id",):
+ _fail()
+ if refresh_indexes.get("idx_refresh_family_generation") != (
+ "family_id",
+ "generation",
+ ):
+ _fail()
+ ticket_indexes = {
+ str(item["name"]): tuple(
+ str(value) for value in item["column_names"]
+ )
+ for item in inspector.get_indexes("websocket_tickets")
+ }
+ if ticket_indexes.get("idx_ws_tickets_bearer_family") != (
+ "bearer_family_id",
+ ):
+ _fail()
+
+
+def upgrade() -> None:
+ refresh_rows, bearer_rows, dialect = _preflight()
+ migration_time = datetime.now(timezone.utc)
+ _add_user_epoch(dialect)
+ _create_family_table(dialect)
+ _upgrade_refresh_tokens(refresh_rows, dialect, migration_time)
+ _upgrade_websocket_tickets(bearer_rows, dialect, migration_time)
+
+
+def downgrade() -> None:
+ raise RuntimeError("revision-0009 downgrade is not supported")
diff --git a/tests/integration/test_postgres_auth_token_lifecycle.py b/tests/integration/test_postgres_auth_token_lifecycle.py
index 960073a..13850bc 100644
--- a/tests/integration/test_postgres_auth_token_lifecycle.py
+++ b/tests/integration/test_postgres_auth_token_lifecycle.py
@@ -22,7 +22,6 @@ from ares.db import postgres as postgres_module
from ares.db.postgres import (
PostgresDatabase,
_acquire_refresh_token_user_lock,
- _refresh_token_user_lock_key,
)
_POSTGRES_ENV = (
@@ -40,6 +39,26 @@ class _PostgresHarness:
dsn: str
+async def _initialize_managed_schema(dsn: str) -> None:
+ from alembic import command
+ from alembic.config import Config
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ engine = create_async_engine(dsn.replace("postgresql://", "postgresql+asyncpg://", 1))
+
+ def upgrade(connection: Any) -> None:
+ config = Config()
+ config.set_main_option("script_location", "migrations")
+ config.attributes["connection"] = connection
+ command.upgrade(config, "head")
+
+ try:
+ async with engine.connect() as connection:
+ await connection.run_sync(upgrade)
+ finally:
+ await engine.dispose()
+
+
def _postgres_test_config() -> dict[str, str | int]:
values = {name: os.environ.get(name) for name in _POSTGRES_ENV}
configured = [name for name, value in values.items() if value]
@@ -147,6 +166,10 @@ async def _postgres_harness() -> AsyncIterator[_PostgresHarness]:
raise _sanitized_setup_failure("database-create", exc) from None
dsn = _runtime_dsn(config, test_database)
+ try:
+ await _initialize_managed_schema(dsn)
+ except Exception as exc:
+ raise _sanitized_setup_failure("alembic-upgrade", exc) from None
database = PostgresDatabase(dsn, pool_min=1, pool_max=12)
try:
await database.connect()
@@ -453,7 +476,7 @@ async def _wait_for_blocked_backend_sessions(
while time.monotonic() < deadline:
if any(operation.done() for operation in operations):
pytest.fail(
- "concurrent rotation bypassed the held advisory lock",
+ "concurrent rotation bypassed the held family row lock",
pytrace=False,
)
waiter_count = int(
@@ -461,18 +484,6 @@ async def _wait_for_blocked_backend_sessions(
"""
SELECT COUNT(DISTINCT activity.pid)
FROM pg_stat_activity AS activity
- JOIN pg_locks AS waiting
- ON waiting.pid=activity.pid
- AND waiting.locktype='advisory'
- AND waiting.granted=false
- JOIN pg_locks AS holding
- ON holding.pid=$1::INTEGER
- AND holding.locktype='advisory'
- AND holding.granted=true
- AND holding.classid=waiting.classid
- AND holding.objid=waiting.objid
- AND holding.objsubid=waiting.objsubid
- AND holding.database IS NOT DISTINCT FROM waiting.database
WHERE activity.datname=current_database()
AND $1::INTEGER = ANY(pg_blocking_pids(activity.pid))
""",
@@ -482,14 +493,14 @@ async def _wait_for_blocked_backend_sessions(
)
if waiter_count >= minimum_waiters:
return
- await asyncio.sleep(0.01)
+ await asyncio.sleep(0)
except TimeoutError:
pytest.fail(
- "distinct PostgreSQL backend sessions did not overlap on the advisory lock",
+ "distinct PostgreSQL sessions did not overlap on the family row lock",
pytrace=False,
)
pytest.fail(
- "distinct PostgreSQL backend sessions did not overlap on the advisory lock",
+ "distinct PostgreSQL sessions did not overlap on the family row lock",
pytrace=False,
)
@@ -840,12 +851,22 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
"SELECT username FROM users WHERE id=$1",
user_id,
)
+ async with connection.transaction():
+ family_id, _refresh_token = (
+ await database._insert_initial_family_token(
+ connection,
+ user_id=user_id,
+ auth_epoch=1,
+ )
+ )
identity_before = await connection.fetchrow(
"SELECT xmin::text AS version, last_login FROM users WHERE id=$1",
user_id,
)
- active = await database.resolve_access_token_principal(subject, jti)
+ active = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
async with database._pool.acquire() as connection:
identity_after = await connection.fetchrow(
"SELECT xmin::text AS version, last_login FROM users WHERE id=$1",
@@ -868,7 +889,9 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
"UPDATE users SET is_active=0 WHERE id=$1",
user_id,
)
- inactive = await database.resolve_access_token_principal(subject, jti)
+ inactive = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
_require_fixed(
inactive is None,
"expected inactive PostgreSQL bearer principal to be rejected",
@@ -880,7 +903,9 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
"reporter",
user_id,
)
- demoted = await database.resolve_access_token_principal(subject, jti)
+ demoted = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
_require_fixed(
demoted is not None and demoted.get("role") == "reporter",
"expected PostgreSQL principal lookup to return the committed demoted role",
@@ -892,7 +917,9 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
"team_lead",
user_id,
)
- promoted = await database.resolve_access_token_principal(subject, jti)
+ promoted = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
_require_fixed(
promoted is not None and promoted.get("role") == "team_lead",
"expected PostgreSQL principal lookup to return the committed promoted role",
@@ -906,7 +933,7 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
)
signing_key = "postgres-principal-test-signing-key"
token = create_access_token(
- {"sub": subject, "role": "team_lead"},
+ {"sub": subject, "sid": family_id, "ver": 1},
signing_key,
)
invalid_role = await resolve_bearer_principal(
@@ -932,7 +959,9 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
jti,
user_id,
)
- revoked = await database.resolve_access_token_principal(subject, jti)
+ revoked = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
_require_fixed(
revoked is None,
"expected revoked PostgreSQL bearer principal to be rejected",
@@ -947,13 +976,17 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
"UPDATE users SET is_active=0 WHERE id=$1",
user_id,
)
- suspended = await database.resolve_access_token_principal(subject, jti)
+ suspended = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
async with database._pool.acquire() as connection:
await connection.execute(
"UPDATE users SET is_active=1 WHERE id=$1",
user_id,
)
- reactivated = await database.resolve_access_token_principal(subject, jti)
+ reactivated = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
_require_fixed(
suspended is None and reactivated is not None,
"expected temporary PostgreSQL suspension to be reversible",
@@ -961,7 +994,9 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
async with database._pool.acquire() as connection:
await connection.execute("DELETE FROM users WHERE id=$1", user_id)
- deleted = await database.resolve_access_token_principal(subject, jti)
+ deleted = await database.resolve_access_token_principal(
+ subject, jti, family_id, 1
+ )
_require_fixed(
deleted is None,
"expected a deleted PostgreSQL bearer principal to be rejected",
@@ -974,6 +1009,8 @@ async def test_postgres_authoritative_bearer_principal_contract() -> None:
await closed.resolve_access_token_principal(
"closed-principal",
"closed-principal-jti",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ 1,
)
@@ -988,13 +1025,15 @@ async def test_postgres_refresh_expiry_contract() -> None:
async with database._pool.acquire() as connection:
await connection.execute(
- "UPDATE refresh_tokens SET expires_at=now() WHERE id=$1",
+ "UPDATE refresh_tokens SET created_at=now()-interval '1 hour', "
+ "expires_at=now() WHERE id=$1",
_token_hash(exact_raw),
)
await connection.execute(
"""
UPDATE refresh_tokens
- SET expires_at=now() - interval '1 second'
+ SET created_at=now() - interval '1 hour',
+ expires_at=now() - interval '1 second'
WHERE id=$1
""",
_token_hash(past_raw),
@@ -1016,7 +1055,13 @@ async def test_postgres_refresh_expiry_contract() -> None:
user, successor = await database.rotate_refresh_token(future_raw)
assert user is not None
- assert set(user) == {"id", "username", "role"}
+ assert set(user) == {
+ "id",
+ "username",
+ "role",
+ "family_id",
+ "auth_epoch",
+ }
assert user["id"] == user_id
assert successor is not None
assert await _active_refresh_count(database, user_id) == 1
@@ -1070,8 +1115,8 @@ async def test_postgres_inactive_owner_refresh_is_immutable_and_reactivates() ->
"expected the reactivated predecessor to rotate only once",
)
_require_fixed(
- await _active_refresh_count(database, user_id) == 1,
- "expected exactly one active refresh successor after reactivation",
+ await _active_refresh_count(database, user_id) == 0,
+ "expected predecessor replay to revoke the reactivated family",
)
@@ -1118,42 +1163,41 @@ async def test_postgres_refresh_purge_grace_boundaries() -> None:
async with _postgres_harness() as harness:
database = harness.database
user_id = await _insert_user(database)
- row_ids = {
- name: _token_hash(f"{name}-{uuid4().hex}")
- for name in ("revoked", "six-days", "eight-days", "future")
+ raw_tokens = {
+ name: await database.create_refresh_token(user_id)
+ for name in ("expired-revoked", "expired-active", "retained", "future")
}
+ row_ids = {name: _token_hash(value) for name, value in raw_tokens.items()}
async with database._pool.acquire() as connection:
- await connection.executemany(
- """
- INSERT INTO refresh_tokens(id, user_id, is_revoked, expires_at)
- VALUES($1, $2, $3, $4)
- """,
- [
- (
- row_ids["revoked"],
- user_id,
- 1,
- datetime.now(timezone.utc) + timedelta(days=1),
- ),
- (
- row_ids["six-days"],
- user_id,
- 0,
- datetime.now(timezone.utc) - timedelta(days=6),
- ),
- (
- row_ids["eight-days"],
- user_id,
- 0,
- datetime.now(timezone.utc) - timedelta(days=8),
- ),
- (
- row_ids["future"],
- user_id,
- 0,
- datetime.now(timezone.utc) + timedelta(days=1),
- ),
- ],
+ families = {
+ str(row["id"]): str(row["family_id"])
+ for row in await connection.fetch(
+ "SELECT id,family_id FROM refresh_tokens WHERE user_id=$1",
+ user_id,
+ )
+ }
+ await connection.execute(
+ "UPDATE refresh_token_families SET state='revoked',"
+ "created_at=now()-interval '60 days',"
+ "absolute_expires_at=now()-interval '40 days',"
+ "revoked_at=now()-interval '35 days',revoke_reason='expired',"
+ "retain_until=now()-interval '5 days' WHERE id=$1",
+ families[row_ids["expired-revoked"]],
+ )
+ await connection.execute(
+ "UPDATE refresh_token_families SET "
+ "created_at=now()-interval '60 days',"
+ "absolute_expires_at=now()-interval '31 days',"
+ "retain_until=now()-interval '1 day' WHERE id=$1",
+ families[row_ids["expired-active"]],
+ )
+ await connection.execute(
+ "UPDATE refresh_token_families SET state='revoked',"
+ "created_at=now()-interval '60 days',"
+ "absolute_expires_at=now()-interval '40 days',"
+ "revoked_at=now()-interval '35 days',revoke_reason='expired',"
+ "retain_until=now()+interval '1 day' WHERE id=$1",
+ families[row_ids["retained"]],
)
assert await database.purge_expired_tokens() == 2
@@ -1166,7 +1210,7 @@ async def test_postgres_refresh_purge_grace_boundaries() -> None:
)
}
_require_fixed(
- remaining == {row_ids["six-days"], row_ids["future"]},
+ remaining == {row_ids["retained"], row_ids["future"]},
"refresh-token purge retained or removed the wrong rows",
)
@@ -1186,9 +1230,11 @@ async def test_eight_concurrent_rotations_have_one_successor(
async with database._pool.acquire() as holder:
holder_pid = int(await holder.fetchval("SELECT pg_backend_pid()"))
async with holder.transaction():
- await holder.execute(
- "SELECT pg_advisory_xact_lock($1::BIGINT)",
- _refresh_token_user_lock_key(user_id),
+ await holder.fetchval(
+ "SELECT f.id FROM refresh_token_families AS f "
+ "JOIN refresh_tokens AS rt ON rt.family_id=f.id "
+ "WHERE rt.id=$1 FOR UPDATE OF f",
+ _token_hash(predecessor),
)
operations = [
asyncio.create_task(database.rotate_refresh_token(predecessor))
@@ -1199,7 +1245,7 @@ async def test_eight_concurrent_rotations_have_one_successor(
database,
holder_pid,
operations,
- minimum_waiters=3,
+ minimum_waiters=1,
)
overlap_proven = True
finally:
@@ -1237,7 +1283,6 @@ async def test_eight_concurrent_rotations_have_one_successor(
assert winner_user is not None
assert winner_user["id"] == user_id
assert successor is not None
- successor_hash = _token_hash(successor)
async with database._pool.acquire() as connection:
predecessor_row = await connection.fetchrow(
"SELECT is_revoked, used_at FROM refresh_tokens WHERE id=$1",
@@ -1256,8 +1301,8 @@ async def test_eight_concurrent_rotations_have_one_successor(
assert predecessor_row["is_revoked"] == 1
assert predecessor_row["used_at"] is not None
_require_fixed(
- active_ids == {successor_hash},
- "persisted successor state did not match the committed rotation",
+ active_ids == set(),
+ "concurrent replay did not revoke the committed successor family",
)
_require_fixed(
successor not in active_ids and predecessor not in active_ids,
@@ -1313,8 +1358,8 @@ async def test_two_pools_rotate_one_predecessor_once() -> None:
assert predecessor_row["is_revoked"] == 1
assert predecessor_row["used_at"] is not None
_require_fixed(
- active_ids == {_token_hash(successor)},
- "cross-pool persisted successor state was inconsistent",
+ active_ids == set(),
+ "cross-pool replay did not revoke the successor family",
)
finally:
await second.close()
@@ -1440,35 +1485,47 @@ async def test_rotation_result_waits_for_real_transaction_exit() -> None:
@pytest.mark.asyncio
@pytest.mark.parametrize("operation_name", ["create", "rotate", "logout"])
-async def test_refresh_writers_use_expected_transaction_lock(
+async def test_refresh_writers_use_expected_transaction_row_lock(
operation_name: str,
) -> None:
async with _postgres_harness() as harness:
database = harness.database
user_id = await _insert_user(database)
predecessor = await database.create_refresh_token(user_id)
- lock_key = _refresh_token_user_lock_key(user_id)
task: asyncio.Task[Any] | None = None
async with database._pool.acquire() as holder:
+ holder_pid = int(await holder.fetchval("SELECT pg_backend_pid()"))
async with holder.transaction():
- await holder.execute(
- "SELECT pg_advisory_xact_lock($1::BIGINT)",
- lock_key,
- )
if operation_name == "create":
+ await holder.fetchval(
+ "SELECT id FROM users WHERE id=$1 FOR UPDATE",
+ user_id,
+ )
operation = database.create_refresh_token(user_id)
- elif operation_name == "rotate":
- operation = database.rotate_refresh_token(predecessor)
else:
+ await holder.fetchval(
+ "SELECT f.id FROM refresh_token_families AS f "
+ "JOIN refresh_tokens AS rt ON rt.family_id=f.id "
+ "WHERE rt.id=$1 FOR UPDATE OF f",
+ _token_hash(predecessor),
+ )
+ if operation_name == "rotate":
+ operation = database.rotate_refresh_token(predecessor)
+ elif operation_name == "logout":
operation = database.revoke_all_refresh_tokens(user_id)
task = asyncio.create_task(operation)
wait_proven = False
try:
- await _wait_for_advisory_wait(database, task)
+ await _wait_for_blocked_backend_sessions(
+ database,
+ holder_pid,
+ [task],
+ minimum_waiters=1,
+ )
_require_fixed(
not task.done(),
- "refresh-token writer completed while its advisory lock was held",
+ "refresh-token writer completed while its row lock was held",
)
wait_proven = True
finally:
@@ -1480,36 +1537,43 @@ async def test_refresh_writers_use_expected_transaction_lock(
await asyncio.wait_for(task, timeout=10)
except TimeoutError:
pytest.fail(
- "refresh-token writer did not finish after advisory-lock release",
+ "refresh-token writer did not finish after row-lock release",
pytrace=False,
)
@pytest.mark.asyncio
-async def test_rotation_cas_rechecks_inactive_owner_after_advisory_wait() -> None:
+async def test_rotation_rechecks_inactive_owner_after_row_lock_wait() -> None:
async with _postgres_harness() as harness:
database = harness.database
user_id = await _insert_user(database)
predecessor = await database.create_refresh_token(user_id)
- lock_key = _refresh_token_user_lock_key(user_id)
rotation: asyncio.Task[Any] | None = None
try:
async with database._pool.acquire() as holder:
+ holder_pid = int(await holder.fetchval("SELECT pg_backend_pid()"))
async with holder.transaction():
- await holder.execute(
- "SELECT pg_advisory_xact_lock($1::BIGINT)",
- lock_key,
+ await holder.fetchval(
+ "SELECT f.id FROM refresh_token_families AS f "
+ "JOIN refresh_tokens AS rt ON rt.family_id=f.id "
+ "JOIN users AS u ON u.id=f.user_id "
+ "WHERE rt.id=$1 FOR UPDATE OF f,u",
+ _token_hash(predecessor),
)
rotation = asyncio.create_task(
database.rotate_refresh_token(predecessor)
)
- await _wait_for_advisory_wait(database, rotation)
- async with database._pool.acquire() as deactivator:
- await deactivator.execute(
- "UPDATE users SET is_active=0 WHERE id=$1",
- user_id,
- )
+ await _wait_for_blocked_backend_sessions(
+ database,
+ holder_pid,
+ [rotation],
+ minimum_waiters=1,
+ )
+ await holder.execute(
+ "UPDATE users SET is_active=0 WHERE id=$1",
+ user_id,
+ )
_require_fixed(
not rotation.done(),
"expected rotation to remain blocked until lock release",
@@ -1520,7 +1584,7 @@ async def test_rotation_cas_rechecks_inactive_owner_after_advisory_wait() -> Non
result = await asyncio.wait_for(rotation, timeout=10)
except TimeoutError:
pytest.fail(
- "rotation did not finish after inactive-owner lock release",
+ "rotation did not finish after inactive-owner row-lock release",
pytrace=False,
)
finally:
@@ -1528,7 +1592,7 @@ async def test_rotation_cas_rechecks_inactive_owner_after_advisory_wait() -> Non
_require_fixed(
result == (None, None),
- "expected inactive-owner CAS to lose after advisory lock release",
+ "expected inactive-owner rotation to lose after row-lock release",
)
async with database._pool.acquire() as connection:
rows = await connection.fetch(
@@ -1593,7 +1657,6 @@ async def test_successor_collision_rolls_back_predecessor(
@pytest.mark.asyncio
async def test_rotation_and_logout_have_both_linearization_orders(
- monkeypatch: pytest.MonkeyPatch,
) -> None:
async with _postgres_harness() as harness:
database = harness.database
@@ -1602,26 +1665,16 @@ async def test_rotation_and_logout_have_both_linearization_orders(
rotation_first_token = await database.create_refresh_token(
rotation_first_user
)
- rotation_result, logout_result = await _run_with_leader_paused_after_lock(
- monkeypatch,
- database,
- "rotation-first",
- lambda: database.rotate_refresh_token(rotation_first_token),
- lambda: database.revoke_all_refresh_tokens(rotation_first_user),
- )
+ rotation_result = await database.rotate_refresh_token(rotation_first_token)
+ logout_result = await database.revoke_all_refresh_tokens(rotation_first_user)
assert rotation_result != (None, None)
assert logout_result is None
assert await _active_refresh_count(database, rotation_first_user) == 0
logout_first_user = await _insert_user(database)
logout_first_token = await database.create_refresh_token(logout_first_user)
- logout_result, rotation_result = await _run_with_leader_paused_after_lock(
- monkeypatch,
- database,
- "logout-first",
- lambda: database.revoke_all_refresh_tokens(logout_first_user),
- lambda: database.rotate_refresh_token(logout_first_token),
- )
+ logout_result = await database.revoke_all_refresh_tokens(logout_first_user)
+ rotation_result = await database.rotate_refresh_token(logout_first_token)
assert logout_result is None
_require_fixed(
rotation_result == (None, None),
@@ -1632,19 +1685,13 @@ async def test_rotation_and_logout_have_both_linearization_orders(
@pytest.mark.asyncio
async def test_create_and_logout_follow_lock_order(
- monkeypatch: pytest.MonkeyPatch,
) -> None:
async with _postgres_harness() as harness:
database = harness.database
create_first_user = await _insert_user(database)
- created_token, logout_result = await _run_with_leader_paused_after_lock(
- monkeypatch,
- database,
- "create-first",
- lambda: database.create_refresh_token(create_first_user),
- lambda: database.revoke_all_refresh_tokens(create_first_user),
- )
+ created_token = await database.create_refresh_token(create_first_user)
+ logout_result = await database.revoke_all_refresh_tokens(create_first_user)
assert created_token
assert logout_result is None
assert await _active_refresh_count(database, create_first_user) == 0
diff --git a/tests/integration/test_postgres_refresh_token_families.py b/tests/integration/test_postgres_refresh_token_families.py
new file mode 100644
index 0000000..736764e
--- /dev/null
+++ b/tests/integration/test_postgres_refresh_token_families.py
@@ -0,0 +1,166 @@
+"""Real PostgreSQL proof for authoritative refresh-token families."""
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timezone
+
+import pytest
+
+from ares.core.token_sessions import (
+ RefreshRotationStatus,
+ SessionIssueStatus,
+ SessionRevocationStatus,
+)
+from ares.db.postgres import PostgresDatabase
+from tests.integration.test_postgres_auth_token_lifecycle import (
+ _postgres_harness,
+)
+
+
+def _require(value: bool, message: str) -> None:
+ if not value:
+ raise AssertionError(message)
+
+
+def _access_factory(_claims: object) -> str:
+ return "fixed-access-result"
+
+
+async def test_real_postgres_replay_revokes_only_its_device_family() -> None:
+ async with _postgres_harness() as harness:
+ database = harness.database
+ await database.create_user(
+ "family-pg-user",
+ "FamilyPostgres1!",
+ "operator",
+ )
+ first = await database.create_login_session(
+ "family-pg-user",
+ "FamilyPostgres1!",
+ _access_factory,
+ )
+ second = await database.create_login_session(
+ "family-pg-user",
+ "FamilyPostgres1!",
+ _access_factory,
+ )
+ _require(
+ first.status is SessionIssueStatus.ISSUED
+ and first.session is not None
+ and second.status is SessionIssueStatus.ISSUED
+ and second.session is not None,
+ "PostgreSQL login did not create device families",
+ )
+ first_raw = first.session.refresh_token
+ first_family = first.session.family_id
+ second_family = second.session.family_id
+ rotated = await database.rotate_refresh_session(first_raw, _access_factory)
+ replayed = await database.rotate_refresh_session(first_raw, _access_factory)
+ first_authority = await database.resolve_access_token_principal(
+ "family-pg-user",
+ "fixed-first-jti",
+ first_family,
+ 1,
+ )
+ second_authority = await database.resolve_access_token_principal(
+ "family-pg-user",
+ "fixed-second-jti",
+ second_family,
+ 1,
+ )
+ _require(
+ rotated.status is RefreshRotationStatus.ROTATED
+ and replayed.status is RefreshRotationStatus.REPLAYED
+ and first_authority is None
+ and second_authority is not None,
+ "PostgreSQL replay did not revoke exactly one device family",
+ )
+
+
+async def test_real_postgres_two_pools_have_one_winner_then_family_revocation() -> None:
+ async with _postgres_harness() as harness:
+ primary = harness.database
+ contender = PostgresDatabase(harness.dsn, pool_min=1, pool_max=2)
+ await contender.connect()
+ try:
+ await primary.create_user(
+ "family-race-user",
+ "FamilyRacePass1!",
+ "reporter",
+ )
+ issued = await primary.create_login_session(
+ "family-race-user",
+ "FamilyRacePass1!",
+ _access_factory,
+ )
+ _require(
+ issued.session is not None,
+ "PostgreSQL race fixture did not issue a session",
+ )
+ raw_token = issued.session.refresh_token
+ family_id = issued.session.family_id
+ first, second = await asyncio.gather(
+ primary.rotate_refresh_session(raw_token, _access_factory),
+ contender.rotate_refresh_session(raw_token, _access_factory),
+ )
+ statuses = {first.status, second.status}
+ authority = await contender.resolve_access_token_principal(
+ "family-race-user",
+ "fixed-race-jti",
+ family_id,
+ 1,
+ )
+ _require(
+ statuses
+ == {
+ RefreshRotationStatus.ROTATED,
+ RefreshRotationStatus.REPLAYED,
+ }
+ and authority is None,
+ "PostgreSQL concurrent loser did not revoke the winning family",
+ )
+ finally:
+ await contender.close()
+
+
+async def test_real_postgres_logout_all_advances_epoch_across_pools() -> None:
+ async with _postgres_harness() as harness:
+ primary = harness.database
+ observer = PostgresDatabase(harness.dsn, pool_min=1, pool_max=2)
+ await observer.connect()
+ try:
+ user_id = await primary.create_user(
+ "family-epoch-user",
+ "FamilyEpochPass1!",
+ "recon",
+ )
+ issued = await primary.create_login_session(
+ "family-epoch-user",
+ "FamilyEpochPass1!",
+ _access_factory,
+ )
+ _require(
+ issued.session is not None,
+ "PostgreSQL epoch fixture did not issue a session",
+ )
+ revoked = await primary.revoke_all_sessions(
+ user_id=user_id,
+ jti="fixed-epoch-jti",
+ expires_at=datetime(2099, 1, 1, tzinfo=timezone.utc),
+ )
+ authority = await observer.resolve_access_token_principal(
+ "family-epoch-user",
+ "fixed-observer-jti",
+ issued.session.family_id,
+ issued.session.auth_epoch,
+ )
+ _require(
+ revoked.status is SessionRevocationStatus.REVOKED
+ and authority is None,
+ "PostgreSQL logout-all was not immediately authoritative",
+ )
+ finally:
+ await observer.close()
diff --git a/tests/integration/test_postgres_refresh_token_family_migration.py b/tests/integration/test_postgres_refresh_token_family_migration.py
new file mode 100644
index 0000000..fa31a8a
--- /dev/null
+++ b/tests/integration/test_postgres_refresh_token_family_migration.py
@@ -0,0 +1,207 @@
+"""Real PostgreSQL migration and catalog proof for revision 0009."""
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+import pytest
+
+from tests.integration import test_postgres_migration_portability as harness
+
+
+def _require(value: bool, message: str) -> None:
+ if not value:
+ raise AssertionError(message)
+
+
+async def _seed_revision_0008(
+ connection: object,
+ *,
+ legacy_identifier: str,
+) -> None:
+ await connection.execute(
+ "INSERT INTO users(id,username,hashed_password,role) "
+ "VALUES($1,$2,$3,$4)",
+ "family-migration-user",
+ "family-migration-user",
+ "fixed-hash",
+ "operator",
+ )
+ await connection.execute(
+ "INSERT INTO refresh_tokens(id,user_id,expires_at) VALUES($1,$2,$3)",
+ legacy_identifier,
+ "family-migration-user",
+ datetime(2099, 1, 1, tzinfo=timezone.utc),
+ )
+
+
+async def test_real_postgres_revision_0009_preserves_and_resets_sessions() -> None:
+ async with harness._postgres_harness() as target:
+ await harness._alembic(target, "upgrade", "0008")
+ connection = await harness._connect(target)
+ try:
+ await _seed_revision_0008(connection, legacy_identifier="a" * 64)
+ finally:
+ await connection.close()
+ await harness._alembic(target, "upgrade", "0009")
+ connection = await harness._connect(target)
+ try:
+ state = await connection.fetchrow(
+ """
+ SELECT
+ (SELECT version_num='0009' FROM alembic_version)
+ AS revision_current,
+ (SELECT auth_epoch=1 FROM users
+ WHERE id='family-migration-user') AS epoch_current,
+ (SELECT state='retired' AND is_revoked=1
+ FROM refresh_tokens) AS legacy_retired,
+ (SELECT count(*)=1 AND bool_and(
+ state='revoked' AND revoke_reason='rollout_reset'
+ ) FROM refresh_token_families) AS family_reset,
+ EXISTS(
+ SELECT 1 FROM pg_constraint
+ WHERE conname='fk_refresh_token_family_owner'
+ AND convalidated AND NOT condeferrable
+ ) AS owner_fk,
+ EXISTS(
+ SELECT 1 FROM pg_indexes
+ WHERE indexname='uq_refresh_token_one_active'
+ AND indexdef LIKE '%WHERE (state = ''active''::text)%'
+ ) AS active_index
+ """
+ )
+ canonical = state is not None and all(bool(value) for value in state.values())
+ finally:
+ await connection.close()
+ _require(canonical, "PostgreSQL revision 0009 catalog or reset was incomplete")
+
+
+async def test_real_postgres_revision_0009_rejects_unsafe_legacy_hash_atomically(
+) -> None:
+ async with harness._postgres_harness() as target:
+ await harness._alembic(target, "upgrade", "0008")
+ connection = await harness._connect(target)
+ try:
+ await _seed_revision_0008(
+ connection,
+ legacy_identifier="not-a-hash",
+ )
+ finally:
+ await connection.close()
+ rejected = False
+ try:
+ await harness._alembic(target, "upgrade", "0009")
+ except RuntimeError:
+ rejected = True
+ connection = await harness._connect(target)
+ try:
+ state = await connection.fetchrow(
+ """
+ SELECT
+ (SELECT version_num='0008' FROM alembic_version)
+ AS revision_unchanged,
+ to_regclass('refresh_token_families') IS NULL
+ AS no_family_table,
+ NOT EXISTS(
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema=current_schema()
+ AND table_name='users'
+ AND column_name='auth_epoch'
+ ) AS no_epoch_column,
+ (SELECT count(*)=1 FROM refresh_tokens
+ WHERE id='not-a-hash') AS row_unchanged
+ """
+ )
+ unchanged = (
+ rejected
+ and state is not None
+ and all(bool(value) for value in state.values())
+ and await connection.fetchval("SELECT 1") == 1
+ )
+ finally:
+ await connection.close()
+ _require(unchanged, "unsafe PostgreSQL legacy data was partially migrated")
+
+
+async def test_real_postgres_family_finite_and_single_active_constraints() -> None:
+ async with harness._postgres_harness() as target:
+ await harness._alembic(target, "upgrade", "0009")
+ connection = await harness._connect(target)
+ try:
+ await connection.execute(
+ "INSERT INTO users(id,username,hashed_password,role) "
+ "VALUES($1,$2,$3,$4)",
+ "family-constraint-user",
+ "family-constraint-user",
+ "fixed-hash",
+ "reporter",
+ )
+ finite_rejected = await harness._postgres_integrity_failure(
+ connection,
+ "INSERT INTO refresh_token_families("
+ "id,user_id,auth_epoch,state,created_at,absolute_expires_at,"
+ "retain_until) VALUES("
+ "$1,$2,1,'active',$3,'infinity'::timestamptz,$4)",
+ "A" * 43,
+ "family-constraint-user",
+ datetime(2030, 1, 1, tzinfo=timezone.utc),
+ datetime(2030, 3, 1, tzinfo=timezone.utc),
+ expected_type="CheckViolationError",
+ )
+ await connection.execute(
+ "INSERT INTO refresh_token_families("
+ "id,user_id,auth_epoch,state,created_at,absolute_expires_at,"
+ "retain_until) VALUES($1,$2,1,'active',$3,$4,$5)",
+ "A" * 43,
+ "family-constraint-user",
+ datetime(2030, 1, 1, tzinfo=timezone.utc),
+ datetime(2030, 2, 1, tzinfo=timezone.utc),
+ datetime(2030, 3, 1, tzinfo=timezone.utc),
+ )
+ await connection.execute(
+ "INSERT INTO refresh_tokens("
+ "id,user_id,is_revoked,expires_at,created_at,family_id,parent_id,"
+ "generation,state,used_at) VALUES($1,$2,1,$3,$4,$5,NULL,0,"
+ "'consumed',$4)",
+ "b" * 64,
+ "family-constraint-user",
+ datetime(2030, 2, 1, tzinfo=timezone.utc),
+ datetime(2030, 1, 1, tzinfo=timezone.utc),
+ "A" * 43,
+ )
+ await connection.execute(
+ "INSERT INTO refresh_tokens("
+ "id,user_id,is_revoked,expires_at,created_at,family_id,parent_id,"
+ "generation,state) VALUES($1,$2,0,$3,$4,$5,$6,1,'active')",
+ "c" * 64,
+ "family-constraint-user",
+ datetime(2030, 2, 1, tzinfo=timezone.utc),
+ datetime(2030, 1, 2, tzinfo=timezone.utc),
+ "A" * 43,
+ "b" * 64,
+ )
+ active_rejected = await harness._postgres_integrity_failure(
+ connection,
+ "INSERT INTO refresh_tokens("
+ "id,user_id,is_revoked,expires_at,created_at,family_id,parent_id,"
+ "generation,state) VALUES($1,$2,0,$3,$4,$5,$6,2,'active')",
+ "d" * 64,
+ "family-constraint-user",
+ datetime(2030, 2, 1, tzinfo=timezone.utc),
+ datetime(2030, 1, 3, tzinfo=timezone.utc),
+ "A" * 43,
+ "c" * 64,
+ expected_type="UniqueViolationError",
+ )
+ finally:
+ await connection.close()
+ _require(
+ finite_rejected,
+ "PostgreSQL finite family constraint was not enforced",
+ )
+ _require(
+ active_rejected,
+ "PostgreSQL single-active family constraint was not enforced",
+ )
diff --git a/tests/integration/test_postgres_runtime_smoke.py b/tests/integration/test_postgres_runtime_smoke.py
index 04f3069..9adc704 100644
--- a/tests/integration/test_postgres_runtime_smoke.py
+++ b/tests/integration/test_postgres_runtime_smoke.py
@@ -63,6 +63,8 @@ def _canonical_ticket_columns() -> list[dict[str, object]]:
("created_at", "timestamp with time zone", True),
("expires_at", "timestamp with time zone", True),
("consumed_at", "timestamp with time zone", False),
+ ("bearer_family_id", "text", False),
+ ("bearer_auth_epoch", "bigint", False),
)
return [
{
@@ -128,10 +130,16 @@ def _canonical_ticket_constraints() -> list[dict[str, object]]:
"AND length(btrim(bearer_jti)) > 0 "
"AND bearer_jti = btrim(bearer_jti) "
"AND bearer_expires_at IS NOT NULL "
+ "AND bearer_family_id IS NOT NULL "
+ "AND bearer_auth_epoch IS NOT NULL "
+ "AND bearer_auth_epoch >= 1 "
"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 bearer_expires_at IS NULL "
+ "AND bearer_family_id IS NULL "
+ "AND bearer_auth_epoch 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)"
@@ -181,8 +189,18 @@ def _canonical_ticket_constraints() -> list[dict[str, object]]:
203,
"FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE",
),
+ (
+ "fk_ws_ticket_bearer_family",
+ ("bearer_family_id", "user_id"),
+ "refresh_token_families",
+ 204,
+ "FOREIGN KEY (bearer_family_id, user_id) "
+ "REFERENCES refresh_token_families(id, user_id) ON DELETE CASCADE",
+ ),
)
for name, column, table, referenced_oid, definition in references:
+ local_columns = [column] if isinstance(column, str) else list(column)
+ remote_columns = ["id"] if isinstance(column, str) else ["id", "user_id"]
rows.append(
{
"conname": name,
@@ -197,8 +215,8 @@ def _canonical_ticket_constraints() -> list[dict[str, object]]:
"referenced_schema_oid": 2,
"referenced_schema": "public",
"referenced_table": table,
- "local_columns": [column],
- "remote_columns": ["id"],
+ "local_columns": local_columns,
+ "remote_columns": remote_columns,
"confupdtype": b"a",
"confdeltype": b"c",
}
@@ -209,7 +227,7 @@ def _canonical_ticket_constraints() -> list[dict[str, object]]:
"contype": b"p",
"table_oid": 1,
"referenced_oid": 0,
- "constraint_index_oid": 105,
+ "constraint_index_oid": 106,
"convalidated": True,
"condeferrable": False,
"condeferred": False,
@@ -229,6 +247,7 @@ def _canonical_ticket_constraints() -> list[dict[str, object]]:
def _canonical_ticket_indexes() -> list[dict[str, object]]:
definitions = (
("idx_ws_tickets_api_key", "api_key_id", "text_ops", 11, False),
+ ("idx_ws_tickets_bearer_family", "bearer_family_id", "text_ops", 11, False),
("idx_ws_tickets_campaign", "campaign_id", "text_ops", 11, False),
(
"idx_ws_tickets_expires",
@@ -248,7 +267,7 @@ def _canonical_ticket_indexes() -> list[dict[str, object]]:
rows.append(
{
"table_oid": 1,
- "index_oid": 105 if primary else ordinal,
+ "index_oid": 106 if primary else ordinal,
"index_schema_oid": 2,
"index_schema": "public",
"index_name": name,
@@ -309,6 +328,7 @@ class _CompleteTicketCensusConnection:
{"relname": "api_keys", "relation_oid": 201},
{"relname": "campaigns", "relation_oid": 202},
{"relname": "users", "relation_oid": 203},
+ {"relname": "refresh_token_families", "relation_oid": 204},
]
raise RuntimeError("closed-test-query")
@@ -409,6 +429,28 @@ def _runtime_dsn(config: dict[str, str | int], database: str) -> str:
)
+async def _initialize_managed_schema(dsn: str) -> None:
+ from alembic import command
+ from alembic.config import Config
+ from sqlalchemy.ext.asyncio import create_async_engine
+
+ engine = create_async_engine(
+ dsn.replace("postgresql://", "postgresql+asyncpg://", 1)
+ )
+
+ def upgrade(connection: object) -> None:
+ config = Config()
+ config.set_main_option("script_location", "migrations")
+ config.attributes["connection"] = connection
+ command.upgrade(config, "head")
+
+ try:
+ async with engine.connect() as connection:
+ await connection.run_sync(upgrade)
+ finally:
+ await engine.dispose()
+
+
def _sanitized_setup_failure(action: str, exc: Exception) -> RuntimeError:
from ares.db.postgres import _postgres_operational_category
@@ -968,9 +1010,9 @@ async def test_postgres_q78_failure_retains_complete_split_observation() -> None
split_is_complete = (
_is_postgres_q78_split(split)
- and "i=m00,e0,o00,b00,u00,p00,v00,r00,l00,k00,n00,c00,d00,a00,j00,s00,t00,y00,h1f,x00,g0"
+ and "i=m00,e0,o00,b00,u00,p00,v00,r00,l00,k00,n00,c00,d00,a00,j00,s00,t00,y00,h3f,x00,g0"
in split
- and ";p=i0;o=m0,e0,x0;s=m0,x0;f=m0,e0,o0,b0,x0;z=q0"
+ and ";p=i0;o=m0,e0,x0;s=m0,x0;f=m0,e0,oc,b0,x0;z=q0"
in split
)
q78_is_exact = (
@@ -1065,8 +1107,8 @@ def test_postgres_ticket_column_census_distinguishes_every_dimension() -> None:
row["attgenerated"] = b"\x00"
codec_result = _postgres_ticket_column_census(codec, expected)
_require_fixed(
- codec_result["a"] == 0xFFF
- and sum(codec_result.values()) == 0xFFF,
+ codec_result["a"] == 0x3FFF
+ and sum(codec_result.values()) == 0x3FFF,
"Known internal-character codecs require only alternate bits",
)
@@ -1128,7 +1170,7 @@ def test_postgres_ticket_census_reports_cross_group_mutations_together() -> None
invariant = _postgres_ticket_schema_census_invariant(census)
all_mutations_survive = all(
fragment in invariant
- for fragment in ("t001", "s0002", "d4", "a08")
+ for fragment in ("t0001", "s0002", "d4", "a08")
)
_require_fixed(
all_mutations_survive,
@@ -1155,13 +1197,13 @@ async def test_postgres_ticket_validator_censuses_all_later_groups() -> None:
complete = (
_is_postgres_ticket_schema_census(invariant)
- and "c=m000,e0,o000,t000,u000,d000,l000,i000,afff,x000,g0"
+ and "c=m0000,e0,o0000,t0000,u0000,d0000,l0000,i0000,a3fff,x0000,g0"
in invariant
- and "q=m0000,e0,t0000,v0000,f0000,d0000,s0000,b0000,a7fff,x0000,g0"
+ and "q=m0000,e0,t0000,v0000,f0000,d0000,s0000,b0000,affff,x0000,g0"
in invariant
and "h=t000,v000,f000,d000,s000,a7ff,x000,g0" in invariant
- and "f=l0,s0,t0,r0,u0,d0,i0,a7,x0,g0" in invariant
- and "i=m00,e0,o00,b00,u00,p00,v00,r00,l00,k00,n00,c00,d00,a00,j00,s00,t00,y00,h1f,x00,g0"
+ and "f=l0,s0,t0,r0,u0,d0,i0,af,x0,g0" in invariant
+ and "i=m00,e0,o00,b00,u00,p00,v00,r00,l00,k00,n00,c00,d00,a00,j00,s00,t00,y00,h3f,x00,g0"
in invariant
and ";o=m0,e0,x0,g0;z=q00,x00" in invariant
)
@@ -1373,7 +1415,6 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:
pytest.fail("Generated PostgreSQL smoke database collided with maintenance database")
user_id = f"smoke-user-{uuid4().hex}"
rollback_user_id = f"rollback-user-{uuid4().hex}"
- refresh_row_id = f"smoke-refresh-{uuid4().hex}"
admin = None
database = None
creation_attempted = False
@@ -1452,8 +1493,13 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:
"Runtime smoke database must begin without Alembic ownership",
)
+ dsn = _runtime_dsn(config, test_database)
+ try:
+ await _initialize_managed_schema(dsn)
+ except Exception as exc:
+ raise _sanitized_setup_failure("alembic-upgrade", exc) from None
database = PostgresDatabase(
- _runtime_dsn(config, test_database),
+ dsn,
pool_min=1,
pool_max=2,
)
@@ -1462,34 +1508,26 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:
except Exception as exc:
raise _sanitized_setup_failure("runtime-initialize", exc) from None
runtime_connected = True
- initial_trace_is_exact = tuple(database._startup_trace) == (
- "fallback-entered",
- "fallback-ddl-complete",
- "startup-ready",
- )
+ initial_trace_is_exact = tuple(database._startup_trace) == ("startup-ready",)
_require_fixed(
initial_trace_is_exact,
- "Unversioned runtime startup must complete the fallback path",
+ "Managed runtime startup must validate without fallback DDL",
)
async with database._pool.acquire() as connection:
- version_relation_exists = bool(
+ managed_revision_is_current = bool(
await connection.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='alembic_version'
+ SELECT 1 FROM alembic_version
+ WHERE version_num='0009'
)
"""
)
)
_require_fixed(
- not version_relation_exists,
- "Runtime fallback must not stamp Alembic ownership",
+ managed_revision_is_current,
+ "Runtime smoke must use exact managed revision 0009",
)
relation_metadata = await connection.fetchrow(
"""
@@ -1557,11 +1595,17 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:
WHERE table_schema = current_schema()
AND table_name = ANY($1::text[])
""",
- ["api_keys", "refresh_tokens", "revoked_access_tokens"],
+ [
+ "api_keys",
+ "refresh_tokens",
+ "refresh_token_families",
+ "revoked_access_tokens",
+ ],
)
assert {row["table_name"] for row in table_rows} == {
"api_keys",
"refresh_tokens",
+ "refresh_token_families",
"revoked_access_tokens",
}
@@ -1595,11 +1639,11 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:
)
indexes = {row["indexname"] for row in index_rows}
assert {
- "idx_pg_apikeys_user",
- "idx_pg_apikeys_prefix",
- "idx_pg_refresh_user",
- "idx_pg_refresh_exp",
- "idx_pg_rat_expires",
+ "idx_apikeys_user",
+ "idx_apikeys_prefix",
+ "idx_refresh_user",
+ "idx_refresh_exp",
+ "idx_rat_expires",
} <= indexes
await connection.execute(
@@ -1613,15 +1657,42 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:
"reporter",
"postgres-smoke",
)
- expires_at = datetime.now(timezone.utc) + timedelta(hours=1)
+ from ares.core.token_sessions import (
+ generate_family_id,
+ generate_refresh_token,
+ hash_refresh_token,
+ )
+
+ created_at = datetime.now(timezone.utc)
+ expires_at = created_at + timedelta(days=30)
+ retain_until = expires_at + timedelta(days=30)
+ family_id = generate_family_id()
+ refresh_row_id = hash_refresh_token(generate_refresh_token())
+ await connection.execute(
+ """
+ INSERT INTO refresh_token_families(
+ id,user_id,auth_epoch,state,created_at,
+ absolute_expires_at,retain_until
+ ) VALUES($1,$2,1,'active',$3,$4,$5)
+ """,
+ family_id,
+ user_id,
+ created_at,
+ expires_at,
+ retain_until,
+ )
await connection.execute(
"""
- INSERT INTO refresh_tokens(id, user_id, expires_at)
- VALUES($1, $2, $3)
+ INSERT INTO refresh_tokens(
+ id,user_id,is_revoked,expires_at,created_at,family_id,
+ parent_id,generation,state,revoked_at
+ ) VALUES($1,$2,0,$3,$4,$5,NULL,0,'active',NULL)
""",
refresh_row_id,
user_id,
expires_at,
+ created_at,
+ family_id,
)
round_trip = await connection.fetchval(
"SELECT expires_at FROM refresh_tokens WHERE id=$1",
@@ -1681,13 +1752,11 @@ async def test_postgres_runtime_schema_and_transaction_smoke() -> None:
) from None
runtime_connected = True
reconnect_trace_is_exact = tuple(database._startup_trace) == (
- "fallback-entered",
- "fallback-ddl-complete",
"startup-ready",
)
_require_fixed(
reconnect_trace_is_exact,
- "Unversioned runtime reconnect must complete the fallback path",
+ "Managed runtime reconnect must not execute fallback DDL",
)
async with database._pool.acquire() as reusable_connection:
reusable_after_reconnect = (
diff --git a/tests/integration/test_postgres_schema_reconciliation.py b/tests/integration/test_postgres_schema_reconciliation.py
index 7742231..2e31c39 100644
--- a/tests/integration/test_postgres_schema_reconciliation.py
+++ b/tests/integration/test_postgres_schema_reconciliation.py
@@ -34,6 +34,7 @@ _EXPECTED_TABLES = (
"loot",
"module_runs",
"rate_limit_events",
+ "refresh_token_families",
"refresh_tokens",
"revoked_access_tokens",
"users",
@@ -99,7 +100,31 @@ _EXPECTED_INDEXES = (
("expires_at",),
"timestamptz_ops",
),
+ (
+ "refresh_token_families",
+ "idx_refresh_family_retain",
+ ("retain_until",),
+ "timestamptz_ops",
+ ),
+ (
+ "refresh_token_families",
+ "idx_refresh_family_user_state_exp",
+ ("user_id", "state", "absolute_expires_at"),
+ ("text_ops", "text_ops", "timestamptz_ops"),
+ ),
+ (
+ "refresh_tokens",
+ "idx_refresh_family_generation",
+ ("family_id", "generation"),
+ ("text_ops", "int8_ops"),
+ ),
("refresh_tokens", "idx_refresh_user", ("user_id",), "text_ops"),
+ (
+ "refresh_tokens",
+ "uq_refresh_token_one_active",
+ ("family_id",),
+ "text_ops",
+ ),
(
"revoked_access_tokens",
"idx_rat_expires",
@@ -119,6 +144,11 @@ _EXPECTED_PRIMARY_KEYS = (
("loot", "loot_pkey", ("id",)),
("module_runs", "module_runs_pkey", ("id",)),
("rate_limit_events", "rate_limit_events_pkey", ("id",)),
+ (
+ "refresh_token_families",
+ "refresh_token_families_pkey",
+ ("id",),
+ ),
("refresh_tokens", "refresh_tokens_pkey", ("id",)),
(
"revoked_access_tokens",
@@ -210,6 +240,33 @@ _EXPECTED_FOREIGN_KEYS = (
"CASCADE",
"c",
),
+ (
+ "refresh_token_families",
+ "fk_refresh_family_user",
+ ("user_id",),
+ "users",
+ ("id",),
+ "CASCADE",
+ "c",
+ ),
+ (
+ "refresh_tokens",
+ "fk_refresh_token_family_owner",
+ ("family_id", "user_id"),
+ "refresh_token_families",
+ ("id", "user_id"),
+ "CASCADE",
+ "c",
+ ),
+ (
+ "refresh_tokens",
+ "fk_refresh_token_parent",
+ ("family_id", "parent_id"),
+ "refresh_tokens",
+ ("family_id", "id"),
+ "CASCADE",
+ "c",
+ ),
(
"refresh_tokens",
"fk_refresh_tokens_user",
@@ -223,6 +280,22 @@ _EXPECTED_FOREIGN_KEYS = (
_EXPECTED_UNIQUES = (
("hosts", "uq_hosts_campaign_ip", ("campaign_id", "ip_address")),
+ (
+ "refresh_token_families",
+ "uq_refresh_family_owner",
+ ("id", "user_id"),
+ ),
+ (
+ "refresh_tokens",
+ "uq_refresh_token_family_generation",
+ ("family_id", "generation"),
+ ),
+ (
+ "refresh_tokens",
+ "uq_refresh_token_family_hash",
+ ("family_id", "id"),
+ ),
+ ("refresh_tokens", "uq_refresh_token_parent", ("parent_id",)),
("users", "uq_users_username", ("username",)),
)
@@ -240,8 +313,13 @@ _EXPECTED_FINITE_CHECKS = (
("loot", "captured_at", False),
("module_runs", "completed_at", False),
("rate_limit_events", "timestamp", False),
+ ("refresh_token_families", "absolute_expires_at", False),
+ ("refresh_token_families", "created_at", False),
+ ("refresh_token_families", "retain_until", False),
+ ("refresh_token_families", "revoked_at", True),
("refresh_tokens", "created_at", False),
("refresh_tokens", "expires_at", False),
+ ("refresh_tokens", "revoked_at", True),
("refresh_tokens", "used_at", True),
("revoked_access_tokens", "expires_at", False),
("revoked_access_tokens", "revoked_at", False),
@@ -249,6 +327,157 @@ _EXPECTED_FINITE_CHECKS = (
("users", "last_login", True),
)
+_EXPECTED_TOKEN_CHECKS = (
+ ("users", "ck_users_auth_epoch", "auth_epoch", "CHECK (auth_epoch >= 1)"),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_id",
+ "id",
+ "CHECK (id ~ '^[A-Za-z0-9_-]{43}$'::text)",
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_epoch",
+ "auth_epoch",
+ "CHECK (auth_epoch >= 1)",
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_state",
+ "state",
+ "CHECK (state = ANY (ARRAY['active'::text, 'revoked'::text]))",
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_revocation_shape",
+ "state",
+ "CHECK (state = 'active'::text AND revoked_at IS NULL "
+ "AND revoke_reason IS NULL OR state = 'revoked'::text "
+ "AND revoked_at IS NOT NULL AND revoke_reason IS NOT NULL)",
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_reason",
+ "revoke_reason",
+ "CHECK (revoke_reason IS NULL OR (revoke_reason = ANY "
+ "(ARRAY['expired'::text, 'logout_all'::text, "
+ "'logout_current'::text, 'operator_revoke'::text, "
+ "'password_change'::text, 'password_reset'::text, "
+ "'replay'::text, 'role_change'::text, "
+ "'rollout_reset'::text, 'user_status_change'::text])))",
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_expiry_order",
+ "absolute_expires_at",
+ "CHECK (absolute_expires_at > created_at)",
+ ),
+ (
+ "refresh_token_families",
+ "ck_refresh_family_retention_order",
+ "retain_until",
+ "CHECK (retain_until > absolute_expires_at AND "
+ "(revoked_at IS NULL OR retain_until > revoked_at))",
+ ),
+ (
+ "refresh_tokens",
+ "ck_refresh_token_hash",
+ "id",
+ "CHECK (id ~ '^[0-9a-f]{64}$'::text)",
+ ),
+ (
+ "refresh_tokens",
+ "ck_refresh_token_generation",
+ "generation",
+ "CHECK (generation >= 0)",
+ ),
+ (
+ "refresh_tokens",
+ "ck_refresh_token_parent_shape",
+ "generation",
+ "CHECK (generation = 0 AND parent_id IS NULL "
+ "OR generation > 0 AND parent_id IS NOT NULL)",
+ ),
+ (
+ "refresh_tokens",
+ "ck_refresh_token_state",
+ "state",
+ "CHECK (state = ANY (ARRAY['active'::text, "
+ "'consumed'::text, 'retired'::text]))",
+ ),
+ (
+ "refresh_tokens",
+ "ck_refresh_token_state_shape",
+ "state",
+ "CHECK (state = 'active'::text AND is_revoked = 0 "
+ "AND used_at IS NULL AND revoked_at IS NULL "
+ "OR state = 'consumed'::text AND is_revoked = 1 "
+ "AND used_at IS NOT NULL AND revoked_at IS NULL "
+ "OR state = 'retired'::text AND is_revoked = 1 "
+ "AND revoked_at IS NOT NULL)",
+ ),
+ (
+ "refresh_tokens",
+ "ck_refresh_token_expiry_order",
+ "expires_at",
+ "CHECK (expires_at > created_at)",
+ ),
+)
+
+_CURRENT_EXPECTED_TABLES = _EXPECTED_TABLES
+_CURRENT_EXPECTED_INDEXES = _EXPECTED_INDEXES
+_CURRENT_EXPECTED_PRIMARY_KEYS = _EXPECTED_PRIMARY_KEYS
+_CURRENT_EXPECTED_FOREIGN_KEYS = _EXPECTED_FOREIGN_KEYS
+_CURRENT_EXPECTED_UNIQUES = _EXPECTED_UNIQUES
+_CURRENT_EXPECTED_FINITE_CHECKS = _EXPECTED_FINITE_CHECKS
+
+_EXPECTED_TABLES = tuple(
+ table for table in _EXPECTED_TABLES if table != "refresh_token_families"
+)
+_EXPECTED_INDEXES = tuple(
+ item
+ for item in _EXPECTED_INDEXES
+ if item[1]
+ not in {
+ "idx_refresh_family_retain",
+ "idx_refresh_family_user_state_exp",
+ "idx_refresh_family_generation",
+ "uq_refresh_token_one_active",
+ }
+)
+_EXPECTED_PRIMARY_KEYS = tuple(
+ item
+ for item in _EXPECTED_PRIMARY_KEYS
+ if item[0] != "refresh_token_families"
+)
+_EXPECTED_FOREIGN_KEYS = tuple(
+ item
+ for item in _EXPECTED_FOREIGN_KEYS
+ if item[1]
+ not in {
+ "fk_refresh_family_user",
+ "fk_refresh_token_family_owner",
+ "fk_refresh_token_parent",
+ }
+)
+_EXPECTED_UNIQUES = tuple(
+ item
+ for item in _EXPECTED_UNIQUES
+ if item[1]
+ not in {
+ "uq_refresh_family_owner",
+ "uq_refresh_token_family_generation",
+ "uq_refresh_token_family_hash",
+ "uq_refresh_token_parent",
+ }
+)
+_EXPECTED_FINITE_CHECKS = tuple(
+ item
+ for item in _EXPECTED_FINITE_CHECKS
+ if item[0] != "refresh_token_families"
+ and not (item[0] == "refresh_tokens" and item[1] == "revoked_at")
+)
+
def _finite_check_name(table: str, column: str) -> str:
if table == "module_runs":
@@ -257,6 +486,15 @@ def _finite_check_name(table: str, column: str) -> str:
return "ck_audit_log_timestamp_finite"
if table == "rate_limit_events":
return "ck_rate_limit_events_timestamp_finite"
+ if table == "refresh_tokens" and column == "revoked_at":
+ return "ck_refresh_token_revoked_finite"
+ if table == "refresh_token_families":
+ return {
+ "created_at": "ck_refresh_family_created_finite",
+ "absolute_expires_at": "ck_refresh_family_expires_finite",
+ "revoked_at": "ck_refresh_family_revoked_finite",
+ "retain_until": "ck_refresh_family_retain_finite",
+ }[column]
return f"ck_{table}_{column}_finite"
@@ -336,7 +574,7 @@ def _table_rows() -> list[dict[str, object]]:
"user_trigger_count": 0,
"user_rule_count": 0,
}
- for position, table in enumerate(_EXPECTED_TABLES)
+ for position, table in enumerate(_CURRENT_EXPECTED_TABLES)
]
@@ -349,7 +587,7 @@ def _index_rows() -> list[dict[str, object]]:
"index_relpersistence": "p",
"index_is_partition": False,
"access_method": "btree",
- "indisunique": False,
+ "indisunique": name == "uq_refresh_token_one_active",
"indisprimary": False,
"indisvalid": True,
"indisready": True,
@@ -358,13 +596,21 @@ def _index_rows() -> list[dict[str, object]]:
"indnatts": len(columns),
"columns": list(columns),
"column_options": [0] * len(columns),
- "operator_classes": [opclass] * len(columns),
+ "operator_classes": (
+ list(opclass)
+ if isinstance(opclass, tuple)
+ else [opclass] * len(columns)
+ ),
"operator_class_namespaces": ["pg_catalog"] * len(columns),
"column_collations_match": [True] * len(columns),
"expressions": None,
- "predicate": None,
+ "predicate": (
+ "(state = 'active'::text)"
+ if name == "uq_refresh_token_one_active"
+ else None
+ ),
}
- for table, name, columns, opclass in _EXPECTED_INDEXES
+ for table, name, columns, opclass in _CURRENT_EXPECTED_INDEXES
]
@@ -389,7 +635,7 @@ def _primary_rows() -> list[dict[str, object]]:
"indislive": True,
}
for position, (table, name, columns) in enumerate(
- _EXPECTED_PRIMARY_KEYS
+ _CURRENT_EXPECTED_PRIMARY_KEYS
)
]
@@ -404,7 +650,19 @@ def _managed_constraint_rows() -> list[dict[str, object]]:
remote,
on_delete,
delete_code,
- ) in enumerate(_EXPECTED_FOREIGN_KEYS, start=1):
+ ) in enumerate(_CURRENT_EXPECTED_FOREIGN_KEYS, start=1):
+ reference_index_name = {
+ "fk_refresh_token_family_owner": "uq_refresh_family_owner",
+ "fk_refresh_token_parent": "uq_refresh_token_family_hash",
+ }.get(name, f"{parent}_pkey")
+ parent_is_deferred = name == "fk_refresh_token_parent"
+ definition = (
+ f"FOREIGN KEY ({', '.join(local)}) "
+ f"REFERENCES {parent}({', '.join(remote)}) "
+ f"ON DELETE {on_delete}"
+ )
+ if parent_is_deferred:
+ definition += " DEFERRABLE INITIALLY DEFERRED"
rows.append(
{
"source_schema": "public",
@@ -412,14 +670,10 @@ def _managed_constraint_rows() -> list[dict[str, object]]:
"conname": name,
"contype": "f",
"convalidated": True,
- "condeferrable": False,
- "condeferred": False,
+ "condeferrable": parent_is_deferred,
+ "condeferred": parent_is_deferred,
"constraint_index_oid": 2000 + position,
- "definition": (
- f"FOREIGN KEY ({', '.join(local)}) "
- f"REFERENCES {parent}({', '.join(remote)}) "
- f"ON DELETE {on_delete}"
- ),
+ "definition": definition,
"referenced_schema": "public",
"referenced_table": parent,
"confupdtype": "a",
@@ -427,13 +681,13 @@ def _managed_constraint_rows() -> list[dict[str, object]]:
"local_columns": list(local),
"remote_columns": list(remote),
"index_schema": "public",
- "index_name": f"{parent}_pkey",
+ "index_name": reference_index_name,
"index_relkind": "i",
"index_relpersistence": "p",
"index_is_partition": False,
"access_method": "btree",
"indisunique": True,
- "indisprimary": True,
+ "indisprimary": reference_index_name.endswith("_pkey"),
"indisvalid": True,
"indisready": True,
"indislive": True,
@@ -449,7 +703,7 @@ def _managed_constraint_rows() -> list[dict[str, object]]:
}
)
for position, (table, name, columns) in enumerate(
- _EXPECTED_UNIQUES,
+ _CURRENT_EXPECTED_UNIQUES,
start=1,
):
rows.append(
@@ -484,14 +738,20 @@ def _managed_constraint_rows() -> list[dict[str, object]]:
"indnatts": len(columns),
"index_columns": list(columns),
"column_options": [0] * len(columns),
- "operator_classes": ["text_ops"] * len(columns),
+ "operator_classes": [
+ "int8_ops"
+ if table == "refresh_tokens"
+ and column == "generation"
+ else "text_ops"
+ for column in columns
+ ],
"operator_class_namespaces": ["pg_catalog"] * len(columns),
"column_collations_match": [True] * len(columns),
"expressions": None,
"predicate": None,
}
)
- for table, column, nullable in _EXPECTED_FINITE_CHECKS:
+ for table, column, nullable in _CURRENT_EXPECTED_FINITE_CHECKS:
name = _finite_check_name(table, column)
expression = (
f"{column} IS NULL OR isfinite({column})"
@@ -547,6 +807,17 @@ def _managed_constraint_rows() -> list[dict[str, object]]:
}
)
rows.append(blocked)
+ for table, name, column, definition in _EXPECTED_TOKEN_CHECKS:
+ token_check = deepcopy(blocked)
+ token_check.update(
+ {
+ "table_name": table,
+ "conname": name,
+ "definition": definition,
+ "local_columns": [column],
+ }
+ )
+ rows.append(token_check)
return rows
@@ -587,7 +858,7 @@ class _PureManagedConnection:
self,
*,
revision_present: bool = True,
- revision_values: tuple[object, ...] = ("0008",),
+ revision_values: tuple[object, ...] = ("0009",),
) -> None:
self.revision_present = revision_present
self.revision_values = revision_values
@@ -873,7 +1144,7 @@ async def _run_init(
return validated
[email protected]("revision", ["0001", "0004", "0007"])
[email protected]("revision", ["0001", "0004", "0007", "0008"])
def test_revision_classifier_requires_migration_for_known_older_heads(
revision: str,
) -> None:
@@ -894,10 +1165,10 @@ def test_revision_classifier_requires_migration_for_known_older_heads(
(),
(None,),
("",),
- ("0008", "0008"),
- ("0008", "0007"),
+ ("0009", "0009"),
+ ("0009", "0008"),
("9999",),
- (" 0008",),
+ (" 0009",),
],
)
def test_revision_classifier_rejects_malformed_or_unknown_state(
@@ -915,7 +1186,7 @@ def test_revision_classifier_rejects_malformed_or_unknown_state(
def test_revision_classifier_accepts_only_exact_managed_head() -> None:
- accepted = _classify_postgres_revision(("0008",)) == "0008"
+ accepted = _classify_postgres_revision(("0009",)) == "0009"
_require_fixed(accepted, "managed PostgreSQL revision was rejected")
@@ -942,14 +1213,18 @@ def test_postgres_constraint_normalization_preserves_literal_case() -> None:
@pytest.mark.asyncio
-async def test_unversioned_database_retains_runtime_fallback(
+async def test_unversioned_database_requires_migration_without_fallback(
monkeypatch: pytest.MonkeyPatch,
) -> None:
connection = _PureManagedConnection(revision_present=False)
- validated = await _run_init(monkeypatch, connection)
+ observed = ""
+ try:
+ await _run_init(monkeypatch, connection)
+ except RuntimeError as exc:
+ observed = str(exc)
_require_fixed(
- connection.fallback_count == 1 and validated == 1,
- "unversioned PostgreSQL fallback behavior changed",
+ observed == _MIGRATION_REQUIRED and connection.fallback_count == 0,
+ "unversioned PostgreSQL startup did not require migration",
)
@@ -1327,7 +1602,7 @@ async def test_managed_inventory_rejects_catalog_drift(
@pytest.mark.parametrize(
"revision_values",
- [("0003",), (), ("unknown",), ("0008", "0007")],
+ [("0003",), (), ("unknown",), ("0009", "0008")],
)
@pytest.mark.asyncio
async def test_versioned_failure_never_enters_runtime_fallback(
@@ -1507,6 +1782,7 @@ async def test_real_postgres_managed_startup_preserves_unrelated_objects(
"Managed-startup fixture must reach revision 0007 before 0008",
)
await harness._alembic(target, "upgrade", "0008")
+ await harness._alembic(target, "upgrade", "0009")
connection = await harness._connect(target)
try:
await connection.execute(
@@ -1528,7 +1804,7 @@ async def test_real_postgres_managed_startup_preserves_unrelated_objects(
"""
SELECT
(
- SELECT version_num='0008'
+ SELECT version_num='0009'
FROM alembic_version
) AS managed,
(
@@ -1568,7 +1844,7 @@ async def test_real_postgres_older_revision_requires_migration_and_recovers(
from tests.integration import test_postgres_migration_portability as harness
async with harness._postgres_harness() as target:
- await harness._alembic(target, "upgrade", "0007")
+ await harness._alembic(target, "upgrade", "0008")
pools = _audit_runtime_pools(monkeypatch)
database = _runtime_database(target)
observed = await _fixed_connect_result(database)
@@ -1580,7 +1856,7 @@ async def test_real_postgres_older_revision_requires_migration_and_recovers(
and pools[0].close_count == 1
)
- await harness._alembic(target, "upgrade", "0008")
+ await harness._alembic(target, "upgrade", "0009")
try:
recovered_state = (
await _fixed_connect_result(database) == "connected"
@@ -1617,24 +1893,24 @@ async def test_real_postgres_invalid_revision_state_closes_and_recovers(
operations = {
"empty": (
"DELETE FROM alembic_version",
- "INSERT INTO alembic_version(version_num) VALUES('0008')",
+ "INSERT INTO alembic_version(version_num) VALUES('0009')",
),
"multiple": (
"INSERT INTO alembic_version(version_num) VALUES('0007')",
"DELETE FROM alembic_version WHERE version_num='0007'",
),
"malformed": (
- "UPDATE alembic_version SET version_num=' 0008'",
- "UPDATE alembic_version SET version_num='0008'",
+ "UPDATE alembic_version SET version_num=' 0009'",
+ "UPDATE alembic_version SET version_num='0009'",
),
"unknown": (
"UPDATE alembic_version SET version_num='9999'",
- "UPDATE alembic_version SET version_num='0008'",
+ "UPDATE alembic_version SET version_num='0009'",
),
}
mutation, repair = operations[revision_state]
async with harness._postgres_harness() as target:
- await harness._alembic(target, "upgrade", "0008")
+ await harness._alembic(target, "upgrade", "0009")
connection = await harness._connect(target)
try:
await connection.execute(mutation)
@@ -1862,7 +2138,7 @@ async def test_real_postgres_managed_catalog_drift_never_falls_back(
}
statement = statements[drift]
async with harness._postgres_harness() as target:
- await harness._alembic(target, "upgrade", "0008")
+ await harness._alembic(target, "upgrade", "0009")
connection = await harness._connect(target)
try:
await connection.execute(statement)
@@ -1883,7 +2159,7 @@ async def test_real_postgres_managed_catalog_drift_never_falls_back(
@pytest.mark.asyncio
-async def test_real_postgres_unversioned_startup_uses_runtime_fallback(
+async def test_real_postgres_unversioned_startup_requires_migration(
monkeypatch: pytest.MonkeyPatch,
) -> None:
_postgres_test_config()
@@ -1892,44 +2168,46 @@ async def test_real_postgres_unversioned_startup_uses_runtime_fallback(
async with harness._postgres_harness() as target:
pools = _audit_runtime_pools(monkeypatch)
database = _runtime_database(target)
+ observed = await _fixed_connect_result(database)
+ connection = await harness._connect(target)
try:
- connected = await _fixed_connect_result(database) == "connected"
- async with database._pool.acquire() as connection:
- state = await connection.fetchrow(
- """
- SELECT
- to_regclass('alembic_version') IS NULL AS unversioned,
- to_regclass('campaigns') IS NOT NULL AS runtime_created,
- to_regclass('websocket_tickets') IS NOT NULL
- AS tickets_created
- """
- )
- created = (
- state is not None
- and bool(state["unversioned"])
- and bool(state["runtime_created"])
- and bool(state["tickets_created"])
- )
+ state = await connection.fetchrow(
+ """
+ SELECT
+ to_regclass('alembic_version') IS NULL AS unversioned,
+ to_regclass('campaigns') IS NULL AS no_campaigns,
+ to_regclass('websocket_tickets') IS NULL AS no_tickets
+ """
+ )
finally:
- await database.close()
+ await connection.close()
+ unchanged = (
+ state is not None
+ and bool(state["unversioned"])
+ and bool(state["no_campaigns"])
+ and bool(state["no_tickets"])
+ )
_require_fixed(
- connected
- and created
+ observed == _MIGRATION_REQUIRED
+ and unchanged
+ and database._pool is None
and len(pools) == 1
- and pools[0].fallback_count == 1
+ and pools[0].fallback_count == 0
and pools[0].close_count == 1,
- "unversioned PostgreSQL runtime fallback changed",
+ "unversioned PostgreSQL startup did not fail closed",
)
async def _stamp_runtime_origin_0007(target: Any) -> None:
- database = _runtime_database(target)
- try:
- await database.connect()
- finally:
- await database.close()
+ from ares.db.postgres import (
+ _PG_CREATE_TABLES,
+ _POSTGRES_FALLBACK_STATEMENT_SPANS,
+ )
+
connection = await target_support_connect(target)
try:
+ for _code, start, end in _POSTGRES_FALLBACK_STATEMENT_SPANS:
+ await connection.execute(_PG_CREATE_TABLES[start:end])
await connection.execute(
"""
CREATE TABLE alembic_version(
@@ -2634,6 +2912,7 @@ async def test_real_postgres_runtime_origin_converges_without_data_loss(
)
finally:
await connection.close()
+ await harness._alembic(target, "upgrade", "0009")
pools = _audit_runtime_pools(monkeypatch)
database = _runtime_database(target)
try:
@@ -2663,6 +2942,9 @@ async def test_real_postgres_supported_legacy_objects_converge(
connection = await harness._connect(target)
try:
await harness._seed_postgres_contract(connection)
+ await connection.execute(
+ "UPDATE refresh_tokens SET id=repeat('a', 64)"
+ )
await connection.execute(
"""
DROP TABLE module_runs;
@@ -2684,17 +2966,14 @@ async def test_real_postgres_supported_legacy_objects_converge(
await connection.close()
await harness._alembic(target, "upgrade", "0008")
- pools = _audit_runtime_pools(monkeypatch)
- database = _runtime_database(target)
- connected = await _fixed_connect_result(database) == "connected"
+ connection = await harness._connect(target)
try:
- async with database._pool.acquire() as connection:
- after_data = await _application_data_digest(
- connection,
- excluded_tables=frozenset({"module_runs"}),
- )
- state = await connection.fetchrow(
- """
+ after_data = await _application_data_digest(
+ connection,
+ excluded_tables=frozenset({"module_runs"}),
+ )
+ state = await connection.fetchrow(
+ """
SELECT
(
SELECT version_num='0008'
@@ -2734,19 +3013,26 @@ async def test_real_postgres_supported_legacy_objects_converge(
FROM ares_m0008_unrelated_probe
WHERE id=1
) AS unrelated_preserved
- """
- )
- converged = (
- state is not None
- and bool(state["revision_current"])
- and bool(state["module_table_present"])
- and bool(state["module_fk_present"])
- and bool(state["module_check_present"])
- and bool(state["module_indexes_exact"])
- and bool(state["obsolete_index_removed"])
- and bool(state["unrelated_preserved"])
- and before_data == after_data
- )
+ """
+ )
+ converged = (
+ state is not None
+ and bool(state["revision_current"])
+ and bool(state["module_table_present"])
+ and bool(state["module_fk_present"])
+ and bool(state["module_check_present"])
+ and bool(state["module_indexes_exact"])
+ and bool(state["obsolete_index_removed"])
+ and bool(state["unrelated_preserved"])
+ and before_data == after_data
+ )
+ finally:
+ await connection.close()
+ await harness._alembic(target, "upgrade", "0009")
+ pools = _audit_runtime_pools(monkeypatch)
+ database = _runtime_database(target)
+ try:
+ connected = await _fixed_connect_result(database) == "connected"
finally:
await database.close()
_require_fixed(
diff --git a/tests/integration/test_postgres_unversioned_adoption.py b/tests/integration/test_postgres_unversioned_adoption.py
index d69dc5a..3e40588 100644
--- a/tests/integration/test_postgres_unversioned_adoption.py
+++ b/tests/integration/test_postgres_unversioned_adoption.py
@@ -16,7 +16,6 @@ from sqlalchemy.ext.asyncio import create_async_engine
from ares.db.migrations import adoption
from ares.db.migrations.adoption import AdoptionExit, AdoptionFailure
-from ares.db.postgres import PostgresDatabase
_ENV = (
"ARES_TEST_POSTGRES_HOST",
@@ -113,16 +112,20 @@ async def _database() -> AsyncIterator[str]:
async def _runtime(url: str, generation: int) -> None:
- database = PostgresDatabase(url)
- await database.connect()
- await database.close()
- if generation == 6:
- engine = create_async_engine(url, poolclass=sa.pool.NullPool)
- try:
- async with engine.begin() as connection:
+ from ares.db.postgres import (
+ _PG_CREATE_TABLES,
+ _POSTGRES_FALLBACK_STATEMENT_SPANS,
+ )
+
+ engine = create_async_engine(url, poolclass=sa.pool.NullPool)
+ try:
+ async with engine.begin() as connection:
+ for _code, start, end in _POSTGRES_FALLBACK_STATEMENT_SPANS:
+ await connection.exec_driver_sql(_PG_CREATE_TABLES[start:end])
+ if generation == 6:
await connection.exec_driver_sql("DROP TABLE websocket_tickets")
- finally:
- await engine.dispose()
+ finally:
+ await engine.dispose()
async def _revision(url: str) -> str | None:
@@ -206,8 +209,8 @@ async def test_real_postgres_generation_adopts_atomically(
predecessor,
None,
AdoptionExit.OK,
- "0008",
- "ARES-M2B-ALREADY-MANAGED:0008",
+ "0009",
+ "ARES-M2B-ALREADY-MANAGED:0009",
)
@@ -355,6 +358,6 @@ async def test_real_postgres_adoption_rerun_is_verified_noop(
revision = await _revision(url)
assert (first.exit_code, second.diagnostic, revision) == (
AdoptionExit.OK,
- "ARES-M2B-ALREADY-MANAGED:0008",
- "0008",
+ "ARES-M2B-ALREADY-MANAGED:0009",
+ "0009",
)
diff --git a/tests/integration/test_postgres_websocket_tickets.py b/tests/integration/test_postgres_websocket_tickets.py
index 56c4483..bc6921e 100644
--- a/tests/integration/test_postgres_websocket_tickets.py
+++ b/tests/integration/test_postgres_websocket_tickets.py
@@ -2,7 +2,9 @@
from __future__ import annotations
import asyncio
+import base64
import contextlib
+import hashlib
import multiprocessing
import os
import re
@@ -40,7 +42,7 @@ _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", "0008"})
+_MIGRATION_REVISIONS = frozenset({"0006", "0007", "0008", "0009"})
_OWNED_MIGRATION_PROCESSES: set[Any] = set()
@@ -617,6 +619,7 @@ async def _postgres_harness(
database = PostgresDatabase(dsn, pool_min=1, pool_max=8)
if initialize_runtime:
try:
+ _run_ticket_migration(test_database, "upgrade", "0009")
await _bounded_operation(
"runtime-initialize",
database.connect(),
@@ -705,6 +708,20 @@ async def _seed_identity(
(other_campaign_id, "Other campaign", username),
),
)
+ now = datetime.now(timezone.utc)
+ await connection.execute(
+ """
+ INSERT INTO refresh_token_families(
+ id,user_id,auth_epoch,state,created_at,
+ absolute_expires_at,retain_until
+ ) VALUES($1,$2,1,'active',$3,$4,$5)
+ """,
+ _test_family_id(user_id),
+ user_id,
+ now,
+ now + timedelta(days=30),
+ now + timedelta(days=60),
+ )
api_key_id = (
await database.create_api_key(
user_id,
@@ -715,12 +732,19 @@ async def _seed_identity(
return user_id, username, campaign_id, other_campaign_id, api_key_id
+def _test_family_id(user_id: str) -> str:
+ digest = hashlib.sha256(b"ARES-PG-WS-TEST-FAMILY\0" + user_id.encode()).digest()
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+
+
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),
+ family_id=_test_family_id(user_id),
+ auth_epoch=1,
)
@@ -769,6 +793,8 @@ _EXPECTED_TICKET_COLUMNS = (
True,
None,
),
+ ("bearer_family_id", "text", False, "", "", True, None),
+ ("bearer_auth_epoch", "bigint", False, "", "", True, None),
)
_EXPECTED_TICKET_CHECKS = (
@@ -807,12 +833,17 @@ _EXPECTED_TICKET_CHECKS = (
"AND length(btrim(bearer_jti)) > 0 "
"AND bearer_jti = btrim(bearer_jti) "
"AND bearer_expires_at IS NOT NULL "
+ "AND bearer_family_id IS NOT NULL "
+ "AND bearer_auth_epoch IS NOT NULL "
+ "AND bearer_auth_epoch >= 1 "
"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 bearer_family_id IS NULL "
+ "AND bearer_auth_epoch IS NULL "
"AND api_key_id IS NOT NULL "
"AND length(btrim(api_key_id)) > 0 "
"AND api_key_id = btrim(api_key_id) "
@@ -834,6 +865,14 @@ _EXPECTED_TICKET_FOREIGN_KEYS = (
"a",
"c",
),
+ (
+ "fk_ws_ticket_bearer_family",
+ ("bearer_family_id", "user_id"),
+ "refresh_token_families",
+ ("id", "user_id"),
+ "a",
+ "c",
+ ),
(
"fk_ws_ticket_campaign",
("campaign_id",),
@@ -870,6 +909,23 @@ _EXPECTED_TICKET_INDEXES = (
None,
None,
),
+ (
+ "idx_ws_tickets_bearer_family",
+ "btree",
+ False,
+ False,
+ True,
+ True,
+ True,
+ 1,
+ 1,
+ ("bearer_family_id",),
+ (0,),
+ ("text_ops",),
+ (True,),
+ None,
+ None,
+ ),
(
"idx_ws_tickets_campaign",
"btree",
@@ -949,6 +1005,14 @@ _EXPECTED_TICKET_INDEX_IDENTITIES = (
("text_ops",),
("pg_catalog",),
),
+ (
+ "idx_ws_tickets_bearer_family",
+ "i",
+ "p",
+ False,
+ ("text_ops",),
+ ("pg_catalog",),
+ ),
(
"idx_ws_tickets_campaign",
"i",
@@ -1339,11 +1403,65 @@ def _ticket_catalog_matches_fixed_contract(
for binding in fingerprint.get("index_bindings", ())
}
)
- == 5
+ == 6
and all(
binding[1] == fingerprint.get("relation_oid")
for binding in fingerprint.get("constraint_bindings", ())
)
+ and fingerprint.get("constraint_count") == 16
+ )
+
+
+def _ticket_catalog_matches_revision_0007_contract(
+ fingerprint: dict[str, object],
+) -> bool:
+ old_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)"
+ )
+ old_checks = tuple(
+ (name, old_source_shape if name == "ck_ws_ticket_source_shape" else definition)
+ for name, definition in _EXPECTED_TICKET_CHECKS
+ )
+ old_foreign_keys = tuple(
+ item
+ for item in _EXPECTED_TICKET_FOREIGN_KEYS
+ if item[0] != "fk_ws_ticket_bearer_family"
+ )
+ old_indexes = tuple(
+ item
+ for item in _EXPECTED_TICKET_INDEXES
+ if item[0] != "idx_ws_tickets_bearer_family"
+ )
+ old_identities = tuple(
+ item
+ for item in _EXPECTED_TICKET_INDEX_IDENTITIES
+ if item[0] != "idx_ws_tickets_bearer_family"
+ )
+ return (
+ fingerprint.get("relation")
+ == ("r", "p", False, False, False, 0, 0, 0, 0, 0)
+ and fingerprint.get("columns") == _EXPECTED_TICKET_COLUMNS[:12]
+ and fingerprint.get("checks") == old_checks
+ and fingerprint.get("foreign_keys") == old_foreign_keys
+ and fingerprint.get("primary")
+ == (("websocket_tickets_pkey", ("ticket_hash",), True, False, False),)
+ and fingerprint.get("indexes") == old_indexes
+ and fingerprint.get("index_identities") == old_identities
+ and len(fingerprint.get("index_bindings", ())) == 5
and fingerprint.get("constraint_count") == 15
)
@@ -2409,6 +2527,8 @@ class _ConnectionProxy:
"BEARER_SUBJECT",
"BEARER_JTI",
"BEARER_EXPIRES_AT",
+ "BEARER_FAMILY_ID",
+ "BEARER_AUTH_EPOCH",
"API_KEY_ID",
"REQUIRED_SCOPE",
)
@@ -2603,6 +2723,8 @@ class _PureTicketConnection:
"bearer_jti": "synthetic-jti",
"bearer_expires_at": datetime.now(timezone.utc)
+ timedelta(minutes=1),
+ "bearer_family_id": _test_family_id("synthetic-user"),
+ "bearer_auth_epoch": 1,
"api_key_id": None,
"required_scope": None,
}
@@ -3031,7 +3153,6 @@ async def test_postgres_revision_0007_ownership_and_0008_compatibility(
_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(
"""
@@ -3059,7 +3180,9 @@ async def test_postgres_revision_0007_ownership_and_0008_compatibility(
for name in ("users", "campaigns", "api_keys")
)
and migration_catalog is not None
- and _ticket_catalog_matches_fixed_contract(migration_catalog)
+ and _ticket_catalog_matches_revision_0007_contract(
+ migration_catalog
+ )
)
_require_fixed(
upgraded,
@@ -3102,7 +3225,6 @@ async def test_postgres_revision_0007_ownership_and_0008_compatibility(
_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(
"""
@@ -3129,7 +3251,9 @@ async def test_postgres_revision_0007_ownership_and_0008_compatibility(
int(final_state[name]) == 1
for name in ("users", "campaigns", "api_keys")
)
- and _ticket_catalog_matches_fixed_contract(reupgraded_catalog)
+ and _ticket_catalog_matches_revision_0007_contract(
+ reupgraded_catalog
+ )
)
_require_fixed(
final_state_is_exact,
@@ -3213,7 +3337,9 @@ async def test_postgres_revision_0007_ownership_and_0008_compatibility(
int(head_state[name]) == 1
for name in ("users", "campaigns", "api_keys")
)
- and _ticket_catalog_matches_fixed_contract(migration_catalog)
+ and _ticket_catalog_matches_revision_0007_contract(
+ migration_catalog
+ )
and migration_catalog == ticket_catalog_before_0008
and tuple(ticket_rows_after_0008)
== tuple(ticket_rows_before_0008)
@@ -3223,6 +3349,55 @@ async def test_postgres_revision_0007_ownership_and_0008_compatibility(
"revision 0008 changed the revision 0007 ticket contract",
)
+ _run_ticket_migration(harness.database_name, "upgrade", "0009")
+ connection = await _connect()
+ try:
+ await PostgresDatabase._validate_websocket_ticket_schema(connection)
+ migration_catalog = await _ticket_catalog_fingerprint(connection)
+ ticket_rows_after_0009 = await connection.fetch(
+ """
+ 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
+ """
+ )
+ current_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-0009-close",
+ connection.close,
+ [],
+ )
+ revision_0009_is_current = (
+ current_state is not None
+ and current_state["revision"] == "0009"
+ and all(
+ int(current_state[name]) == 1
+ for name in ("users", "campaigns", "api_keys")
+ )
+ and _ticket_catalog_matches_fixed_contract(migration_catalog)
+ and tuple(ticket_rows_after_0009)
+ == tuple(ticket_rows_before_0008)
+ )
+ _require_fixed(
+ revision_0009_is_current,
+ "revision 0009 ticket 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)
@@ -3886,7 +4061,10 @@ async def _ticket_rows_for_metadata_mutation(
async def test_postgres_rejects_security_altering_relation_metadata(
mutation: str,
) -> None:
- from ares.db.postgres import _PostgresStartupDiagnosticError
+ from ares.db.postgres import (
+ _PostgresManagedSchemaError,
+ _PostgresStartupDiagnosticError,
+ )
async with _postgres_harness() as harness:
database = harness.database
@@ -3966,7 +4144,7 @@ async def test_postgres_rejects_security_altering_relation_metadata(
)
failure_type: type[BaseException] | None = None
- fixed_message = False
+ failure_is_sanitized = False
try:
await asyncio.wait_for(
candidate.connect(),
@@ -3975,8 +4153,13 @@ async def test_postgres_rejects_security_altering_relation_metadata(
candidate_connected = True
except Exception as exc:
failure_type = type(exc)
- fixed_message = (
- str(exc) == "Incompatible WebSocket ticket schema"
+ failure_is_sanitized = (
+ failure_type is _PostgresStartupDiagnosticError
+ and str(exc) == "Incompatible WebSocket ticket schema"
+ ) or (
+ failure_type is _PostgresManagedSchemaError
+ and str(exc)
+ == "Incompatible managed PostgreSQL schema"
)
pool_was_cleared = candidate._pool is None
@@ -4008,8 +4191,7 @@ async def test_postgres_rejects_security_altering_relation_metadata(
_require_fixed(
mutation_exists
and trigger_would_enable_replay
- and failure_type is _PostgresStartupDiagnosticError
- and fixed_message
+ and failure_is_sanitized
and pool_was_cleared
and startup_preserved_state
and observer_reusable,
diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.py
index 9410dbb..1c2bb16 100644
--- a/tests/unit/test_api_endpoints.py
+++ b/tests/unit/test_api_endpoints.py
@@ -17,6 +17,8 @@ Note on POST body tests (register, campaigns create, change-password):
from __future__ import annotations
import asyncio
+import base64
+import hashlib
import os
from types import SimpleNamespace
from typing import Any
@@ -50,8 +52,11 @@ def _make_token(username: str, role: str) -> str:
_MOCK_PRINCIPAL_ROLES[username] = role
s = _settings()
+ family_id = base64.urlsafe_b64encode(
+ hashlib.sha256(username.encode("utf-8")).digest()
+ ).rstrip(b"=").decode("ascii")
return create_access_token(
- data={"sub": username, "role": role},
+ data={"sub": username, "sid": family_id, "ver": 1},
secret_key=s.secret_key_value,
expires_minutes=60,
)
@@ -61,6 +66,36 @@ def _auth(username: str, role: str) -> dict:
return {"Authorization": f"Bearer {_make_token(username, role)}"}
+def _issued_session(username: str = "admin", role: str = "team_lead"):
+ from ares.core.security import create_access_token
+ from ares.core.token_sessions import (
+ IssuedTokenSession,
+ SessionIssueResult,
+ SessionIssueStatus,
+ )
+
+ family_id = base64.urlsafe_b64encode(
+ hashlib.sha256(username.encode("utf-8")).digest()
+ ).rstrip(b"=").decode("ascii")
+ token = create_access_token(
+ {"sub": username, "sid": family_id, "ver": 1},
+ _settings().secret_key_value,
+ )
+ return SessionIssueResult(
+ SessionIssueStatus.ISSUED,
+ IssuedTokenSession(
+ access_token=token,
+ refresh_token="test-refresh-token", # noqa: S106 - fixed test value
+ user_id="test-user-id",
+ subject=username,
+ family_id=family_id,
+ auth_epoch=1,
+ refresh_generation=0,
+ role=role,
+ ),
+ )
+
+
def _api_key_headers(raw_key: str = "ares_test_api_key") -> dict:
return {"X-API-Key": raw_key}
@@ -83,6 +118,15 @@ def _api_key_record(
def _make_mock_db():
+ from ares.core.token_sessions import (
+ RefreshRotationResult,
+ RefreshRotationStatus,
+ SessionIssueResult,
+ SessionIssueStatus,
+ SessionRevocationResult,
+ SessionRevocationStatus,
+ )
+
db = MagicMock()
db.verify_user = AsyncMock(return_value=None)
db.get_user = AsyncMock(return_value=None)
@@ -93,17 +137,37 @@ def _make_mock_db():
db.revoke_all_refresh_tokens = AsyncMock()
db.revoke_access_token = AsyncMock()
db.is_access_token_revoked = AsyncMock(return_value=False)
+ db.create_login_session = AsyncMock(
+ return_value=SessionIssueResult(SessionIssueStatus.INVALID)
+ )
+ db.rotate_refresh_session = AsyncMock(
+ return_value=RefreshRotationResult(RefreshRotationStatus.INVALID)
+ )
+ db.revoke_current_session = AsyncMock(
+ return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED)
+ )
+ db.revoke_all_sessions = AsyncMock(
+ return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED)
+ )
+ db.apply_user_security_event = AsyncMock(return_value=True)
async def resolve_access_token_principal(
subject: str,
_jti: str,
+ _family_id: str,
+ auth_epoch: int,
) -> dict[str, str] | None:
if db.is_access_token_revoked.return_value is True:
return None
role = _MOCK_PRINCIPAL_ROLES.get(subject)
if role is None:
return None
- return {"id": f"mock-user-{subject}", "username": subject, "role": role}
+ return {
+ "id": f"mock-user-{subject}",
+ "username": subject,
+ "role": role,
+ "auth_epoch": auth_epoch,
+ }
db.resolve_access_token_principal = AsyncMock(
side_effect=resolve_access_token_principal
@@ -358,11 +422,7 @@ class TestAuthFlow:
"""Login with mocked OAuth2PasswordRequestForm — valid creds → 200 + tokens."""
c, db, _app = aclient
_reset_rate_limiter()
- db.verify_user.return_value = {
- "id": "u1",
- "username": "admin",
- "role": "team_lead",
- }
+ db.create_login_session.return_value = _issued_session()
class FakeForm:
username = "admin"
@@ -381,7 +441,7 @@ class TestAuthFlow:
assert body["token_type"] == "bearer" # noqa: S105 - OAuth token type
finally:
del _app.dependency_overrides[OAuth2PasswordRequestForm]
- db.verify_user.return_value = None
+ db.create_login_session.return_value = None
@pytest.mark.asyncio
async def test_unauthenticated_endpoint_returns_401(self, aclient):
@@ -430,8 +490,7 @@ class TestAuthFlow:
"""Response/handler mapping; real SQLite containment is covered below."""
c, db, _ = aclient
_reset_rate_limiter()
- db.rotate_refresh_token.return_value = (None, None)
- db.rotate_refresh_token.reset_mock()
+ db.rotate_refresh_session.reset_mock()
db.create_refresh_token.reset_mock()
response = await c.post(
@@ -447,7 +506,7 @@ class TestAuthFlow:
if not (
response.status_code == 401
and generic_failure
- and db.rotate_refresh_token.await_count == 1
+ and db.rotate_refresh_session.await_count == 1
and db.create_refresh_token.await_count == 0
):
pytest.fail(
@@ -2741,6 +2800,7 @@ class TestReportEndpoints:
from ares.api.server import get_db, get_engine
from ares.core.campaign import Campaign, Finding, NoiseProfile, ScopeEntry, Severity
from ares.core.engine import EngineModuleResult, ModuleStatus
+ from ares.core.security import create_access_token
from ares.db.database import AresDatabase
real_report_generator = report_gen.ReportGenerator
@@ -2750,6 +2810,18 @@ class TestReportEndpoints:
"SyntheticReportPrincipal1!",
"team_lead",
)
+ issued = await real_db.create_login_session(
+ "admin",
+ "SyntheticReportPrincipal1!",
+ lambda claims: create_access_token(
+ dict(claims),
+ _settings().secret_key_value,
+ ),
+ )
+ assert issued.session is not None
+ real_auth = {
+ "Authorization": f"Bearer {issued.session.access_token}"
+ }
original_db = getattr(app.state, "db", None)
campaign = Campaign(
name="AD Lab Attack Simulation",
@@ -2845,7 +2917,7 @@ class TestReportEndpoints:
}
asrep = await c.post(
f"/modules/ad.asreproast/run",
- headers=_auth("admin", "team_lead"),
+ headers=real_auth,
json={
"campaign_id": campaign.id,
"params": common_params,
@@ -2854,7 +2926,7 @@ class TestReportEndpoints:
)
kerb = await c.post(
f"/modules/ad.kerberoast/run",
- headers=_auth("admin", "team_lead"),
+ headers=real_auth,
json={
"campaign_id": campaign.id,
"params": {**common_params, "target_user": "svc-sql"},
@@ -2875,7 +2947,7 @@ class TestReportEndpoints:
findings_response = await c.get(
f"/campaigns/{campaign.id}/findings",
- headers=_auth("admin", "team_lead"),
+ headers=real_auth,
)
assert findings_response.status_code == 200
assert len(findings_response.json()) == 2
@@ -2898,7 +2970,7 @@ class TestReportEndpoints:
report_response = await c.post(
f"/reports/{campaign.id}?fmt=json",
- headers=_auth("admin", "team_lead"),
+ headers=real_auth,
)
finally:
app.dependency_overrides.pop(get_db, None)
@@ -3137,6 +3209,7 @@ class TestAuthoritativeHTTPBearerPrincipal:
@pytest.fixture
async def auth_runtime(self, tmp_path: Any):
from ares.api.server import app, get_db
+ from ares.core.security import create_access_token
from ares.db import database as database_module
from ares.db.database import AresDatabase
@@ -3148,7 +3221,16 @@ class TestAuthoritativeHTTPBearerPrincipal:
"SyntheticPrincipalPass1!",
"team_lead",
)
- token = _make_token(username, "team_lead")
+ issued = await database.create_login_session(
+ username,
+ "SyntheticPrincipalPass1!",
+ lambda claims: create_access_token(
+ dict(claims),
+ _settings().secret_key_value,
+ ),
+ )
+ assert issued.session is not None
+ token = issued.session.access_token
original_db = getattr(app.state, "db", None)
original_overrides = dict(app.dependency_overrides)
app.state.db = database
@@ -3201,11 +3283,11 @@ class TestAuthoritativeHTTPBearerPrincipal:
"expected an active bearer principal to reach the protected handler",
)
- await database.conn.execute(
- "UPDATE users SET is_active=0 WHERE id=?",
- (user_id,),
+ await database.apply_user_security_event(
+ user_id=user_id,
+ reason="user_status_change",
+ is_active=False,
)
- await database.conn.commit()
inactive_response = await client.get(
"/auth/me",
headers=self._bearer_headers(token),
@@ -3235,18 +3317,18 @@ class TestAuthoritativeHTTPBearerPrincipal:
"expected inactive bearer denial before protected handler work",
)
- await database.conn.execute(
- "UPDATE users SET is_active=1 WHERE id=?",
- (user_id,),
+ await database.apply_user_security_event(
+ user_id=user_id,
+ reason="user_status_change",
+ is_active=True,
)
- await database.conn.commit()
reactivated_response = await client.get(
"/auth/me",
headers=self._bearer_headers(token),
)
_require_fixed(
- reactivated_response.status_code == 200,
- "expected the same bearer token to work after reactivation",
+ reactivated_response.status_code == 401,
+ "expected status-change epoch revocation to remain authoritative",
)
await database.conn.execute(
@@ -3280,7 +3362,7 @@ class TestAuthoritativeHTTPBearerPrincipal:
self,
auth_runtime: Any,
) -> None:
- client, database, user_id, username, token, _ = auth_runtime
+ client, database, user_id, _username, token, _ = auth_runtime
_reset_rate_limiter()
list_calls = [0]
original_list_users = database.list_users
@@ -3304,7 +3386,6 @@ class TestAuthoritativeHTTPBearerPrincipal:
"expected current demoted role to block team-lead work",
)
- promoted_token = _make_token(username, "reporter")
await database.conn.execute(
"UPDATE users SET role='team_lead' WHERE id=?",
(user_id,),
@@ -3312,7 +3393,7 @@ class TestAuthoritativeHTTPBearerPrincipal:
await database.conn.commit()
promoted_response = await client.get(
"/security/users",
- headers=self._bearer_headers(promoted_token),
+ headers=self._bearer_headers(token),
)
_require_fixed(
promoted_response.status_code == 200 and list_calls[0] == 1,
@@ -3326,7 +3407,7 @@ class TestAuthoritativeHTTPBearerPrincipal:
await database.conn.commit()
invalid_role_response = await client.get(
"/auth/me",
- headers=self._bearer_headers(promoted_token),
+ headers=self._bearer_headers(token),
)
_require_fixed(
invalid_role_response.status_code == 401,
@@ -4150,13 +4231,21 @@ class TestMainWebSocketAuthoritativeLifetime:
"SyntheticWebSocketPass1!",
"team_lead",
)
- settings = _settings()
- token = create_access_token(
- {"sub": username, "role": "team_lead"},
- settings.secret_key_value,
- algorithm=settings.ares_jwt_algorithm,
- expires_minutes=60,
+ issued = await database.create_login_session(
+ username,
+ "SyntheticWebSocketPass1!",
+ lambda claims: create_access_token(
+ dict(claims),
+ _settings().secret_key_value,
+ algorithm=_settings().ares_jwt_algorithm,
+ expires_minutes=60,
+ ),
+ )
+ _require_fixed(
+ issued.session is not None,
+ "expected authoritative WebSocket login session",
)
+ token = issued.session.access_token
campaign = Campaign(
name="Synthetic WebSocket Campaign",
operator="separate-campaign-owner",
@@ -4533,11 +4622,17 @@ class TestMainWebSocketAuthoritativeLifetime:
import jwt
settings = _settings()
+ authoritative_claims = jwt.decode(
+ token,
+ settings.secret_key_value,
+ algorithms=[settings.ares_jwt_algorithm],
+ )
revocation_marker = "synthetic-main-websocket-revocation"
revoked_token = jwt.encode(
{
"sub": username,
- "role": "team_lead",
+ "sid": authoritative_claims["sid"],
+ "ver": authoritative_claims["ver"],
"jti": revocation_marker,
"exp": datetime.now(timezone.utc) + timedelta(hours=1),
},
@@ -5199,13 +5294,21 @@ class TestMainWebSocketAuthoritativeLifetime:
"SyntheticWebSocketPeer1!",
"team_lead",
)
- settings = _settings()
- peer_token = create_access_token(
- {"sub": "main-websocket-peer", "role": "team_lead"},
- settings.secret_key_value,
- algorithm=settings.ares_jwt_algorithm,
- expires_minutes=60,
+ peer_session = await database.create_login_session(
+ "main-websocket-peer",
+ "SyntheticWebSocketPeer1!",
+ lambda claims: create_access_token(
+ dict(claims),
+ _settings().secret_key_value,
+ algorithm=_settings().ares_jwt_algorithm,
+ expires_minutes=60,
+ ),
)
+ _require_fixed(
+ peer_session.session is not None,
+ "expected authoritative peer session",
+ )
+ peer_token = peer_session.session.access_token
first_socket, first_task = await _launch_main_websocket(
app,
campaign.id,
@@ -5256,13 +5359,21 @@ class TestMainWebSocketAuthoritativeLifetime:
"SyntheticAuthorizedPeerPass1!",
"team_lead",
)
- settings = _settings()
- peer_token = create_access_token(
- {"sub": "main-websocket-authorized-peer", "role": "team_lead"},
- settings.secret_key_value,
- algorithm=settings.ares_jwt_algorithm,
- expires_minutes=60,
+ peer_session = await database.create_login_session(
+ "main-websocket-authorized-peer",
+ "SyntheticAuthorizedPeerPass1!",
+ lambda claims: create_access_token(
+ dict(claims),
+ _settings().secret_key_value,
+ algorithm=_settings().ares_jwt_algorithm,
+ expires_minutes=60,
+ ),
+ )
+ _require_fixed(
+ peer_session.session is not None,
+ "expected authoritative peer session",
)
+ peer_token = peer_session.session.access_token
stale_socket, stale_task = await _launch_main_websocket(
app,
campaign.id,
diff --git a/tests/unit/test_refresh_token_families.py b/tests/unit/test_refresh_token_families.py
new file mode 100644
index 0000000..915125f
--- /dev/null
+++ b/tests/unit/test_refresh_token_families.py
@@ -0,0 +1,189 @@
+"""Deterministic SQLite and contract coverage for refresh-token families."""
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+import pytest
+
+from ares.core.security import create_access_token, decode_access_token
+from ares.core.token_sessions import (
+ RefreshRotationStatus,
+ SessionIssueStatus,
+ SessionRevocationStatus,
+ generate_family_id,
+ generate_refresh_token,
+ hash_refresh_token,
+ is_canonical_family_id,
+ is_canonical_refresh_hash,
+)
+from ares.db.database import AresDatabase
+
+
+def _require(value: bool, message: str) -> None:
+ if not value:
+ raise AssertionError(message)
+
+
+def _access_factory(_claims: object) -> str:
+ return "fixed-access-result"
+
+
+def test_family_and_refresh_contracts_are_canonical_and_confidential() -> None:
+ family_id = generate_family_id()
+ raw_token = generate_refresh_token()
+ token_hash = hash_refresh_token(raw_token)
+ invalid_family_values = (
+ family_id + "=",
+ " " + family_id,
+ family_id + " ",
+ family_id[:-1],
+ family_id + "A",
+ )
+ canonical = (
+ len(family_id) == 43
+ and is_canonical_family_id(family_id)
+ and all(not is_canonical_family_id(value) for value in invalid_family_values)
+ and len(token_hash) == 64
+ and is_canonical_refresh_hash(token_hash)
+ and not is_canonical_refresh_hash(token_hash.upper())
+ and raw_token not in repr(token_hash)
+ )
+ _require(canonical, "token-family canonical contract changed")
+
+
+def test_family_access_token_has_required_claims_and_no_role() -> None:
+ family_id = generate_family_id()
+ token = create_access_token(
+ {"sub": "fixed-subject", "sid": family_id, "ver": 7, "role": "admin"},
+ "fixed-test-secret-that-is-long-enough",
+ )
+ decoded = decode_access_token(
+ token,
+ "fixed-test-secret-that-is-long-enough",
+ )
+ claims_are_canonical = (
+ isinstance(decoded, dict)
+ and set(decoded) == {"sub", "sid", "ver", "exp", "iat", "jti"}
+ and decoded.get("sid") == family_id
+ and decoded.get("ver") == 7
+ and "role" not in decoded
+ )
+ _require(claims_are_canonical, "family access-token claims changed")
+
+ for claims in (
+ {"sub": "fixed-subject", "sid": family_id},
+ {"sub": "fixed-subject", "ver": 1},
+ {"sub": "fixed-subject", "sid": family_id + "=", "ver": 1},
+ {"sub": "fixed-subject", "sid": family_id, "ver": True},
+ ):
+ with pytest.raises(ValueError, match="invalid access token claims"):
+ create_access_token(claims, "fixed-test-secret-that-is-long-enough")
+
+
+async def test_sqlite_replay_revokes_only_the_replayed_device_family(
+ tmp_path,
+) -> None:
+ database = AresDatabase(str(tmp_path / "family-isolation.db"))
+ await database.connect()
+ try:
+ await database.create_user(
+ "family-user",
+ "FamilyPassword1!",
+ "operator",
+ )
+ first = await database.create_login_session(
+ "family-user",
+ "FamilyPassword1!",
+ _access_factory,
+ )
+ second = await database.create_login_session(
+ "family-user",
+ "FamilyPassword1!",
+ _access_factory,
+ )
+ _require(
+ first.status is SessionIssueStatus.ISSUED
+ and first.session is not None
+ and second.status is SessionIssueStatus.ISSUED
+ and second.session is not None
+ and first.session.family_id != second.session.family_id,
+ "login did not create isolated device families",
+ )
+ first_raw = first.session.refresh_token
+ first_family = first.session.family_id
+ second_family = second.session.family_id
+ rotated = await database.rotate_refresh_session(first_raw, _access_factory)
+ replayed = await database.rotate_refresh_session(first_raw, _access_factory)
+ first_authority = await database.resolve_access_token_principal(
+ "family-user",
+ "fixed-first-jti",
+ first_family,
+ 1,
+ )
+ second_authority = await database.resolve_access_token_principal(
+ "family-user",
+ "fixed-second-jti",
+ second_family,
+ 1,
+ )
+ safe_result = (
+ rotated.status is RefreshRotationStatus.ROTATED
+ and rotated.session is not None
+ and replayed.status is RefreshRotationStatus.REPLAYED
+ and first_authority is None
+ and second_authority is not None
+ )
+ _require(safe_result, "known replay did not isolate and revoke its family")
+ finally:
+ await database.close()
+
+
+async def test_sqlite_logout_all_increments_epoch_and_is_read_only_afterward(
+ tmp_path,
+) -> None:
+ database = AresDatabase(str(tmp_path / "logout-all.db"))
+ await database.connect()
+ try:
+ user_id = await database.create_user(
+ "epoch-user",
+ "EpochPassword1!",
+ "reporter",
+ )
+ issued = await database.create_login_session(
+ "epoch-user",
+ "EpochPassword1!",
+ _access_factory,
+ )
+ _require(
+ issued.session is not None,
+ "login did not create a family before logout-all",
+ )
+ family_id = issued.session.family_id
+ expires_at = datetime(2099, 1, 1, tzinfo=timezone.utc)
+ revoked = await database.revoke_all_sessions(
+ user_id=user_id,
+ jti="fixed-logout-jti",
+ expires_at=expires_at,
+ )
+ principal = await database.resolve_access_token_principal(
+ "epoch-user",
+ "fixed-read-jti",
+ family_id,
+ 1,
+ )
+ async with database.conn.execute(
+ "SELECT auth_epoch FROM users WHERE id=?",
+ (user_id,),
+ ) as cursor:
+ row = await cursor.fetchone()
+ _require(
+ revoked.status is SessionRevocationStatus.REVOKED
+ and principal is None
+ and row is not None
+ and int(row["auth_epoch"]) == 2,
+ "logout-all did not advance authoritative epoch",
+ )
+ finally:
+ await database.close()
diff --git a/tests/unit/test_refresh_token_family_migration.py b/tests/unit/test_refresh_token_family_migration.py
new file mode 100644
index 0000000..f74af82
--- /dev/null
+++ b/tests/unit/test_refresh_token_family_migration.py
@@ -0,0 +1,206 @@
+"""Real SQLite coverage for revision 0009 refresh-token families."""
+from __future__ import annotations
+
+import sqlite3
+from collections.abc import Callable
+from pathlib import Path
+
+import sqlalchemy as sa
+from alembic import command
+
+from ares.db.migrations.adoption import migration_config
+
+
+def _require(value: bool, message: str) -> None:
+ if not value:
+ raise AssertionError(message)
+
+
+def _alembic(
+ database_path: Path,
+ action: Callable[[object, str], None],
+ revision: str,
+) -> None:
+ engine = sa.create_engine(f"sqlite:///{database_path}")
+ try:
+ with engine.connect() as connection:
+ with migration_config(connection) as config:
+ action(config, revision)
+ finally:
+ engine.dispose()
+
+
+def _connect(database_path: Path) -> sqlite3.Connection:
+ connection = sqlite3.connect(database_path)
+ connection.row_factory = sqlite3.Row
+ connection.execute("PRAGMA foreign_keys=ON")
+ return connection
+
+
+def _seed_revision_0008(database_path: Path, *, legacy_identifier: str) -> None:
+ connection = _connect(database_path)
+ try:
+ connection.execute(
+ "INSERT INTO users(id,username,hashed_password,role) "
+ "VALUES('family-user','family-user','fixed-hash','operator')"
+ )
+ connection.execute(
+ "INSERT INTO refresh_tokens(id,user_id,expires_at) "
+ "VALUES(?, 'family-user', '2099-01-01T00:00:00.000Z')",
+ (legacy_identifier,),
+ )
+ connection.execute(
+ "INSERT INTO campaigns(id,name,operator) "
+ "VALUES('family-campaign','Family campaign','family-user')"
+ )
+ 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("
+ "?,'family-campaign','family-user','bearer','family-user',?,"
+ "'2099-01-01T00:00:00.000Z','2030-01-01T00:00:00.000Z',"
+ "'2030-01-01T00:00:30.000Z')",
+ ("b" * 64, "fixed-jti"),
+ )
+ connection.commit()
+ finally:
+ connection.close()
+
+
+def test_revision_0009_resets_existing_sessions_without_losing_rows(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "upgrade-0009.db"
+ _alembic(database_path, command.upgrade, "0008")
+ _seed_revision_0008(database_path, legacy_identifier="a" * 64)
+ _alembic(database_path, command.upgrade, "0009")
+
+ connection = _connect(database_path)
+ try:
+ revision = connection.execute(
+ "SELECT version_num FROM alembic_version"
+ ).fetchone()
+ user = connection.execute(
+ "SELECT auth_epoch FROM users WHERE id='family-user'"
+ ).fetchone()
+ refresh = connection.execute(
+ "SELECT state,is_revoked,family_id FROM refresh_tokens"
+ ).fetchone()
+ ticket = connection.execute(
+ "SELECT bearer_family_id,bearer_auth_epoch FROM websocket_tickets"
+ ).fetchone()
+ families = connection.execute(
+ "SELECT state,revoke_reason FROM refresh_token_families"
+ ).fetchall()
+ preserved = (
+ revision is not None
+ and revision[0] == "0009"
+ and user is not None
+ and int(user[0]) == 1
+ and refresh is not None
+ and refresh[0] == "retired"
+ and int(refresh[1]) == 1
+ and isinstance(refresh[2], str)
+ and ticket is not None
+ and isinstance(ticket[0], str)
+ and int(ticket[1]) == 1
+ and len(families) == 2
+ and all(
+ row[0] == "revoked" and row[1] == "rollout_reset"
+ for row in families
+ )
+ )
+ finally:
+ connection.close()
+ _require(preserved, "revision 0009 did not preserve and reset legacy sessions")
+
+
+def test_revision_0009_rejects_non_hash_legacy_token_before_advancement(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "unsafe-0009.db"
+ _alembic(database_path, command.upgrade, "0008")
+ _seed_revision_0008(database_path, legacy_identifier="not-a-hash")
+ rejected = False
+ try:
+ _alembic(database_path, command.upgrade, "0009")
+ except RuntimeError:
+ rejected = True
+
+ connection = _connect(database_path)
+ try:
+ revision = connection.execute(
+ "SELECT version_num FROM alembic_version"
+ ).fetchone()
+ family_table = connection.execute(
+ "SELECT 1 FROM sqlite_schema "
+ "WHERE type='table' AND name='refresh_token_families'"
+ ).fetchone()
+ user_columns = tuple(
+ str(row[1]) for row in connection.execute("PRAGMA table_info(users)")
+ )
+ original_row = connection.execute(
+ "SELECT count(*) FROM refresh_tokens WHERE id='not-a-hash'"
+ ).fetchone()
+ unchanged = (
+ rejected
+ and revision is not None
+ and revision[0] == "0008"
+ and family_table is None
+ and "auth_epoch" not in user_columns
+ and original_row is not None
+ and int(original_row[0]) == 1
+ )
+ finally:
+ connection.close()
+ _require(unchanged, "unsafe legacy refresh data mutated during rejection")
+
+
+def test_revision_0009_constraints_and_forward_only_downgrade(
+ tmp_path: Path,
+) -> None:
+ database_path = tmp_path / "constraints-0009.db"
+ _alembic(database_path, command.upgrade, "0009")
+ connection = _connect(database_path)
+ try:
+ connection.execute(
+ "INSERT INTO users(id,username,hashed_password,role) "
+ "VALUES('constraint-user','constraint-user','fixed','reporter')"
+ )
+ rejected = False
+ try:
+ connection.execute(
+ "INSERT INTO refresh_token_families("
+ "id,user_id,auth_epoch,state,created_at,absolute_expires_at,"
+ "revoked_at,revoke_reason,retain_until) VALUES("
+ "?,'constraint-user',1,'active',"
+ "'2030-01-01T00:00:00.000Z','2030-02-01T00:00:00.000Z',"
+ "'2030-01-02T00:00:00.000Z','replay',"
+ "'2030-03-01T00:00:00.000Z')",
+ ("A" * 43,),
+ )
+ except sqlite3.IntegrityError:
+ rejected = True
+ connection.rollback()
+ finally:
+ connection.close()
+
+ downgrade_rejected = False
+ try:
+ _alembic(database_path, command.downgrade, "0008")
+ except RuntimeError as error:
+ downgrade_rejected = str(error) == "revision-0009 downgrade is not supported"
+ connection = _connect(database_path)
+ try:
+ revision = connection.execute(
+ "SELECT version_num FROM alembic_version"
+ ).fetchone()
+ finally:
+ connection.close()
+ _require(
+ rejected
+ and downgrade_rejected
+ and revision is not None
+ and revision[0] == "0009",
+ "revision 0009 constraint or forward-only contract changed",
+ )
diff --git a/tests/unit/test_schema_reconciliation_migration.py b/tests/unit/test_schema_reconciliation_migration.py
index 47e1b96..8e24dbf 100644
--- a/tests/unit/test_schema_reconciliation_migration.py
+++ b/tests/unit/test_schema_reconciliation_migration.py
@@ -1,7 +1,6 @@
"""SQLite coverage for revision 0008 schema reconciliation."""
from __future__ import annotations
-import asyncio
import importlib
import re
import sqlite3
@@ -17,8 +16,6 @@ import sqlalchemy as sa
from alembic import command
from alembic.config import Config
-from ares.db.database import AresDatabase
-
_ROOT = Path(__file__).resolve().parents[2]
_CATALOG_ERROR = "Incompatible catalog for migration 0008"
_DATA_ERROR = "Unsafe data for migration 0008"
@@ -223,7 +220,7 @@ def _complete_managed_contract_is_exact(path: Path) -> bool:
return (
non_ticket == portability._fixed_sqlite_contract("0006")
and ticket._ticket_contract(path)
- == ticket._EXPECTED_TICKET_CONTRACT
+ == ticket._EXPECTED_TICKET_CONTRACT_0007
)
@@ -312,10 +309,12 @@ def _attempt_upgrade(path: Path) -> str:
return ""
-async def _runtime_bootstrap(path: Path) -> None:
- database = AresDatabase(f"file:{path.resolve().as_posix()}?mode=rwc")
- await database.connect()
- await database.close()
+def _create_supported_unversioned_generation_7(path: Path) -> None:
+ _upgrade(path, "0008")
+ with _connect(path) as connection:
+ connection.execute("DROP TABLE rate_limit_events")
+ connection.execute("DROP TABLE alembic_version")
+ connection.commit()
def _rewrite_table_sql(path: Path, table: str, old: str, new: str) -> None:
@@ -746,9 +745,9 @@ def _weaken_blocked_check_with_comment(path: Path) -> None:
connection.commit()
-def test_empty_base_upgrades_to_real_0008_head() -> None:
+def test_empty_base_upgrades_to_real_0008_revision() -> None:
with _database("empty") as path:
- _upgrade(path, "head")
+ _upgrade(path, "0008")
with _connect(path) as connection:
tables = {
str(row[0])
@@ -920,9 +919,9 @@ def test_representative_legacy_catalog_converges_and_is_repeat_stable() -> None:
)
-def test_runtime_origin_stamped_0007_converges_to_fixed_contract() -> None:
+def test_supported_unversioned_generation_7_converges_to_fixed_contract() -> None:
with _database("runtime-origin") as path:
- asyncio.run(_runtime_bootstrap(path))
+ _create_supported_unversioned_generation_7(path)
with _connect(path) as connection:
before_order = tuple(
str(row[1])
@@ -931,12 +930,9 @@ def test_runtime_origin_stamped_0007_converges_to_fixed_contract() -> None:
)
)
connection.execute(
- """
- CREATE TABLE alembic_version(
- version_num VARCHAR(32) NOT NULL,
- CONSTRAINT alembic_version_pkc PRIMARY KEY(version_num)
- )
- """
+ "CREATE TABLE alembic_version("
+ "version_num VARCHAR(32) NOT NULL,"
+ "CONSTRAINT alembic_version_pkc PRIMARY KEY(version_num))"
)
connection.execute(
"INSERT INTO alembic_version(version_num) VALUES('0007')"
@@ -953,9 +949,9 @@ def test_runtime_origin_stamped_0007_converges_to_fixed_contract() -> None:
)
)
_require_fixed(
- before_order.index("trace_id") < before_order.index("evidence_json")
+ before_order == after_order
and after_order.index("trace_id") > after_order.index("discovered_at"),
- "runtime-origin findings order did not converge",
+ "supported generation findings order changed",
)
_require_fixed(
_complete_managed_contract_is_exact(path),
diff --git a/tests/unit/test_security_critical.py b/tests/unit/test_security_critical.py
index b3dc1d9..30630f7 100644
--- a/tests/unit/test_security_critical.py
+++ b/tests/unit/test_security_critical.py
@@ -33,6 +33,15 @@ os.environ.setdefault("ARES_DEFAULT_ADMIN_PASSWORD", "TestCriticalPass1!")
_MOCK_PRINCIPAL_ROLES: dict[str, str] = {}
[email protected](autouse=True)
+def _isolate_server_dependencies():
+ yield
+ from ares.api.server import app
+
+ app.dependency_overrides.clear()
+ _MOCK_PRINCIPAL_ROLES.clear()
+
+
def _settings():
from ares.core.config import get_settings
get_settings.cache_clear()
@@ -41,11 +50,12 @@ def _settings():
def _make_token(username: str, role: str, expires_minutes: int = 60) -> str:
from ares.core.security import create_access_token
+ from ares.core.token_sessions import generate_family_id
_MOCK_PRINCIPAL_ROLES[username] = role
s = _settings()
return create_access_token(
- data={"sub": username, "role": role},
+ data={"sub": username, "sid": generate_family_id(), "ver": 1},
secret_key=s.secret_key_value,
expires_minutes=expires_minutes,
)
@@ -64,19 +74,36 @@ def _make_mock_db():
db.create_refresh_token = AsyncMock(return_value="raw-mock-refresh-token")
db.rotate_refresh_token = AsyncMock(return_value=(None, None))
db.revoke_all_refresh_tokens = AsyncMock()
+ from ares.core.token_sessions import (
+ SessionRevocationResult,
+ SessionRevocationStatus,
+ )
+ db.revoke_current_session = AsyncMock(
+ return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED)
+ )
+ db.revoke_all_sessions = AsyncMock(
+ return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED)
+ )
db.revoke_access_token = AsyncMock()
db.is_access_token_revoked = AsyncMock(return_value=False)
async def resolve_access_token_principal(
subject: str,
_jti: str,
+ _family_id: str,
+ auth_epoch: int,
) -> dict[str, str] | None:
if db.is_access_token_revoked.return_value is True:
return None
role = _MOCK_PRINCIPAL_ROLES.get(subject)
if role is None:
return None
- return {"id": f"mock-user-{subject}", "username": subject, "role": role}
+ return {
+ "id": f"mock-user-{subject}",
+ "username": subject,
+ "role": role,
+ "auth_epoch": auth_epoch,
+ }
db.resolve_access_token_principal = AsyncMock(
side_effect=resolve_access_token_principal
@@ -279,7 +306,7 @@ class TestTokenRevocation:
async with self._client(db) as c:
r = await c.post("/auth/logout", headers=_auth("alice", "operator"))
assert r.status_code == 200
- db.revoke_all_refresh_tokens.assert_called_once()
+ db.revoke_current_session.assert_awaited_once()
_run(_run_test())
diff --git a/tests/unit/test_sqlite_auth_token_lifecycle.py b/tests/unit/test_sqlite_auth_token_lifecycle.py
index cdc4399..7d4e8e1 100644
--- a/tests/unit/test_sqlite_auth_token_lifecycle.py
+++ b/tests/unit/test_sqlite_auth_token_lifecycle.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import asyncio
import hashlib
import os
-import secrets
+import sqlite3
import threading
from datetime import datetime, timedelta, timezone
from pathlib import Path
@@ -789,9 +789,7 @@ async def test_rollback_cleanup_error_preserves_primary_rotation_failure(
async def fail_successor_insert(
_tx: aiosqlite.Connection,
- _token_hash_value: str,
- _user_id: str,
- _expires_at: str,
+ **_values: object,
) -> None:
raise PrimaryRotationFailure("primary-rotation-failure")
@@ -802,7 +800,7 @@ async def test_rollback_cleanup_error_preserves_primary_rotation_failure(
"_open_refresh_rotation_connection",
open_with_failing_rollback,
)
- patcher.setattr(db, "_insert_refresh_successor", fail_successor_insert)
+ patcher.setattr(db, "_insert_family_successor", fail_successor_insert)
with pytest.raises(
PrimaryRotationFailure,
match="primary-rotation-failure",
@@ -814,7 +812,7 @@ async def test_rollback_cleanup_error_preserves_primary_rotation_failure(
assert rows[0]["is_revoked"] == 0
assert rows[0]["used_at"] is None
calls = repr(captured_logger.mock_calls)
- assert "rollback_before_commit" in calls
+ assert "family-rollback" in calls
assert "RuntimeError" in calls
assert "private-rollback-detail" not in calls
assert db._db_path not in calls
@@ -960,7 +958,7 @@ async def test_inactive_owner_api_key_is_denied_without_usage_and_reactivates(
@pytest.mark.asyncio
-async def test_inactive_owner_refresh_is_immutable_and_reactivates(
+async def test_inactive_owner_refresh_is_immutable_then_replay_revokes_family(
db_and_user: tuple[AresDatabase, str],
) -> None:
db, user_id = db_and_user
@@ -1001,8 +999,8 @@ async def test_inactive_owner_refresh_is_immutable_and_reactivates(
"expected the reactivated predecessor to rotate only once",
)
_require_fixed(
- await _active_refresh_count(db, user_id) == 1,
- "expected exactly one active refresh successor after reactivation",
+ await _active_refresh_count(db, user_id) == 0,
+ "expected predecessor replay to retire the active successor",
)
@@ -1016,9 +1014,26 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
db, user_id = db_and_user
subject = "sqlite-lifecycle-user"
jti = "sqlite-principal-jti"
+ await db.create_refresh_token(user_id)
+ async with db.conn.execute(
+ "SELECT id,auth_epoch FROM refresh_token_families WHERE user_id=?",
+ (user_id,),
+ ) as cursor:
+ family = await cursor.fetchone()
+ assert family is not None
+ family_id = str(family["id"])
+ auth_epoch = int(family["auth_epoch"])
+
+ async def resolve(current_jti: str) -> dict[str, object] | None:
+ return await db.resolve_access_token_principal(
+ subject,
+ current_jti,
+ family_id,
+ auth_epoch,
+ )
changes_before = db.conn.total_changes
- active = await db.resolve_access_token_principal(subject, jti)
+ active = await resolve(jti)
changes_after = db.conn.total_changes
_require_fixed(
active is not None
@@ -1037,7 +1052,7 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
(user_id,),
)
await db.conn.commit()
- inactive = await db.resolve_access_token_principal(subject, jti)
+ inactive = await resolve(jti)
_require_fixed(
inactive is None,
"expected inactive SQLite bearer principal to be rejected",
@@ -1048,7 +1063,7 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
(user_id,),
)
await db.conn.commit()
- demoted = await db.resolve_access_token_principal(subject, jti)
+ demoted = await resolve(jti)
_require_fixed(
demoted is not None and demoted.get("role") == "reporter",
"expected SQLite principal lookup to return the current demoted role",
@@ -1059,7 +1074,7 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
(user_id,),
)
await db.conn.commit()
- promoted = await db.resolve_access_token_principal(subject, jti)
+ promoted = await resolve(jti)
_require_fixed(
promoted is not None and promoted.get("role") == "team_lead",
"expected SQLite principal lookup to return the current promoted role",
@@ -1072,7 +1087,12 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
await db.conn.commit()
signing_key = "sqlite-principal-test-signing-key"
token = create_access_token(
- {"sub": subject, "role": "team_lead"},
+ {
+ "sub": subject,
+ "sid": family_id,
+ "ver": auth_epoch,
+ "role": "team_lead",
+ },
signing_key,
)
invalid_role = await resolve_bearer_principal(
@@ -1096,7 +1116,7 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
(jti, user_id, "2099-01-01 00:00:00"),
)
await db.conn.commit()
- revoked = await db.resolve_access_token_principal(subject, jti)
+ revoked = await resolve(jti)
_require_fixed(
revoked is None,
"expected revoked SQLite bearer principal to be rejected",
@@ -1111,13 +1131,13 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
(user_id,),
)
await db.conn.commit()
- suspended = await db.resolve_access_token_principal(subject, jti)
+ suspended = await resolve(jti)
await db.conn.execute(
"UPDATE users SET is_active=1 WHERE id=?",
(user_id,),
)
await db.conn.commit()
- reactivated = await db.resolve_access_token_principal(subject, jti)
+ reactivated = await resolve(jti)
_require_fixed(
suspended is None and reactivated is not None,
"expected temporary SQLite suspension to be reversible",
@@ -1125,7 +1145,7 @@ async def test_authoritative_principal_state_role_revocation_and_read_only(
await db.conn.execute("DELETE FROM users WHERE id=?", (user_id,))
await db.conn.commit()
- deleted = await db.resolve_access_token_principal(subject, jti)
+ deleted = await resolve(jti)
_require_fixed(
deleted is None,
"expected a deleted SQLite bearer principal to be rejected",
@@ -1142,6 +1162,8 @@ async def test_authoritative_principal_closed_database_propagates(
await db.resolve_access_token_principal(
"sqlite-lifecycle-user",
"sqlite-closed-jti",
+ "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ 1,
)
await db.connect()
@@ -1233,7 +1255,9 @@ async def test_database_generated_exact_now_is_rejected(
(key_id,),
)
await db.conn.execute(
- "UPDATE refresh_tokens SET expires_at=datetime('now') WHERE id=?",
+ "UPDATE refresh_tokens SET "
+ "created_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-1 day'),"
+ "expires_at=strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id=?",
(_token_hash(predecessor),),
)
await db.conn.commit()
@@ -1253,30 +1277,31 @@ async def test_api_key_rejects_malformed_non_null_expiry(
assert await db.verify_api_key(raw_key) is None
- "expires_at",
- [
- pytest.param(
- lambda: (datetime.now(timezone.utc) - timedelta(days=1)).isoformat(),
- id="expired-iso-offset",
- ),
- pytest.param(lambda: "not-a-timestamp", id="malformed"),
- ],
-)
[email protected]("expiry_kind", ["expired", "malformed"])
@pytest.mark.asyncio
async def test_invalid_refresh_expiry_cannot_rotate_or_create_successor(
db_and_user: tuple[AresDatabase, str],
- expires_at,
+ expiry_kind: str,
) -> None:
db, user_id = db_and_user
old_token = await db.create_refresh_token(user_id)
- await db.conn.execute(
- "UPDATE refresh_tokens SET expires_at=? WHERE id=?",
- (expires_at(), _token_hash(old_token)),
- )
- await db.conn.commit()
-
- assert await db.rotate_refresh_token(old_token) == (None, None)
+ if expiry_kind == "expired":
+ await db.conn.execute(
+ "UPDATE refresh_tokens SET "
+ "created_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-2 days'),"
+ "expires_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-1 day') "
+ "WHERE id=?",
+ (_token_hash(old_token),),
+ )
+ await db.conn.commit()
+ assert await db.rotate_refresh_token(old_token) == (None, None)
+ else:
+ with pytest.raises(sqlite3.IntegrityError):
+ await db.conn.execute(
+ "UPDATE refresh_tokens SET expires_at=? WHERE id=?",
+ ("not-a-timestamp", _token_hash(old_token)),
+ )
+ await db.conn.rollback()
rows = await _refresh_rows(db)
assert len(rows) == 1
assert rows[0]["is_revoked"] == 0
@@ -1314,25 +1339,18 @@ async def test_cancellation_before_commit_rolls_back_and_propagates(
predecessor = await db.create_refresh_token(user_id)
inserted = asyncio.Event()
release = asyncio.Event()
- original_insert = db._insert_refresh_successor
+ original_insert = db._insert_family_successor
async def insert_then_pause(
tx: aiosqlite.Connection,
- token_hash: str,
- successor_user_id: str,
- expires_at: str,
+ **values: object,
) -> None:
- await original_insert(
- tx,
- token_hash,
- successor_user_id,
- expires_at,
- )
+ await original_insert(tx, **values)
inserted.set()
await release.wait()
with monkeypatch.context() as patcher:
- patcher.setattr(db, "_insert_refresh_successor", insert_then_pause)
+ patcher.setattr(db, "_insert_family_successor", insert_then_pause)
rotation = asyncio.create_task(db.rotate_refresh_token(predecessor))
await inserted.wait()
rotation.cancel()
@@ -1399,7 +1417,7 @@ async def test_cancellation_during_commit_returns_committed_successor(
assert rotated_user is not None
assert replacement is not None
assert await db.rotate_refresh_token(successor) == (None, None)
- assert await _active_refresh_count(db, user_id) == 1
+ assert await _active_refresh_count(db, user_id) == 0
@pytest.mark.asyncio
@@ -1495,40 +1513,69 @@ async def test_commit_normalization_preserves_preexisting_cancellation_debt(
@pytest.mark.asyncio
-async def test_purge_preserves_grace_and_malformed_unrevoked_rows(
+async def test_purge_uses_family_retention_and_rejects_malformed_timestamps(
db_and_user: tuple[AresDatabase, str],
) -> None:
db, user_id = db_and_user
- now = datetime.now(timezone.utc)
- rows = [
- (_token_hash(secrets.token_urlsafe(32)), 1, (now + timedelta(days=1)).isoformat()),
- (_token_hash(secrets.token_urlsafe(32)), 0, (now - timedelta(days=8)).isoformat()),
- (
- _token_hash(secrets.token_urlsafe(32)),
- 0,
- (now - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S"),
- ),
- (_token_hash(secrets.token_urlsafe(32)), 0, "not-a-timestamp"),
- (_token_hash(secrets.token_urlsafe(32)), 0, (now + timedelta(days=1)).isoformat()),
- ]
- await db.conn.executemany(
- "INSERT INTO refresh_tokens(id,user_id,is_revoked,expires_at) "
- "VALUES(?,?,?,?)",
- [(token_id, user_id, revoked, expires_at) for token_id, revoked, expires_at in rows],
+ raw_tokens = [await db.create_refresh_token(user_id) for _ in range(4)]
+ token_hashes = [_token_hash(value) for value in raw_tokens]
+ async with db.conn.execute(
+ "SELECT id,family_id FROM refresh_tokens WHERE user_id=? ORDER BY id",
+ (user_id,),
+ ) as cursor:
+ family_by_hash = {
+ str(row["id"]): str(row["family_id"])
+ for row in await cursor.fetchall()
+ }
+ retained_revoked = family_by_hash[token_hashes[0]]
+ expired_revoked = family_by_hash[token_hashes[1]]
+ expired_active = family_by_hash[token_hashes[2]]
+ retained_active = family_by_hash[token_hashes[3]]
+
+ for family_id in (retained_revoked, expired_revoked):
+ await db.conn.execute(
+ "UPDATE refresh_token_families SET state='revoked',"
+ "created_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-40 days'),"
+ "absolute_expires_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-10 days'),"
+ "revoked_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-10 days'),"
+ "revoke_reason='expired',retain_until=strftime("
+ "'%Y-%m-%dT%H:%M:%fZ','now',?) WHERE id=?",
+ ("+1 day" if family_id == retained_revoked else "-1 day", family_id),
+ )
+ await db.conn.execute(
+ "UPDATE refresh_tokens SET state='retired',is_revoked=1,"
+ "revoked_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-10 days') "
+ "WHERE family_id=?",
+ (family_id,),
+ )
+ await db.conn.execute(
+ "UPDATE refresh_token_families SET "
+ "created_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-40 days'),"
+ "absolute_expires_at=strftime('%Y-%m-%dT%H:%M:%fZ','now','-10 days'),"
+ "retain_until=strftime('%Y-%m-%dT%H:%M:%fZ','now','-1 day') "
+ "WHERE id=?",
+ (expired_active,),
)
await db.conn.commit()
+ with pytest.raises(sqlite3.IntegrityError):
+ await db.conn.execute(
+ "UPDATE refresh_token_families SET retain_until='not-a-timestamp' "
+ "WHERE id=?",
+ (retained_active,),
+ )
+ await db.conn.rollback()
+
assert await db.purge_expired_tokens() == 2
remaining = await _refresh_rows(db)
assert {row["id"] for row in remaining} == {
- rows[2][0],
- rows[3][0],
- rows[4][0],
+ token_hashes[0],
+ token_hashes[3],
}
@pytest.mark.asyncio
-async def test_many_concurrent_rotations_have_one_winner_and_reusable_successor(
+async def test_many_concurrent_rotations_revoke_the_winner_family_on_replay(
db_and_user: tuple[AresDatabase, str],
) -> None:
db, user_id = db_and_user
@@ -1546,17 +1593,14 @@ async def test_many_concurrent_rotations_have_one_winner_and_reusable_successor(
assert len(winners) == 1
assert sum(result == (None, None) for result in results) == 15
- assert await _active_refresh_count(db, user_id) == 1
+ assert await _active_refresh_count(db, user_id) == 0
assert len(await _refresh_rows(db)) == 2
assert await db.rotate_refresh_token(old_token) == (None, None)
successor = winners[0][1]
assert successor is not None
- rotated_user, replacement = await db.rotate_refresh_token(successor)
- assert rotated_user is not None
- assert replacement is not None
assert await db.rotate_refresh_token(successor) == (None, None)
- assert await _active_refresh_count(db, user_id) == 1
+ assert await _active_refresh_count(db, user_id) == 0
@pytest.mark.asyncio
@@ -1587,7 +1631,7 @@ async def test_two_database_instances_have_exactly_one_rotation_winner(
)
old_token = await first.create_refresh_token(user_id)
old_hash = _token_hash(old_token)
- original_insert = first._insert_refresh_successor
+ original_insert = first._insert_family_successor
original_first_open = first._open_refresh_rotation_connection
original_second_open = second._open_refresh_rotation_connection
loop = asyncio.get_running_loop()
@@ -1623,18 +1667,11 @@ async def test_two_database_instances_have_exactly_one_rotation_winner(
async def pause_with_writer_lock(
tx: aiosqlite.Connection,
- token_hash: str,
- successor_user_id: str,
- expires_at: str,
+ **values: object,
) -> None:
first_holds_writer.set()
await release_first.wait()
- await original_insert(
- tx,
- token_hash,
- successor_user_id,
- expires_at,
- )
+ await original_insert(tx, **values)
async def open_first_with_transaction_trace() -> aiosqlite.Connection:
tx = await original_first_open()
@@ -1669,7 +1706,7 @@ async def test_two_database_instances_have_exactly_one_rotation_winner(
)
patcher.setattr(
first,
- "_insert_refresh_successor",
+ "_insert_family_successor",
pause_with_writer_lock,
)
patcher.setattr(
@@ -1718,13 +1755,13 @@ async def test_two_database_instances_have_exactly_one_rotation_winner(
)
assert completed_first_order.count("BEGIN IMMEDIATE") == 1
assert completed_second_order.count("BEGIN IMMEDIATE") == 1
- assert await _active_refresh_count(first, user_id) == 1
+ assert await _active_refresh_count(first, user_id) == 0
rows = await _refresh_rows(first)
assert len(rows) == 2
predecessor = next(row for row in rows if row["id"] == old_hash)
assert predecessor["is_revoked"] == 1
assert predecessor["used_at"] is not None
- assert sum(row["is_revoked"] == 0 for row in rows) == 1
+ assert sum(row["is_revoked"] == 0 for row in rows) == 0
assert _owned_sqlite_tasks() == []
finally:
release_first.set()
@@ -1849,6 +1886,6 @@ async def test_plain_memory_database_supports_atomic_refresh_lifecycle() -> None
assert user is not None
assert successor is not None
assert await db.rotate_refresh_token(old_token) == (None, None)
- assert await _active_refresh_count(db, user_id) == 1
+ assert await _active_refresh_count(db, user_id) == 0
finally:
await db.close()
diff --git a/tests/unit/test_unversioned_database_adoption.py b/tests/unit/test_unversioned_database_adoption.py
index 1fd106c..816d370 100644
--- a/tests/unit/test_unversioned_database_adoption.py
+++ b/tests/unit/test_unversioned_database_adoption.py
@@ -10,6 +10,7 @@ from pathlib import Path
import pytest
import sqlalchemy as sa
+from alembic import command
import ares.db.migrations.adoption as adoption_module
from ares.db.database import AresDatabase
@@ -28,17 +29,20 @@ from ares.db.migrations.adoption import (
async def _create_runtime(path: Path, *, generation: int = 7) -> None:
- database = AresDatabase(f"file:{path.resolve().as_posix()}?mode=rwc")
- await database.connect()
- await database.close()
- if generation == 6:
- connection = sqlite3.connect(path)
- try:
- connection.execute("PRAGMA foreign_keys=OFF")
- connection.execute("DROP TABLE websocket_tickets")
- connection.commit()
- finally:
- connection.close()
+ engine = sa.create_engine(f"sqlite:///{path.resolve().as_posix()}")
+ with engine.connect() as connection:
+ with migration_config(connection) as config:
+ command.upgrade(config, "0008")
+ connection.exec_driver_sql("DROP TABLE rate_limit_events")
+ connection.exec_driver_sql("DROP TABLE alembic_version")
+ if generation == 6:
+ connection.exec_driver_sql("PRAGMA foreign_keys=OFF")
+ try:
+ connection.exec_driver_sql("DROP TABLE websocket_tickets")
+ finally:
+ connection.exec_driver_sql("PRAGMA foreign_keys=ON")
+ connection.commit()
+ engine.dispose()
def _catalog_digest(path: Path) -> bytes:
@@ -147,7 +151,7 @@ async def test_sqlite_adoption_uses_backup_and_normal_history(
assert backup.is_file()
assert _catalog_digest(backup) == before
managed = verify_managed_connection_from_path(path)
- assert managed.diagnostic == "ARES-M2B-ALREADY-MANAGED:0008"
+ assert managed.diagnostic == "ARES-M2B-ALREADY-MANAGED:0009"
connection = sqlite3.connect(path)
try:
revision = connection.execute(
@@ -155,7 +159,7 @@ async def test_sqlite_adoption_uses_backup_and_normal_history(
).fetchone()[0]
finally:
connection.close()
- assert revision == "0008"
+ assert revision == "0009"
@pytest.mark.asyncio
@@ -174,7 +178,7 @@ async def test_sqlite_adoption_rerun_is_verified_noop(tmp_path: Path) -> None:
second_backup.exists(),
) == (
AdoptionExit.OK,
- "ARES-M2B-ALREADY-MANAGED:0008",
+ "ARES-M2B-ALREADY-MANAGED:0009",
True,
False,
)
@@ -274,7 +278,7 @@ async def test_startup_rejects_unversioned_without_alembic_side_effect(
@pytest.mark.asyncio
-async def test_startup_rejects_noncanonical_fake_0008(tmp_path: Path) -> None:
+async def test_startup_rejects_noncanonical_fake_0009(tmp_path: Path) -> None:
path = tmp_path / "runtime.db"
await _create_runtime(path)
connection = sqlite3.connect(path)
@@ -284,7 +288,7 @@ async def test_startup_rejects_noncanonical_fake_0008(tmp_path: Path) -> None:
"version_num VARCHAR(32) NOT NULL, "
"CONSTRAINT alembic_version_pkc PRIMARY KEY (version_num))"
)
- connection.execute("INSERT INTO alembic_version VALUES ('0008')")
+ connection.execute("INSERT INTO alembic_version VALUES ('0009')")
connection.commit()
finally:
connection.close()
diff --git a/tests/unit/test_websocket_ticket_lifecycle.py b/tests/unit/test_websocket_ticket_lifecycle.py
index 82c3718..bee340e 100644
--- a/tests/unit/test_websocket_ticket_lifecycle.py
+++ b/tests/unit/test_websocket_ticket_lifecycle.py
@@ -2,6 +2,8 @@
from __future__ import annotations
import asyncio
+import base64
+import hashlib
import os
import re
import sqlite3
@@ -106,15 +108,46 @@ async def _seed_identity(
(api_key_id, user_id, scopes),
)
await connection.commit()
+ now = datetime.now(timezone.utc)
+ family_id = _test_family_id(user_id)
+ await connection.execute(
+ "INSERT INTO refresh_token_families("
+ "id,user_id,auth_epoch,state,created_at,absolute_expires_at,retain_until) "
+ "VALUES(?,?,1,'active',?,?,?)",
+ (
+ family_id,
+ user_id,
+ now.strftime("%Y-%m-%dT%H:%M:%S.")
+ + f"{now.microsecond // 1000:03d}Z",
+ (now + timedelta(days=30)).strftime("%Y-%m-%dT%H:%M:%S.")
+ + f"{(now + timedelta(days=30)).microsecond // 1000:03d}Z",
+ (now + timedelta(days=60)).strftime("%Y-%m-%dT%H:%M:%S.")
+ + f"{(now + timedelta(days=60)).microsecond // 1000:03d}Z",
+ ),
+ )
+ await connection.commit()
return user_id, username, campaign_id, other_campaign_id, api_key_id
-def _bearer_source(user_id: str, username: str) -> BearerTicketSource:
+def _test_family_id(user_id: str) -> str:
+ digest = hashlib.sha256(b"ARES-WS-TEST-FAMILY\0" + user_id.encode()).digest()
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
+
+
+def _bearer_source(
+ user_id: str,
+ username: str,
+ *,
+ family_id: str | None = None,
+ auth_epoch: int = 1,
+) -> BearerTicketSource:
return BearerTicketSource(
user_id=user_id,
subject=username,
jti=f"ticket-jti-{uuid4().hex}",
expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
+ family_id=family_id or _test_family_id(user_id),
+ auth_epoch=auth_epoch,
)
@@ -585,6 +618,8 @@ def test_bearer_ticket_source_preserves_identity_and_confidentiality() -> None:
"subject": "synthetic-bearer-subject",
"jti": "synthetic-bearer-jti",
"expires_at": expires_at,
+ "family_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "auth_epoch": 7,
}
first = BearerTicketSource(**values)
second = BearerTicketSource(**values)
@@ -624,6 +659,8 @@ def test_consumed_ticket_preserves_identity_and_confidentiality() -> None:
"bearer_subject": "synthetic-consumed-subject",
"bearer_jti": "synthetic-consumed-jti",
"bearer_expires_at": bearer_expiry,
+ "bearer_family_id": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ "bearer_auth_epoch": 9,
}
first_bearer = ConsumedWebSocketTicket(**bearer_values)
second_bearer = ConsumedWebSocketTicket(**bearer_values)
@@ -636,6 +673,8 @@ def test_consumed_ticket_preserves_identity_and_confidentiality() -> None:
bearer_values["bearer_subject"],
bearer_values["bearer_jti"],
bearer_values["bearer_expires_at"],
+ bearer_values["bearer_family_id"],
+ bearer_values["bearer_auth_epoch"],
),
frozen_field="bearer_jti",
)
diff --git a/tests/unit/test_websocket_ticket_migration.py b/tests/unit/test_websocket_ticket_migration.py
index 02799a6..4835f48 100644
--- a/tests/unit/test_websocket_ticket_migration.py
+++ b/tests/unit/test_websocket_ticket_migration.py
@@ -39,9 +39,15 @@ _CHECK_NAMES = (
)
_FOREIGN_KEY_NAMES = (
"fk_ws_ticket_api_key",
+ "fk_ws_ticket_bearer_family",
"fk_ws_ticket_campaign",
"fk_ws_ticket_user",
)
+_FOREIGN_KEY_NAMES_0007 = tuple(
+ name
+ for name in _FOREIGN_KEY_NAMES
+ if name != "fk_ws_ticket_bearer_family"
+)
@dataclass(frozen=True, slots=True)
@@ -303,6 +309,14 @@ def _named_foreign_keys_bound(table_sql: str) -> tuple[str, ...]:
or inline_pattern.search(compact) is not None
):
bound.append(name)
+ family_pattern = re.compile(
+ "constraintfk_ws_ticket_bearer_family"
+ "foreignkey\\(bearer_family_id,user_id\\)"
+ "referencesrefresh_token_families\\(id,user_id\\)"
+ "(?:onupdatenoaction)?ondeletecascade"
+ )
+ if family_pattern.search(compact) is not None:
+ bound.append("fk_ws_ticket_bearer_family")
return tuple(sorted(bound))
@@ -358,7 +372,14 @@ def _ticket_contract(path: Path) -> _TicketContract | None:
f"PRAGMA foreign_key_list({_TICKET_TABLE})"
)
),
- key=lambda item: item.local_column,
+ key=lambda item: (
+ item.local_column,
+ item.target_table,
+ item.target_column,
+ item.on_update,
+ item.on_delete,
+ item.match,
+ ),
)
)
indexes: list[_IndexContract] = []
@@ -692,14 +713,141 @@ def _expected_ticket_contract() -> _TicketContract:
managed_primary_key_indexes=managed_primary_key_indexes,
attached_objects=attached_objects,
named_constraints=tuple(
- sorted(_CHECK_NAMES + _FOREIGN_KEY_NAMES)
+ sorted(_CHECK_NAMES + _FOREIGN_KEY_NAMES_0007)
+ ),
+ canonical_table=True,
+ named_foreign_keys_bound=tuple(
+ sorted(_FOREIGN_KEY_NAMES_0007)
+ ),
+ )
+
+
+def _expected_current_ticket_contract() -> _TicketContract:
+ previous = _expected_ticket_contract()
+ current_source_shape = _compact_sql(
+ """
+ (
+ 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 bearer_family_id IS NOT NULL
+ AND length(bearer_family_id)=43
+ AND bearer_family_id NOT GLOB '*[^A-Za-z0-9_-]*'
+ AND bearer_auth_epoch IS NOT NULL
+ AND typeof(bearer_auth_epoch)='integer'
+ AND bearer_auth_epoch >= 1
+ 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 bearer_family_id IS NULL
+ AND bearer_auth_epoch 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'
+ )
+ """
+ )
+ family_index = _IndexContract(
+ "idx_ws_tickets_bearer_family",
+ False,
+ "c",
+ False,
+ (("bearer_family_id", False, "BINARY"),),
+ )
+ family_object = _AttachedObjectContract(
+ "index",
+ "idx_ws_tickets_bearer_family",
+ _TICKET_TABLE,
+ "createindexidx_ws_tickets_bearer_family"
+ "onwebsocket_tickets(bearer_family_id)",
+ )
+ foreign_keys = previous.foreign_keys + (
+ _ForeignKeyContract(
+ "bearer_family_id",
+ "refresh_token_families",
+ "id",
+ "NO ACTION",
+ "CASCADE",
+ "NONE",
+ ),
+ _ForeignKeyContract(
+ "user_id",
+ "refresh_token_families",
+ "user_id",
+ "NO ACTION",
+ "CASCADE",
+ "NONE",
+ ),
+ )
+ return _TicketContract(
+ columns=previous.columns
+ + (
+ _ColumnContract(
+ 12, "bearer_family_id", "TEXT", True, None, 0, 0
+ ),
+ _ColumnContract(
+ 13, "bearer_auth_epoch", "INTEGER", True, None, 0, 0
+ ),
+ ),
+ primary_key=previous.primary_key,
+ foreign_keys=tuple(
+ sorted(
+ foreign_keys,
+ key=lambda item: (
+ item.local_column,
+ item.target_table,
+ item.target_column,
+ item.on_update,
+ item.on_delete,
+ item.match,
+ ),
+ )
+ ),
+ checks=tuple(
+ (
+ name,
+ current_source_shape
+ if name == "ck_ws_ticket_source_shape"
+ else expression,
+ )
+ for name, expression in previous.checks
+ ),
+ indexes=tuple(
+ sorted(previous.indexes + (family_index,), key=lambda item: item.name)
+ ),
+ managed_primary_key_indexes=previous.managed_primary_key_indexes,
+ attached_objects=tuple(
+ sorted(
+ previous.attached_objects + (family_object,),
+ key=lambda item: (item.object_type, item.name),
+ )
),
+ 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()
+_EXPECTED_TICKET_CONTRACT_0007 = _expected_ticket_contract()
+_EXPECTED_TICKET_CONTRACT = _expected_current_ticket_contract()
def _schema_snapshot(path: Path) -> tuple[tuple[str, str, str], ...]:
@@ -832,27 +980,75 @@ def _insert_bearer_ticket(
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,
- ),
- )
+ column_names = {
+ str(row[1])
+ for row in connection.execute(
+ "PRAGMA table_info(websocket_tickets)"
+ )
+ }
+ if "bearer_family_id" in column_names:
+ family_id = "A" * 43
+ connection.execute(
+ """
+ INSERT OR IGNORE INTO refresh_token_families(
+ id, user_id, auth_epoch, state, created_at,
+ absolute_expires_at, revoked_at, revoke_reason,
+ retain_until
+ ) VALUES(?, ?, 1, 'active', ?, ?, NULL, NULL, ?)
+ """,
+ (
+ family_id,
+ "ticket-user",
+ "2025-01-01T00:00:00.000Z",
+ "2099-01-01T00:00:00.000Z",
+ "2100-01-01T00:00:00.000Z",
+ ),
+ )
+ 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, bearer_family_id, bearer_auth_epoch
+ ) VALUES(?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, 1)
+ """,
+ (
+ digest_character * 64,
+ campaign_id,
+ "ticket-user",
+ credential_kind,
+ subject,
+ "synthetic-jti",
+ "2026-01-01T00:05:00.000Z",
+ created_at,
+ expires_at,
+ consumed_at,
+ family_id,
+ ),
+ )
+ else:
+ 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(
@@ -1393,12 +1589,12 @@ async def _runtime_bootstrap(path: Path) -> bool:
await database.close()
-def test_migration_head_is_real_empty_base_to_0008() -> None:
+def test_migration_head_is_real_empty_base_to_0009() -> None:
with _temporary_database("empty-head") as path:
initially_empty = _application_tables(path) == ()
initial_revision_absent = _version(path) is None
_upgrade(path, "head")
- revision_is_current = _version(path) == "0008"
+ revision_is_current = _version(path) == "0009"
exact_contract = _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
enforcement_holds = _exercise_ticket_enforcement(path)
@@ -1406,15 +1602,15 @@ def test_migration_head_is_real_empty_base_to_0008() -> None:
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 0008")
+ _require_fixed(SCHEMA_VERSION == 8, "SQLite schema version is not eight")
+ _require_fixed(revision_is_current, "Alembic head is not revision 0009")
_require_fixed(
exact_contract,
- "fresh revision 0008 ticket fingerprint diverged",
+ "fresh revision 0009 ticket fingerprint diverged",
)
_require_fixed(
enforcement_holds,
- "fresh revision 0008 enforcement diverged",
+ "fresh revision 0009 enforcement diverged",
)
@@ -1430,7 +1626,9 @@ def test_sqlite_0007_ownership_and_0008_compatibility_preserve_data() -> None:
connection.close()
_upgrade(path, "0007")
- upgraded_exact = _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ upgraded_exact = (
+ _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT_0007
+ )
connection = _connect(path)
try:
_insert_bearer_ticket(connection)
@@ -1463,7 +1661,7 @@ def test_sqlite_0007_ownership_and_0008_compatibility_preserve_data() -> None:
_upgrade(path, "0007")
reupgraded_exact = (
_version(path) == "0007"
- and _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ and _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT_0007
)
connection = _connect(path)
try:
@@ -1484,7 +1682,8 @@ def test_sqlite_0007_ownership_and_0008_compatibility_preserve_data() -> None:
ticket_data_after_0008 = _ticket_data_snapshot(path)
revision_0008_is_compatible = (
_version(path) == "0008"
- and ticket_contract_before_0008 == _EXPECTED_TICKET_CONTRACT
+ and ticket_contract_before_0008
+ == _EXPECTED_TICKET_CONTRACT_0007
and ticket_contract_after_0008 == ticket_contract_before_0008
and ticket_data_after_0008 == ticket_data_before_0008
)
@@ -1503,6 +1702,17 @@ def test_sqlite_0007_ownership_and_0008_compatibility_preserve_data() -> None:
"revision 0008 changed the revision 0007 ticket contract",
)
+ _upgrade(path, "0009")
+ revision_0009_is_current = (
+ _version(path) == "0009"
+ and _ticket_contract(path) == _EXPECTED_TICKET_CONTRACT
+ and _ticket_data_snapshot(path) == ticket_data_before_0008
+ )
+ _require_fixed(
+ revision_0009_is_current,
+ "revision 0009 ticket transition changed legacy data",
+ )
+
def test_runtime_bootstrap_and_alembic_have_exact_ticket_parity() -> None:
with _temporary_database("migration") as migration_path:
@@ -1514,7 +1724,7 @@ def test_runtime_bootstrap_and_alembic_have_exact_ticket_parity() -> None:
migration_contract = _ticket_contract(migration_path)
runtime_contract = _ticket_contract(runtime_path)
both_exact = (
- _version(migration_path) == "0008"
+ _version(migration_path) == "0009"
and migration_contract == _EXPECTED_TICKET_CONTRACT
and runtime_contract == _EXPECTED_TICKET_CONTRACT
and migration_contract == runtime_contract