ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
feat(auth): move refresh sessions to secure cookies
Mafifrizi78af22cf82ba
diff --git a/.env.example b/.env.exampleindex a5c611e..a65ec3d 100644--- a/.env.example+++ b/.env.example@@ -9,6 +9,9 @@ ARES_SECRET_KEY=CHANGE_ME_USE_openssl_rand_-hex_32ARES_API_HOST=127.0.0.1ARES_API_PORT=8080ARES_DEBUG=false+# Browser authentication is same-origin only. Production requires one exact+# HTTPS origin; do not use a wildcard, multiple origins, or a path.+ARES_BROWSER_ORIGIN=https://ares.example.invalid# JWT Algorithm# HS256 (default, symmetric): sign + verify with ARES_SECRET_KEY - suitable for single-service@@ -77,10 +80,11 @@ ARES_WEBHOOK_TIMEOUT=5.0 # HTTP timeout secondsARES_WEBHOOK_RETRY=2 # Max retries on failure# Network Security-# Comma-separated allowed CORS origins (no wildcard)-# Dev default: localhost only. Production: set to your actual domain.+# Comma-separated origins for noncredentialed bearer/API-key integrations only.+# Browser cookie authentication never relies on CORS. No wildcard or null.+# Production: set only the exact integration origins you operate.# Example: ARES_CORS_ORIGINS=https://ares.corp.local,https://pentest.corp.local-ARES_CORS_ORIGINS=http://localhost:3000,http://localhost:8080+ARES_CORS_ORIGINS=https://ares.corp.local# Comma-separated trusted hostnames for TrustedHostMiddleware (no wildcard)# Dev default: localhost only. Production: set to your actual hostname/IP.diff --git a/QUICKSTART.md b/QUICKSTART.mdindex 1b04e96..3c9e0ee 100644--- a/QUICKSTART.md+++ b/QUICKSTART.md@@ -125,6 +125,7 @@ ARES requires these values before the first dashboard login:| `ARES_SECRET_KEY` | Signs API sessions and tokens. Generate a random high-entropy value. || `ARES_ENCRYPTION_KEY` | Encrypts sensitive stored data such as vault/checkpoint material. Keep it stable and backed up. || `ARES_DEFAULT_ADMIN_PASSWORD` | Bootstrap password for the first `admin` account only when the user table is empty. |+| `ARES_BROWSER_ORIGIN` | One exact HTTPS production browser origin. Debug mode accepts only the fixed loopback Vite origins. |Windows PowerShell:@@ -145,6 +146,11 @@ export ARES_DEFAULT_ADMIN_PASSWORD="replace-with-your-own-strong-admin-password"For repeated local use, copy `.env.example` to `.env` and fill these valuesthere instead of setting session variables each time.+Browser authentication is same-origin. Production must set+`ARES_BROWSER_ORIGIN` to the public HTTPS origin that serves both dashboard and+API through nginx. The local dashboard launcher uses the fixed loopback Vite+proxy boundary; it does not enable general cross-origin cookie authentication.+Important:- The first admin bootstrap password comes from `ARES_DEFAULT_ADMIN_PASSWORD`@@ -272,28 +278,10 @@ Valid roles:| `recon` | Read-heavy recon identity. Main dashboard execution endpoints remain operator-gated. || `reporter` | Read-only reporting and review. No module execution or user administration. |-PowerShell example:--```powershell-$token = (Invoke-RestMethod `- -Method Post `- -Uri http://127.0.0.1:8080/auth/token `- -ContentType "application/x-www-form-urlencoded" `- -Body "username=admin&password=YOUR_CURRENT_ADMIN_PASSWORD").access_token--$headers = @{ Authorization = "Bearer $token" }--Invoke-RestMethod `- -Method Post `- -Uri http://127.0.0.1:8080/auth/register `- -Headers $headers `- -ContentType "application/json" `- -Body (@{- username = "alice"- password = "StrongPass1!"- role = "operator"- } | ConvertTo-Json)-```+Create accounts with `POST /auth/register` from a current `team_lead` browser+session. Login is same-origin and CSRF protected; use the complete+browser-session example in `docs/api-reference.md`, not a direct password POST+to the backend origin.Passwords must be at least 12 characters and include uppercase, lowercase,number, and special-character content.@@ -451,3 +439,11 @@ authoritative refresh-token families and deliberately invalidates existingbrowser bearer sessions. Stop every worker, take the required backup, upgrade,deploy the matching backend and frontend together, and have operators sign inagain. Revision `0009` is forward-only; do not run mixed `0008`/`0009` workers.++The browser transport uses a host-only HttpOnly refresh cookie and a readable+CSRF cookie/header pair. Access tokens remain in memory, API keys remain the+automation credential, and refresh tokens are no longer returned in JSON or+stored in `sessionStorage`. Deploy the matching backend and frontend together,+drain existing WebSockets, and require existing users to sign in again. A+rollback replaces both components together and does not downgrade the database;+there is no revision `0010` for this transport-only change.diff --git a/README.md b/README.mdindex 7f652cf..ca2fda7 100644--- a/README.md+++ b/README.md@@ -273,6 +273,9 @@ See [docs/modules.md](docs/modules.md).- Database-authoritative JWT access with one refresh-token family per login,one-time rotation, strict replay-family revocation, and no JWT role authority.+- Same-origin browser sessions with memory-only access tokens, host-only+ HttpOnly refresh cookies, strict Origin checks, and constant-time CSRF+ validation. Refresh credentials are never returned in JSON or browser storage.- Current-device and all-device logout plus immediate epoch revocation afterpassword, role, or activation security events.- API key lifecycle with revoked-key removal from dashboard lists.@@ -284,6 +287,12 @@ See [docs/modules.md](docs/modules.md).See [docs/security-model.md](docs/security-model.md).+Production requires one exact HTTPS `ARES_BROWSER_ORIGIN`. Browser auth is+same-origin and CORS remains noncredentialed; use API keys for automation.+Backend and frontend cookie-transport changes must be deployed atomically,+existing sockets drained, and existing users asked to sign in again. No schema+revision beyond `0009` is required for this transport change.+### User Roles And AccountsARES creates the first `admin` account automatically when the user table is@@ -317,28 +326,10 @@ Roles are assigned when a `team_lead` creates a user:| `recon` | Low-risk review/recon identity. | Read-heavy access. The internal module permission matrix marks enumeration, fingerprint, and network modules as recon-safe, but the main dashboard execution endpoints are still operator-gated. || `reporter` | Report reviewer or stakeholder account. | Read-only access to campaign/report/graph-style data. No module execution and no user administration. |-Create additional users through the API while logged in as `team_lead`:--```powershell-$token = (Invoke-RestMethod `- -Method Post `- -Uri http://127.0.0.1:8080/auth/token `- -ContentType "application/x-www-form-urlencoded" `- -Body "username=admin&password=YOUR_CURRENT_ADMIN_PASSWORD").access_token--$headers = @{ Authorization = "Bearer $token" }--Invoke-RestMethod `- -Method Post `- -Uri http://127.0.0.1:8080/auth/register `- -Headers $headers `- -ContentType "application/json" `- -Body (@{- username = "alice"- password = "StrongPass1!"- role = "operator"- } | ConvertTo-Json)-```+Create additional users through `POST /auth/register` while logged in as+`team_lead`. Browser login is cookie/CSRF protected; follow the browser-session+example in [docs/api-reference.md](docs/api-reference.md) instead of posting a+password directly to the backend origin.Valid role values are exactly `team_lead`, `operator`, `recon`, and `reporter`.Passwords must be at least 12 characters and include uppercase, lowercase,diff --git a/ares/api/server.py b/ares/api/server.pyindex e89c16f..1c30de2 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -17,7 +17,6 @@ from __future__ import annotationsimport asyncioimport os-import timefrom collections.abc import AsyncGenerator, Iterable, Mappingfrom contextlib import asynccontextmanagerfrom dataclasses import dataclass, field@@ -57,6 +56,16 @@ from ares.api.rbac import (require_operator,require_team_lead,)+from ares.core.browser_sessions import (+ BrowserRequestContext,+ BrowserSessionBoundaryMiddleware,+ BrowserSessionPolicy,+ build_browser_session_policy,+ canonical_noncredentialed_origins,+ clear_session_cookies,+ publish_prelogin_csrf,+ publish_session_cookies,+)from ares.core.campaign import Campaign, Findingfrom ares.core.config import AresSettings, get_settingsfrom ares.core.engine import AresEngine@@ -67,7 +76,6 @@ from ares.core.token_sessions import (SessionIssueStatus,SessionRevocationStatus,)-from ares.modules.base import normalize_module_metadatafrom ares.core.tracing import get_current_trace_id, instrument_fastapi, setup_tracingfrom ares.db.database import AresDatabasefrom ares.db.websocket_tickets import (@@ -76,6 +84,7 @@ from ares.db.websocket_tickets import (WebSocketTicketPrincipal,is_canonical_websocket_ticket,)+from ares.modules.base import normalize_module_metadatalogger = get_logger("ares.api.server")@@ -322,6 +331,8 @@ async def _get_engagement_lock() -> asyncio.Lock:async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:global _engine, _dbsettings = get_settings()+ app.state.browser_policy = build_browser_session_policy(settings)+ canonical_noncredentialed_origins(settings.cors_origins_list)_db = await AresDatabase.create(db_path=settings.db_path,encryption_key=settings.encryption_key_value,@@ -503,7 +514,7 @@ try:from ares.core.config import get_settings as _get_settings_s = _get_settings()- _cors_origins = _s.cors_origins_list+ _cors_origins = canonical_noncredentialed_origins(_s.cors_origins_list)_trusted_hosts = _s.trusted_hosts_listexcept Exception:_cors_origins = ["http://localhost:3000", "http://localhost:8080"]@@ -512,9 +523,9 @@ except Exception:app.add_middleware(CORSMiddleware,allow_origins=_cors_origins,- allow_credentials=True,+ allow_credentials=False,allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],- allow_headers=["Authorization", "Content-Type", "X-API-Key"],+ allow_headers=["Authorization", "Content-Type", "X-API-Key", "X-ARES-CSRF"],)app.add_middleware(TrustedHostMiddleware,@@ -586,6 +597,14 @@ async def global_rate_limit_middleware(request: Request, call_next: Any) -> Any:return response+# Registered last so browser-auth validation and scrubbing is the first ASGI+# operation for its five routes, before body parsing, logging, or database work.+app.add_middleware(+ BrowserSessionBoundaryMiddleware,+ settings_provider=get_settings,+)++# ── Shared dependencies ───────────────────────────────────────────────────────@@ -724,7 +743,6 @@ async def generic_exception_handler(request: Request, exc: Exception) -> JSONResclass TokenResponse(BaseModel):access_token: str- refresh_token: strtoken_type: str = "bearer" # noqa: S105 - OAuth token type, not a secretexpires_in: int = 3600role: str = ""@@ -732,18 +750,58 @@ class TokenResponse(BaseModel):session_coordination_key: str-class RefreshRequest(BaseModel):- refresh_token: str+def _browser_context(request: Request) -> BrowserRequestContext:+ context = getattr(request.state, "browser_session", None)+ if not isinstance(context, BrowserRequestContext):+ raise HTTPException(403, "Browser request rejected")+ return context+++def _browser_policy(request: Request) -> BrowserSessionPolicy:+ policy = getattr(request.state, "browser_policy", None)+ if not isinstance(policy, BrowserSessionPolicy):+ raise HTTPException(503, "Browser authentication unavailable")+ return policy+++def _token_response_content(session: Any, settings: AresSettings) -> dict[str, Any]:+ return {+ "access_token": session.access_token,+ "token_type": "bearer",+ "expires_in": settings.ares_jwt_expire_minutes * 60,+ "role": session.role,+ "refresh_generation": session.refresh_generation,+ "session_coordination_key": session.coordination_key,+ }+++def _auth_json_response(content: dict[str, Any], *, status_code: int = 200) -> JSONResponse:+ return JSONResponse(+ status_code=status_code,+ content=content,+ headers={"Cache-Control": "no-store", "Pragma": "no-cache"},+ )++[email protected]("/auth/csrf", status_code=204, tags=["auth"])+async def bootstrap_browser_csrf(request: Request) -> Response:+ response = Response(+ status_code=204,+ headers={"Cache-Control": "no-store", "Pragma": "no-cache"},+ )+ publish_prelogin_csrf(response, _browser_policy(request))+ return response[email protected]("/auth/token", response_model=TokenResponse, tags=["auth"])[email protected]("/auth/token", tags=["auth"])async def login(request: Request,form: OAuth2PasswordRequestForm = Depends(),settings: AresSettings = Depends(get_settings),db: AresDatabase = Depends(get_db),-) -> TokenResponse:- """Authenticate. Returns access_token (60m) + refresh_token (30d)."""+) -> JSONResponse:+ """Authenticate and publish the committed refresh session as cookies."""+ _browser_context(request)ip = request.client.host if request.client else "unknown"# Double-check: per-IP AND per-username to block both distributed and targeted attacksallowed_ip, _ = await _limiter.is_allowed_async(f"auth:{ip}", RATE_LIMITS["auth"])@@ -781,24 +839,33 @@ async def login(if result.status is not SessionIssueStatus.ISSUED or result.session is None:raise HTTPException(401, "Invalid credentials")session = result.session- return TokenResponse(- access_token=session.access_token,+ response = _auth_json_response(_token_response_content(session, settings))+ if not publish_session_cookies(+ response,+ _browser_policy(request),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,- )+ absolute_expiry=session.absolute_expires_at,+ ):+ raise HTTPException(401, "Session is not valid")+ return response[email protected]("/auth/refresh", response_model=TokenResponse, tags=["auth"])[email protected]("/auth/refresh", tags=["auth"])async def refresh_access_token(request: Request,- body: RefreshRequest,settings: AresSettings = Depends(get_settings),db: AresDatabase = Depends(get_db),-) -> TokenResponse:- """Rotate refresh token. Old token revoked; new access + refresh token issued."""+) -> JSONResponse:+ """Rotate the single canonical refresh cookie."""+ context = _browser_context(request)+ policy = _browser_policy(request)+ if context.refresh_token is None:+ response = _auth_json_response(+ {"code": 401, "detail": "Session is not valid", "type": "api_error"},+ status_code=401,+ )+ clear_session_cookies(response, policy)+ return responseip = request.client.host if request.client else "unknown"allowed, _ = await _limiter.is_allowed_async(f"refresh:{ip}", RATE_LIMITS["auth"])if not allowed:@@ -816,59 +883,63 @@ async def refresh_access_token()try:- result = await db.rotate_refresh_session(body.refresh_token, _token_factory)+ result = await db.rotate_refresh_session(context.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 Noneif result.status is not RefreshRotationStatus.ROTATED or result.session is None:- raise HTTPException(401, "Refresh token invalid or expired")+ response = _auth_json_response(+ {"code": 401, "detail": "Session is not valid", "type": "api_error"},+ status_code=401,+ )+ clear_session_cookies(response, policy)+ return responsesession = result.session- return TokenResponse(- access_token=session.access_token,+ response = _auth_json_response(_token_response_content(session, settings))+ if not publish_session_cookies(+ response,+ policy,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,- )+ absolute_expiry=session.absolute_expires_at,+ ):+ raise HTTPException(401, "Session is not valid")+ return response@app.post("/auth/logout", tags=["auth"])async def logout(request: Request,- actor: AuthenticatedUser = Depends(require_any_auth()),- settings: AresSettings = Depends(get_settings),db: AresDatabase = Depends(get_db),-) -> dict[str, str]:- """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"}+) -> Response:+ """Idempotently revoke the family named by the refresh cookie."""+ context = _browser_context(request)+ policy = _browser_policy(request)+ if context.refresh_token is not None:+ try:+ await db.revoke_refresh_cookie_session(context.refresh_token)+ except Exception as exc:+ logger.warning("logout_current_failed", error_type=type(exc).__name__)+ raise HTTPException(503, "Authentication service unavailable") from None+ response = Response(+ status_code=204,+ headers={"Cache-Control": "no-store", "Pragma": "no-cache"},+ )+ clear_session_cookies(response, policy)+ return response@app.post("/auth/logout-all", tags=["auth"])async def logout_all(+ request: Request,actor: AuthenticatedUser = Depends(require_any_auth()), # noqa: B008db: AresDatabase = Depends(get_db), # noqa: B008-) -> dict[str, str]:+) -> Response:"""Revoke every bearer family by incrementing the user's auth epoch."""+ _browser_context(request)+ policy = _browser_policy(request)source = actor.websocket_ticket_sourceif actor.is_api_key or source is None:- return {"status": "ok"}+ raise HTTPException(401, "Not authenticated")try:result = await db.revoke_all_sessions(user_id=source.user_id,@@ -880,7 +951,12 @@ async def logout_all(raise HTTPException(503, "Authentication service unavailable") from Noneif result.status is SessionRevocationStatus.INVALID:raise HTTPException(401, "Not authenticated")- return {"status": "ok"}+ response = Response(+ status_code=204,+ headers={"Cache-Control": "no-store", "Pragma": "no-cache"},+ )+ clear_session_cookies(response, policy)+ return responsedef _validate_password_complexity(v: str) -> str:diff --git a/ares/core/browser_sessions.py b/ares/core/browser_sessions.pynew file mode 100644index 0000000..17996b9--- /dev/null+++ b/ares/core/browser_sessions.py@@ -0,0 +1,521 @@+"""Same-origin browser refresh-cookie and CSRF security contracts."""+from __future__ import annotations++import base64+import hmac+import re+import secrets+from dataclasses import dataclass, field+from datetime import datetime, timedelta, timezone+from http.cookies import _is_legal_key+from typing import Any, Final+from urllib.parse import urlsplit++from starlette.responses import JSONResponse, Response+from starlette.types import ASGIApp, Message, Receive, Scope, Send++CSRF_RANDOM_BYTES: Final[int] = 32+CSRF_TOKEN_LENGTH: Final[int] = 43+PRELOGIN_CSRF_LIFETIME_SECONDS: Final[int] = 600+MAX_REFRESH_COOKIE_AGE_SECONDS: Final[int] = 2_592_000++PRODUCTION_REFRESH_COOKIE: Final[str] = "__Host-ares-refresh"+PRODUCTION_CSRF_COOKIE: Final[str] = "__Host-ares-csrf"+DEVELOPMENT_REFRESH_COOKIE: Final[str] = "ares-dev-refresh"+DEVELOPMENT_CSRF_COOKIE: Final[str] = "ares-dev-csrf"++CSRF_HEADER: Final[bytes] = b"x-ares-csrf"+_AUTH_PATHS: Final[frozenset[str]] = frozenset(+ {"/auth/csrf", "/auth/token", "/auth/refresh", "/auth/logout", "/auth/logout-all"}+)+_PROTECTED_POST_PATHS: Final[frozenset[str]] = frozenset(+ {"/auth/token", "/auth/refresh", "/auth/logout", "/auth/logout-all"}+)+_REFRESH_TOKEN_RE: Final[re.Pattern[str]] = re.compile(r"[A-Za-z0-9_-]{64}\Z")+_CSRF_TOKEN_RE: Final[re.Pattern[str]] = re.compile(r"[A-Za-z0-9_-]{43}\Z")+_FORBIDDEN_REFRESH_HEADERS: Final[frozenset[bytes]] = frozenset(+ {b"refresh-token", b"x-refresh-token", b"x-ares-refresh-token"}+)+_DEV_ORIGINS: Final[frozenset[str]] = frozenset(+ {"http://127.0.0.1:5173", "http://localhost:5173"}+)+++class BrowserSessionConfigurationError(RuntimeError):+ """Fixed startup failure for an invalid browser-auth boundary."""++ def __init__(self) -> None:+ super().__init__("browser session configuration invalid")+++@dataclass(frozen=True, slots=True, eq=False)+class BrowserSessionPolicy:+ """Validated non-secret browser origin and immutable cookie policy."""++ origin: str = field(repr=False)+ authority: str = field(repr=False)+ refresh_cookie_name: str+ csrf_cookie_name: str+ secure: bool+ debug: bool+++@dataclass(frozen=True, slots=True, eq=False)+class BrowserRequestContext:+ """Sanitized request decision installed by the outer ASGI boundary."""++ refresh_token: str | None = field(default=None, repr=False)+++def _canonical_base64url(value: object, *, encoded_length: int, byte_length: int) -> bool:+ if not isinstance(value, str) or len(value) != encoded_length:+ return False+ pattern = _CSRF_TOKEN_RE if encoded_length == CSRF_TOKEN_LENGTH else _REFRESH_TOKEN_RE+ if pattern.fullmatch(value) is None:+ return False+ try:+ decoded = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))+ except (ValueError, TypeError):+ return False+ canonical = base64.urlsafe_b64encode(decoded).rstrip(b"=").decode("ascii")+ return len(decoded) == byte_length and hmac.compare_digest(canonical, value)+++def is_canonical_csrf_token(value: object) -> bool:+ return _canonical_base64url(value, encoded_length=43, byte_length=32)+++def is_canonical_refresh_token(value: object) -> bool:+ return _canonical_base64url(value, encoded_length=64, byte_length=48)+++def generate_csrf_token() -> str:+ encoded = base64.urlsafe_b64encode(secrets.token_bytes(CSRF_RANDOM_BYTES))+ value = encoded.rstrip(b"=").decode("ascii")+ if not is_canonical_csrf_token(value):+ raise RuntimeError("csrf generation failed")+ return value+++def _canonical_origin(raw: object, *, debug: bool) -> tuple[str, str]:+ if not isinstance(raw, str) or not raw or raw != raw.strip() or "," in raw:+ raise BrowserSessionConfigurationError+ try:+ parsed = urlsplit(raw)+ port = parsed.port+ except (TypeError, ValueError):+ raise BrowserSessionConfigurationError from None+ if (+ parsed.username is not None+ or parsed.password is not None+ or parsed.query+ or parsed.fragment+ or parsed.path not in {"", "/"}+ or parsed.hostname is None+ or parsed.hostname.endswith(".")+ ):+ raise BrowserSessionConfigurationError+ try:+ host = parsed.hostname.encode("ascii").decode("ascii").lower()+ except UnicodeError:+ raise BrowserSessionConfigurationError from None+ if host != parsed.hostname.lower():+ raise BrowserSessionConfigurationError+ if debug:+ if parsed.scheme != "http" or raw not in _DEV_ORIGINS:+ raise BrowserSessionConfigurationError+ elif parsed.scheme != "https":+ raise BrowserSessionConfigurationError+ default_port = 80 if parsed.scheme == "http" else 443+ if port == default_port:+ raise BrowserSessionConfigurationError+ authority = host if port is None else f"{host}:{port}"+ canonical = f"{parsed.scheme}://{authority}"+ if canonical != raw:+ raise BrowserSessionConfigurationError+ return canonical, authority+++def build_browser_session_policy(settings: Any) -> BrowserSessionPolicy:+ debug = bool(settings.ares_debug)+ configured = str(settings.ares_browser_origin or "")+ if debug and not configured:+ configured = "http://127.0.0.1:5173"+ origin, authority = _canonical_origin(configured, debug=debug)+ trusted_hosts = tuple(str(value).lower() for value in settings.trusted_hosts_list)+ origin_host = authority.rsplit(":", 1)[0]+ if debug:+ if any(value not in {"localhost", "127.0.0.1"} for value in trusted_hosts):+ raise BrowserSessionConfigurationError+ elif origin_host not in trusted_hosts:+ raise BrowserSessionConfigurationError+ return BrowserSessionPolicy(+ origin=origin,+ authority=authority,+ refresh_cookie_name=(DEVELOPMENT_REFRESH_COOKIE if debug else PRODUCTION_REFRESH_COOKIE),+ csrf_cookie_name=(DEVELOPMENT_CSRF_COOKIE if debug else PRODUCTION_CSRF_COOKIE),+ secure=not debug,+ debug=debug,+ )+++def canonical_noncredentialed_origins(values: list[str]) -> list[str]:+ result: list[str] = []+ for value in values:+ if not isinstance(value, str) or not value or value != value.strip() or "," in value:+ raise BrowserSessionConfigurationError+ try:+ parsed = urlsplit(value)+ port = parsed.port+ except (TypeError, ValueError):+ raise BrowserSessionConfigurationError from None+ if (+ parsed.scheme not in {"http", "https"}+ or parsed.hostname is None+ or parsed.hostname.endswith(".")+ or parsed.username is not None+ or parsed.password is not None+ or parsed.path not in {"", "/"}+ or parsed.query+ or parsed.fragment+ ):+ raise BrowserSessionConfigurationError+ try:+ host = parsed.hostname.encode("ascii").decode("ascii").lower()+ except UnicodeError:+ raise BrowserSessionConfigurationError from None+ default_port = 80 if parsed.scheme == "http" else 443+ if port == default_port:+ raise BrowserSessionConfigurationError+ authority = host if port is None else f"{host}:{port}"+ origin = f"{parsed.scheme}://{authority}"+ if origin != value:+ raise BrowserSessionConfigurationError+ if origin in result or origin == "null" or "*" in origin:+ raise BrowserSessionConfigurationError+ result.append(origin)+ return result+++def remaining_cookie_seconds(absolute_expiry: datetime, *, now: datetime | None = None) -> int:+ current = now or datetime.now(timezone.utc)+ if absolute_expiry.tzinfo is None or absolute_expiry.utcoffset() is None:+ raise ValueError("family expiry must be timezone-aware")+ delta = absolute_expiry.astimezone(timezone.utc) - current.astimezone(timezone.utc)+ remaining = int(delta.total_seconds())+ return max(0, min(MAX_REFRESH_COOKIE_AGE_SECONDS, remaining))+++def _set_cookie(+ response: Response,+ *,+ name: str,+ value: str,+ max_age: int,+ secure: bool,+ httponly: bool,+) -> None:+ response.set_cookie(+ key=name,+ value=value,+ max_age=max_age,+ expires=datetime.now(timezone.utc) + timedelta(seconds=max_age),+ path="/",+ secure=secure,+ httponly=httponly,+ samesite="strict",+ )+++def publish_prelogin_csrf(response: Response, policy: BrowserSessionPolicy) -> None:+ _set_cookie(+ response,+ name=policy.csrf_cookie_name,+ value=generate_csrf_token(),+ max_age=PRELOGIN_CSRF_LIFETIME_SECONDS,+ secure=policy.secure,+ httponly=False,+ )+++def publish_session_cookies(+ response: Response,+ policy: BrowserSessionPolicy,+ *,+ refresh_token: str,+ absolute_expiry: datetime,+) -> bool:+ if not is_canonical_refresh_token(refresh_token):+ raise ValueError("invalid refresh token")+ max_age = remaining_cookie_seconds(absolute_expiry)+ if max_age <= 0:+ return False+ _set_cookie(+ response,+ name=policy.refresh_cookie_name,+ value=refresh_token,+ max_age=max_age,+ secure=policy.secure,+ httponly=True,+ )+ _set_cookie(+ response,+ name=policy.csrf_cookie_name,+ value=generate_csrf_token(),+ max_age=max_age,+ secure=policy.secure,+ httponly=False,+ )+ return True+++def clear_session_cookies(response: Response, policy: BrowserSessionPolicy) -> None:+ for name, httponly in (+ (policy.refresh_cookie_name, True),+ (policy.csrf_cookie_name, False),+ ):+ response.set_cookie(+ key=name,+ value="",+ max_age=0,+ expires=datetime(1970, 1, 1, tzinfo=timezone.utc),+ path="/",+ secure=policy.secure,+ httponly=httponly,+ samesite="strict",+ )+++def _fixed_response(status: int, detail: str) -> JSONResponse:+ return JSONResponse(+ status_code=status,+ content={"code": status, "detail": detail, "type": "api_error"},+ headers={"Cache-Control": "no-store", "Pragma": "no-cache"},+ )+++def _header_values(headers: tuple[tuple[bytes, bytes], ...], name: bytes) -> list[bytes]:+ return [value for key, value in headers if key.lower() == name]+++def _decode_single_header(headers: tuple[tuple[bytes, bytes], ...], name: bytes) -> str | None:+ values = _header_values(headers, name)+ if len(values) != 1:+ return None+ try:+ return values[0].decode("ascii")+ except UnicodeDecodeError:+ return None+++def _parse_canonical_cookies(+ headers: tuple[tuple[bytes, bytes], ...], policy: BrowserSessionPolicy+) -> tuple[str | None, str | None, bool]:+ found: dict[str, list[str]] = {+ policy.refresh_cookie_name: [],+ policy.csrf_cookie_name: [],+ }+ for raw in _header_values(headers, b"cookie"):+ try:+ text = raw.decode("ascii")+ except UnicodeDecodeError:+ return None, None, False+ for part in text.split(";"):+ item = part.strip()+ if not item or "=" not in item:+ continue+ name, value = item.split("=", 1)+ if not name or not _is_legal_key(name):+ return None, None, False+ if name in found:+ found[name].append(value)+ if any(len(values) > 1 for values in found.values()):+ return None, None, False+ refresh = found[policy.refresh_cookie_name][0] if found[policy.refresh_cookie_name] else None+ csrf = found[policy.csrf_cookie_name][0] if found[policy.csrf_cookie_name] else None+ return refresh, csrf, True+++def _canonical_host(value: str, *, scheme: str) -> str | None:+ if not value or value != value.strip() or "," in value or "@" in value:+ return None+ try:+ parsed = urlsplit(f"{scheme}://{value}")+ port = parsed.port+ except ValueError:+ return None+ if parsed.hostname is None or parsed.hostname.endswith("."):+ return None+ try:+ host = parsed.hostname.encode("ascii").decode("ascii").lower()+ except UnicodeError:+ return None+ default_port = 80 if scheme == "http" else 443+ if port == default_port:+ port = None+ return host if port is None else f"{host}:{port}"+++class BrowserSessionBoundaryMiddleware:+ """Outermost sync-first browser-auth request boundary."""++ def __init__(self, app: ASGIApp, settings_provider: Any) -> None:+ self.app = app+ self._settings_provider = settings_provider++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http" or scope.get("path") not in _AUTH_PATHS:+ await self.app(scope, receive, send)+ return++ path = str(scope["path"])+ method = str(scope.get("method", "")).upper()+ raw_query = bytes(scope.get("query_string", b""))+ scope["query_string"] = b""+ had_query = bool(raw_query)+ del raw_query++ headers = tuple(scope.get("headers", ()))+ scrubbed_names = {b"cookie", b"origin", CSRF_HEADER}+ if path != "/auth/logout-all":+ scrubbed_names.add(b"authorization")+ if path == "/auth/refresh":+ scrubbed_names.update(_FORBIDDEN_REFRESH_HEADERS)+ scope["headers"] = tuple(+ (key, value)+ for key, value in headers+ if key.lower() not in scrubbed_names+ )+ del scrubbed_names++ try:+ policy = build_browser_session_policy(self._settings_provider())+ except BrowserSessionConfigurationError:+ del headers+ await _fixed_response(503, "Browser authentication unavailable")(scope, receive, send)+ return++ origin_values = _header_values(headers, b"origin")+ allow_missing_origin = path == "/auth/csrf" and method == "GET"+ if len(origin_values) == 0 and allow_missing_origin:+ origin_ok = True+ elif len(origin_values) == 1:+ try:+ origin_ok = hmac.compare_digest(origin_values[0].decode("ascii"), policy.origin)+ except UnicodeDecodeError:+ origin_ok = False+ else:+ origin_ok = False+ host = _decode_single_header(headers, b"host")+ scheme = policy.origin.split(":", 1)[0]+ host_ok = (+ host is not None+ and _canonical_host(host, scheme=scheme) == policy.authority+ )+ fetch_site = _header_values(headers, b"sec-fetch-site")+ fetch_ok = not fetch_site or (len(fetch_site) == 1 and fetch_site[0] == b"same-origin")+ if not origin_ok or not host_ok or not fetch_ok:+ del headers+ await _fixed_response(403, "Browser request rejected")(scope, receive, send)+ return+ if had_query:+ del headers+ await _fixed_response(400, "Browser request format invalid")(scope, receive, send)+ return++ refresh, csrf_cookie, cookies_ok = _parse_canonical_cookies(headers, policy)+ if path in _PROTECTED_POST_PATHS:+ csrf_values = _header_values(headers, CSRF_HEADER)+ csrf_header: str | None = None+ if len(csrf_values) == 1:+ try:+ csrf_header = csrf_values[0].decode("ascii")+ except UnicodeDecodeError:+ csrf_header = None+ csrf_ok = (+ cookies_ok+ and is_canonical_csrf_token(csrf_cookie)+ and is_canonical_csrf_token(csrf_header)+ and hmac.compare_digest(str(csrf_cookie), str(csrf_header))+ )+ if not csrf_ok:+ del headers, refresh, csrf_cookie, csrf_header+ await _fixed_response(403, "Browser request rejected")(scope, receive, send)+ return++ if path == "/auth/refresh":+ forbidden_header = any(+ _header_values(headers, name)+ for name in _FORBIDDEN_REFRESH_HEADERS+ )+ authorization_present = bool(_header_values(headers, b"authorization"))+ if forbidden_header or authorization_present:+ del headers, refresh, csrf_cookie+ await _fixed_response(400, "Refresh transport invalid")(scope, receive, send)+ return+ if refresh is not None and not is_canonical_refresh_token(refresh):+ response = _fixed_response(401, "Session is not valid")+ clear_session_cookies(response, policy)+ del headers, refresh, csrf_cookie+ await response(scope, receive, send)+ return++ state = scope.setdefault("state", {})+ state["browser_session"] = BrowserRequestContext(refresh_token=refresh)+ state["browser_policy"] = policy+ del headers, refresh, csrf_cookie+ if path in {"/auth/refresh", "/auth/logout", "/auth/logout-all"}:+ body_present = False+ completed = False+ for _ in range(8):+ message = await receive()+ if message.get("type") != "http.request" or bool(+ message.get("body", b"")+ ):+ body_present = True+ completed = not bool(message.get("more_body", False))+ del message+ if completed or body_present:+ break+ if not completed:+ body_present = True+ if body_present:+ await _fixed_response(400, "Browser request format invalid")(+ scope, receive, send+ )+ return+ delivered = False++ async def _empty_receive() -> Message:+ nonlocal delivered+ if delivered:+ return {"type": "http.disconnect"}+ delivered = True+ return {"type": "http.request", "body": b"", "more_body": False}++ receive = _empty_receive+ await self.app(scope, receive, send)+++__all__ = [+ "BrowserRequestContext",+ "BrowserSessionBoundaryMiddleware",+ "BrowserSessionConfigurationError",+ "BrowserSessionPolicy",+ "CSRF_HEADER",+ "DEVELOPMENT_CSRF_COOKIE",+ "DEVELOPMENT_REFRESH_COOKIE",+ "MAX_REFRESH_COOKIE_AGE_SECONDS",+ "PRELOGIN_CSRF_LIFETIME_SECONDS",+ "PRODUCTION_CSRF_COOKIE",+ "PRODUCTION_REFRESH_COOKIE",+ "build_browser_session_policy",+ "canonical_noncredentialed_origins",+ "clear_session_cookies",+ "generate_csrf_token",+ "is_canonical_csrf_token",+ "is_canonical_refresh_token",+ "publish_prelogin_csrf",+ "publish_session_cookies",+ "remaining_cookie_seconds",+]diff --git a/ares/core/config.py b/ares/core/config.pyindex a2e7199..b9e1be7 100644--- a/ares/core/config.py+++ b/ares/core/config.py@@ -121,6 +121,12 @@ class AresSettings(BaseSettings):default="http://localhost:3000,http://localhost:8080",description="Comma-separated allowed CORS origins. Example: https://ares.corp.local",)+ ares_browser_origin: str = Field(+ default="",+ description=(+ "Exact same-origin browser boundary. Required outside explicit debug mode."+ ),+ )ares_trusted_hosts: str = Field(default="localhost,127.0.0.1",description="Comma-separated trusted hostnames. Example: ares.corp.local,10.0.0.5",diff --git a/ares/core/token_sessions.py b/ares/core/token_sessions.pyindex 3218c24..2c87b01 100644--- a/ares/core/token_sessions.py+++ b/ares/core/token_sessions.py@@ -138,6 +138,7 @@ class IssuedTokenSession:subject: str = field(repr=False)family_id: str = field(repr=False)auth_epoch: int = field(repr=False)+ absolute_expires_at: datetime = field(repr=False)refresh_generation: introle: str@@ -154,6 +155,12 @@ class IssuedTokenSession:raise ValueError("invalid authentication epoch")if isinstance(self.refresh_generation, bool) or self.refresh_generation < 0:raise ValueError("invalid refresh generation")+ if (+ not isinstance(self.absolute_expires_at, datetime)+ or self.absolute_expires_at.tzinfo is None+ or self.absolute_expires_at.utcoffset() is None+ ):+ raise ValueError("invalid family expiry")@propertydef coordination_key(self) -> str:diff --git a/ares/db/database.py b/ares/db/database.pyindex b095f7e..7ac4ce2 100644--- a/ares/db/database.py+++ b/ares/db/database.py@@ -2586,13 +2586,13 @@ class AresDatabase:)return result- async def _insert_initial_family_token(+ async def _insert_initial_family_token_with_expiry(self,tx: aiosqlite.Connection,*,user_id: str,auth_epoch: int,- ) -> tuple[str, str]:+ ) -> tuple[str, str, datetime]:family_id = generate_family_id()raw_token = generate_refresh_token()token_hash = hash_refresh_token(raw_token)@@ -2609,6 +2609,20 @@ class AresDatabase:"generation,state,revoked_at) VALUES(?,?,0,?,?,?,NULL,0,'active',NULL)",(token_hash, user_id, expires, created, family_id),)+ return family_id, raw_token, parse_sqlite_utc(expires)++ async def _insert_initial_family_token(+ self,+ tx: aiosqlite.Connection,+ *,+ user_id: str,+ auth_epoch: int,+ ) -> tuple[str, str]:+ family_id, raw_token, _ = await self._insert_initial_family_token_with_expiry(+ tx,+ user_id=user_id,+ auth_epoch=auth_epoch,+ )return family_id, raw_tokenasync def create_refresh_token(@@ -2649,10 +2663,12 @@ class AresDatabase: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"]),+ family_id, raw_token, absolute_expiry = (+ await self._insert_initial_family_token_with_expiry(+ tx,+ user_id=row["id"],+ auth_epoch=int(row["auth_epoch"]),+ ))access_token = token_factory({@@ -2678,6 +2694,7 @@ class AresDatabase:subject=row["username"],family_id=family_id,auth_epoch=int(row["auth_epoch"]),+ absolute_expires_at=absolute_expiry,refresh_generation=0,role=row["role"],),@@ -2877,6 +2894,7 @@ class AresDatabase:subject=row["username"],family_id=row["family_id"],auth_epoch=int(row["auth_epoch"]),+ absolute_expires_at=parse_sqlite_utc(row["absolute_expires_at"]),refresh_generation=generation,role=row["role"],),@@ -3161,6 +3179,48 @@ class AresDatabase:return await self._run_refresh_family_transaction(_revoke)+ async def revoke_refresh_cookie_session(+ self,+ raw_token: str,+ ) -> SessionRevocationResult:+ """Revoke the family identified only by a browser refresh cookie."""+ token_hash = hash_refresh_token(raw_token)++ async def _revoke(tx: aiosqlite.Connection) -> SessionRevocationResult:+ async with tx.execute(+ "SELECT rt.user_id,rt.family_id,rt.state,f.state AS family_state "+ "FROM refresh_tokens AS rt JOIN refresh_token_families AS f "+ "ON f.id=rt.family_id AND f.user_id=rt.user_id WHERE rt.id=?",+ (token_hash,),+ ) as cursor:+ row = await cursor.fetchone()+ if row is None:+ return SessionRevocationResult(SessionRevocationStatus.INVALID)+ if row["family_state"] != "active":+ return SessionRevocationResult(SessionRevocationStatus.ALREADY_REVOKED)+ reason = "logout_current" if row["state"] == "active" else "replay"+ changed = await self._revoke_family_rows(+ tx,+ user_id=row["user_id"],+ family_id=row["family_id"],+ reason=reason,+ )+ if changed:+ action = (+ "logout_cookie_family_revoked"+ if reason == "logout_current"+ else "logout_cookie_replay_family_revoked"+ )+ await tx.execute(+ "INSERT INTO audit_log(actor,action,detail) VALUES("+ "'auth-system',?,'')",+ (action,),+ )+ return SessionRevocationResult(SessionRevocationStatus.REVOKED)+ return SessionRevocationResult(SessionRevocationStatus.ALREADY_REVOKED)++ return await self._run_refresh_family_transaction(_revoke)+async def revoke_all_sessions(self,*,diff --git a/ares/db/postgres.py b/ares/db/postgres.pyindex ddafb2c..d8b09c4 100644--- a/ares/db/postgres.py+++ b/ares/db/postgres.py@@ -5560,12 +5560,12 @@ class PostgresDatabase:# ── Refresh tokens ───────────────────────────────────────────────────────@staticmethod- async def _insert_initial_family_token(+ async def _insert_initial_family_token_with_expiry(conn: Any,*,user_id: str,auth_epoch: int,- ) -> tuple[str, str]:+ ) -> tuple[str, str, datetime]:family_id = generate_family_id()raw_token = generate_refresh_token()token_hash = hash_refresh_token(raw_token)@@ -5593,6 +5593,22 @@ class PostgresDatabase:now,family_id,)+ return family_id, raw_token, absolute_expiry++ @staticmethod+ async def _insert_initial_family_token(+ conn: Any,+ *,+ user_id: str,+ auth_epoch: int,+ ) -> tuple[str, str]:+ family_id, raw_token, _ = (+ await PostgresDatabase._insert_initial_family_token_with_expiry(+ conn,+ user_id=user_id,+ auth_epoch=auth_epoch,+ )+ )return family_id, raw_tokenasync def create_refresh_token(@@ -5636,10 +5652,12 @@ class PostgresDatabase: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"]),+ family_id, raw_token, absolute_expiry = (+ await self._insert_initial_family_token_with_expiry(+ conn,+ user_id=row["id"],+ auth_epoch=int(row["auth_epoch"]),+ ))access_token = token_factory({@@ -5665,6 +5683,7 @@ class PostgresDatabase:subject=row["username"],family_id=family_id,auth_epoch=int(row["auth_epoch"]),+ absolute_expires_at=absolute_expiry,refresh_generation=0,role=row["role"],),@@ -5799,6 +5818,7 @@ class PostgresDatabase:subject=row["username"],family_id=row["family_id"],auth_epoch=int(row["auth_epoch"]),+ absolute_expires_at=row["absolute_expires_at"],refresh_generation=generation,role=row["role"],),@@ -5903,6 +5923,49 @@ class PostgresDatabase:else SessionRevocationStatus.ALREADY_REVOKED)+ async def revoke_refresh_cookie_session(+ self,+ raw_token: str,+ ) -> SessionRevocationResult:+ """Revoke the family identified only by a browser refresh cookie."""+ token_hash = hash_refresh_token(raw_token)+ async with self._pool.acquire() as conn:+ async with conn.transaction():+ row = await conn.fetchrow(+ "SELECT rt.user_id,rt.family_id,rt.state,f.state AS family_state "+ "FROM refresh_tokens AS rt JOIN refresh_token_families AS f "+ "ON f.id=rt.family_id AND f.user_id=rt.user_id "+ "WHERE rt.id=$1 FOR UPDATE OF rt,f",+ token_hash,+ )+ if row is None:+ return SessionRevocationResult(SessionRevocationStatus.INVALID)+ if row["family_state"] != "active":+ return SessionRevocationResult(+ SessionRevocationStatus.ALREADY_REVOKED+ )+ reason = "logout_current" if row["state"] == "active" else "replay"+ changed = await self._revoke_family_rows(+ conn,+ family_id=row["family_id"],+ reason=reason,+ )+ if changed:+ action = (+ "logout_cookie_family_revoked"+ if reason == "logout_current"+ else "logout_cookie_replay_family_revoked"+ )+ await conn.execute(+ "INSERT INTO audit_log(actor,action,detail) VALUES("+ "'auth-system',$1,'')",+ action,+ )+ return SessionRevocationResult(SessionRevocationStatus.REVOKED)+ return SessionRevocationResult(+ SessionRevocationStatus.ALREADY_REVOKED+ )+async def revoke_all_sessions(self,*,diff --git a/docker/README.md b/docker/README.mdindex ee75c86..69bbdf3 100644--- a/docker/README.md+++ b/docker/README.md@@ -32,6 +32,10 @@ Development compose starts:- `ares-frontend` at `http://localhost:5173/dashboard`The Vite server proxies API and WebSocket traffic to `ares-api`.+Development browser cookies use the distinct `ares-dev-*` names only while+`ARES_DEBUG=true`, the configured origin is exactly `http://localhost:5173`,+and the request host is loopback. Production requires one exact HTTPS+`ARES_BROWSER_ORIGIN`; browser auth is same-origin and does not use CORS.## EnvironmentCopy `.env.example` to `.env` and fill in secrets before starting either stack.@@ -51,3 +55,15 @@ container before the database upgrade, then start the matching backend andfrontend together. Mixed workers are unsupported because managed ownership isrevision-exact. A container-image rollback does not downgrade the additiveschema; return to a compatible forward image instead.++## Browser-session rollout++Refresh sessions use host-only HttpOnly cookies and CSRF/Origin validation.+Access tokens remain in browser memory, and API keys remain the automation+credential. Deploy backend and frontend atomically, drain existing sockets,+and require existing users to sign in again; the old browser refresh value is+deleted from `sessionStorage` and is not bridged into the cookie transport.+Mixed versions are unsupported. No revision `0010` is introduced: Alembic+remains at `0009`, so rollback replaces backend and frontend together without a+database downgrade. The nginx TLS log and HTTP redirect use `$uri`, and the+redirect drops query strings instead of reflecting them.diff --git a/docker/docker-compose.dev.yml b/docker/docker-compose.dev.ymlindex a3d75c8..7d12051 100644--- a/docker/docker-compose.dev.yml+++ b/docker/docker-compose.dev.yml@@ -24,6 +24,12 @@ services:ARES_DATABASE_URL: "${ARES_DATABASE_URL:-sqlite+aiosqlite:////home/ares/.ares/ares.db}"ARES_API_HOST: "0.0.0.0"ARES_API_PORT: "8080"+ # Locked browser-cookie development boundary: Vite is the browser origin+ # and proxies /auth, API, and WebSocket traffic to this service.+ ARES_DEBUG: "true"+ ARES_BROWSER_ORIGIN: "http://localhost:5173"+ ARES_TRUSTED_HOSTS: "localhost,127.0.0.1"+ ARES_CORS_ORIGINS: "http://localhost:5173"env_file:- path: ../.envrequired: false # Don't fail if .env doesn't exist — env block above provides defaultsdiff --git a/docker/nginx.conf b/docker/nginx.confindex c760ecf..10d8d61 100644--- a/docker/nginx.conf+++ b/docker/nginx.conf@@ -15,12 +15,14 @@ map $request_uri $redacted_uri {# Using server_name _ (catch-all) accepts connections from any hostname.# Example: server_name ares.corp.local;-# HTTP → HTTPS redirect. $request_uri reflects queries on this unsupported-# plaintext boundary; production clients must connect with HTTPS/WSS directly.+# HTTP to HTTPS redirect deliberately uses $uri. The unsupported+# plaintext queries are dropped instead of reflected. Production clients must+# connect with HTTPS/WSS directly.server {listen 80;server_name _; # TODO: replace with FQDN, e.g. ares.corp.local- return 301 https://$host$request_uri;+ access_log /var/log/nginx/ares_access.log ares_redacted;+ return 308 https://$host$uri;}server {@@ -34,7 +36,8 @@ server {ssl_prefer_server_ciphers off;ssl_session_cache shared:SSL:10m;- # $uri omits the one-time ticket query while preserving TLS access logging.+ # $uri omits one-time ticket queries. This format does not log Cookie,+ # Authorization, Set-Cookie, or any query string.access_log /var/log/nginx/ares_access.log ares_redacted;# Security headersdiff --git a/docs/api-reference.md b/docs/api-reference.mdindex f44f622..339668b 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -3,8 +3,9 @@> **Base URL:** `http://127.0.0.1:8080`> API endpoints require authentication unless noted otherwise. Automation> endpoints may accept `X-API-Key`; account/security management endpoints use-> JWT/browser sessions only. `POST /auth/token` and `GET /health` are-> unauthenticated.+> JWT/browser sessions only. Browser auth is same-origin and CSRF protected;+> `GET /health` is unauthenticated. API keys are the supported automation+> credential.>> **Note:** The web dashboard (`/dashboard/*`) has its own authentication> using the same tokens — see [Dashboard](#dashboard) section.@@ -15,7 +16,9 @@### `POST /auth/token`-Get a JWT access token + refresh token.+Create a browser session. First call `GET /auth/csrf` from the configured+same origin, then submit the form with the readable CSRF cookie copied into+`X-ARES-CSRF`. The refresh token is returned only as an HttpOnly cookie.**Request:** `application/x-www-form-urlencoded` (OAuth2 password flow)```@@ -26,7 +29,6 @@ username=alice&password=changeme```json{"access_token": "eyJhbGci...",- "refresh_token": "rt-...","token_type": "bearer","role": "operator","refresh_generation": 0,@@ -35,6 +37,10 @@ username=alice&password=changeme}```+The response sets host-only `__Host-ares-refresh` (HttpOnly) and+`__Host-ares-csrf` cookies in production. Both use `Secure`, `SameSite=Strict`,+and `Path=/`; no `Domain` is set. Responses are never cacheable.+Each successful login creates an independent device/session family with afixed 30-day absolute lifetime. Access JWTs carry the family identifier andcurrent authentication epoch; authorization always resolves the current user,@@ -50,27 +56,29 @@ the same family. Rate limited per IP (same limit as `/auth/token`). A knownconsumed-token replay, including a concurrent loser or retry after a lostresponse, revokes the complete family and returns the same fixed `401` as anyinvalid, expired, unknown, or revoked refresh token. No replacement token can-be recovered; the user must sign in again.--```json-{ "refresh_token": "rt-..." }-```+be recovered; the user must sign in again. The request body and query must be+empty, no bearer or refresh-token header is accepted, and the refresh token is+read only from the canonical HttpOnly cookie. Exact Origin and CSRF checks are+required. Success rotates both cookies and returns access/coordination metadata+without a refresh token.---### `POST /auth/logout`-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.+Revoke the family represented by the current refresh cookie. The empty request+requires exact Origin and CSRF checks. A conclusive result returns `204`,+clears both browser cookies, and is idempotent for a missing or already-revoked+cookie. Other device families remain active.---### `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.+Require the current access bearer plus Origin and CSRF, increment the current+user's authentication epoch, and revoke every bearer family. Success returns+`204` and clears both cookies. Existing bearer HTTP and WebSocket authority+fails on its next database resolution. API keys remain outside bearer families.---@@ -114,9 +122,16 @@ and special-character content.PowerShell example:```powershell+$origin = "http://127.0.0.1:5173"+$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession+Invoke-WebRequest -Uri "$origin/auth/csrf" -WebSession $session | Out-Null+$csrf = ($session.Cookies.GetCookies($origin) |+ Where-Object Name -eq "ares-dev-csrf").Value$token = (Invoke-RestMethod `-Method Post `- -Uri http://127.0.0.1:8080/auth/token `+ -Uri "$origin/auth/token" `+ -WebSession $session `+ -Headers @{ Origin = $origin; "X-ARES-CSRF" = $csrf; "Sec-Fetch-Site" = "same-origin" } `-ContentType "application/x-www-form-urlencoded" `-Body "username=admin&password=YOUR_CURRENT_ADMIN_PASSWORD").access_token@@ -124,7 +139,7 @@ $headers = @{ Authorization = "Bearer $token" }Invoke-RestMethod `-Method Post `- -Uri http://127.0.0.1:8080/auth/register `+ -Uri "$origin/auth/register" `-Headers $headers `-ContentType "application/json" `-Body (@{@@ -658,7 +673,8 @@ Windows, and open the Vite-served dashboard at`http://127.0.0.1:5173/dashboard/`. The backend API remains on`http://127.0.0.1:8080` by default.-The dashboard uses `POST /auth/token`, `POST /auth/refresh`, the main REST API,+The dashboard bootstraps CSRF with `GET /auth/csrf`, uses cookie-only+`POST /auth/token` and `POST /auth/refresh`, the main REST API,`POST /campaigns/{campaign_id}/websocket-ticket`, and the ticket-only maincampaign WebSocket. Legacy`/dashboard/api/*` and `/dashboard/ws/live` routes are not the primary data@@ -671,8 +687,9 @@ replaces both components together; the additive ticket migrations remaininstalled. Production clients must use HTTPS/WSS directly. The one-time ticketcan still be visible in browser developer tools or to upstream components thatreceive the handshake query. The nginx TLS access-log format uses `$uri` to-omit queries, but the port-80 `$request_uri` redirect boundary is unsupported-for ticket-bearing requests.+omit queries. Its port-80 redirect also uses `$uri`, deliberately dropping+every query string; production clients must still connect with HTTPS/WSS+directly.The supported dashboard is `/dashboard` on the main ARES application. Theolder `ares.api.dashboard.app:dashboard_app` FastAPI application is not mounteddiff --git a/docs/dashboard-guide.md b/docs/dashboard-guide.mdindex f51a35f..36c857a 100644--- a/docs/dashboard-guide.md+++ b/docs/dashboard-guide.md@@ -144,28 +144,15 @@ The dashboard currently shows users in the `Security` page, but it does notinclude a role editor. In the current release, the role is assigned when theaccount is created.-PowerShell example:--```powershell-$token = (Invoke-RestMethod `- -Method Post `- -Uri http://127.0.0.1:8080/auth/token `- -ContentType "application/x-www-form-urlencoded" `- -Body "username=admin&password=YOUR_CURRENT_ADMIN_PASSWORD").access_token--$headers = @{ Authorization = "Bearer $token" }--Invoke-RestMethod `- -Method Post `- -Uri http://127.0.0.1:8080/auth/register `- -Headers $headers `- -ContentType "application/json" `- -Body (@{- username = "bob"- password = "StrongPass1!"- role = "operator"- } | ConvertTo-Json)-```+Create users through the same-origin dashboard. Browser authentication first+bootstraps CSRF with `GET /auth/csrf`; login then reuses that cookie jar and+sends the exact browser `Origin` plus `X-ARES-CSRF`. The login response returns+an access token and nonsecret coordination metadata only. Refresh authority is+held exclusively in the HttpOnly cookie and is never returned to JavaScript.++For automated API access, create and use a scoped API key. Do not automate the+browser login endpoint or transport refresh credentials in JSON, headers,+queries, `sessionStorage`, or `localStorage`.Password rules:diff --git a/docs/frontend.md b/docs/frontend.mdindex 31e3b67..bce6281 100644--- a/docs/frontend.md+++ b/docs/frontend.md@@ -36,22 +36,28 @@ Then open `http://127.0.0.1:5173/dashboard/`.## Auth-- Login calls `POST /auth/token` with `application/x-www-form-urlencoded`.-- 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. This residual browser-token/XSS- exposure is intentionally deferred to the HttpOnly-cookie/CSRF conversion in- Phase 5B.2.+- Browser authentication is same-origin only. Login first obtains a pre-login+ CSRF cookie from `GET /auth/csrf`, then calls `POST /auth/token` with the+ existing form body and `X-ARES-CSRF`.+- Access tokens are held in module memory only. Refresh tokens exist only in a+ host-only HttpOnly cookie and never enter JSON, browser-readable storage,+ React state, messages, logs, or request bodies/headers/queries.+- Refresh acquires the origin-global `ares-refresh-cookie-v2` Web Lock, reads+ the current CSRF cookie immediately before the request, and sends an empty+ credentialed `POST /auth/refresh`.+- Startup synchronously deletes the legacy `sessionStorage` refresh-token key+ before any request, then performs at most one locked refresh rotation.- Logout calls `POST /auth/logout` and revokes only the current device family;**Logout all devices** calls `POST /auth/logout-all`. Both clear local stateeven 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.+- Web Locks and writable `localStorage` coordination are mandatory.+ `localStorage`, storage events, and `BroadcastChannel` carry only a bounded+ protocol version, non-secret coordination key, refresh generation, and+ logout tombstone. A tab needing its own in-memory access token performs a+ sequential locked rotation using the latest shared cookie.+- An indeterminate refresh is never retried. The frontend clears in-memory+ authority and makes at most one locked logout-current attempt; if that is+ also unavailable, explicit sign-in is required.- 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@@ -123,6 +129,6 @@ existing sockets drained. Mixed old/new versions are unsupported, and rollbackreplaces both together while leaving additive migrations installed. UseHTTPS/WSS directly: one-time tickets can remain visible in browser developertools and upstream handshake processing. The nginx TLS access log omits query-strings through `$uri`; its plaintext port-80 `$request_uri` redirect is an-unsupported ticket boundary. The default-disabled legacy dashboard WebSocket+strings through `$uri`; the port-80 redirect also uses `$uri` and drops+queries. The default-disabled legacy dashboard WebSocketretains its separate limitations.diff --git a/docs/modules.md b/docs/modules.mdindex daac1b1..5c24e49 100644--- a/docs/modules.md+++ b/docs/modules.md@@ -108,13 +108,7 @@ authorization and a scoped campaign.### API Flow```powershell-$token = (Invoke-RestMethod `- -Method Post `- -Uri http://127.0.0.1:8080/auth/token `- -ContentType "application/x-www-form-urlencoded" `- -Body "username=admin&password=YOUR_PASSWORD").access_token--$headers = @{ Authorization = "Bearer $token" }+$headers = @{ "X-API-Key" = $env:ARES_API_KEY }Invoke-RestMethod `-Method Get `@@ -122,6 +116,13 @@ Invoke-RestMethod `-Headers $headers```+API keys are the supported automation credential. Browser authentication is+same-origin only: it begins with `GET /auth/csrf`, keeps the refresh authority+in an HttpOnly cookie, and keeps access tokens in memory. `POST /auth/refresh`+has an empty body and query and accepts no refresh-token header or JSON+fallback. WebSocket tickets continue to be issued from an access bearer or API+key and ignore ambient refresh cookies.+Run a module in dry-run mode:```powershelldiff --git a/docs/security-model.md b/docs/security-model.mdindex 618a0cc..0d6655e 100644--- a/docs/security-model.md+++ b/docs/security-model.md@@ -124,8 +124,9 @@ Use `X-API-Key` for automation endpoints such as `GET /auth/me`; accountcredential management, user registration, and API-key lifecycle operations areperformed from an authenticated browser/JWT session.-**Unauthenticated endpoints** (by design):-- `POST /auth/token` — login (takes credentials, returns token)+**Endpoints without an existing bearer** (by design):+- `GET /auth/csrf` — same-origin pre-login CSRF bootstrap+- `POST /auth/token` — same-origin, CSRF-protected browser login- `GET /health` — health check (no sensitive data)The supported dashboard is the React application served by the main ARES@@ -161,6 +162,16 @@ Current database user status, role, authentication epoch, family state, and JTIare authoritative on every bearer resolution. Default access expiry is onehour.+Browser refresh authority is transported only by a host-only HttpOnly cookie.+Production uses `__Host-ares-refresh` and `__Host-ares-csrf` with `Secure`,+`SameSite=Strict`, `Path=/`, and no `Domain`; access tokens remain memory-only.+Every browser-auth mutation requires one exact configured HTTPS Origin and a+constant-time match between the readable CSRF cookie and `X-ARES-CSRF`.+Refresh-token JSON, header, query, and bearer fallbacks are rejected. Debug+cookies use distinct names and are available only for the fixed loopback Vite+origins under explicit debug mode. CORS remains noncredentialed and is not a+browser-auth mechanism.+Refresh is a one-winner database transaction. The predecessor is consumed andexactly one child is inserted before commit; the raw child is returned onlyafter commit. Reuse of a known consumed or revoked predecessor atomically@@ -171,6 +182,13 @@ nothing. `POST /auth/logout` revokes only the current family;state changes increment the user epoch and revoke all families. Separate loginfamilies remain isolated, and API keys never enter refresh families.+Cookie publication follows the confirmed family commit. An indeterminate+network result is not refreshed again: the browser clears memory authority and+attempts one locked family logout before requiring sign-in. Active XSS can+still act as the user and read the CSRF cookie; HttpOnly limits refresh-token+exfiltration but does not claim to defeat active script, browser extensions,+developer tools, or upstream traffic inspection.+Family lineage is retained until 30 days after the later of family expiry orrevocation. Fixed security audit actions record login-family creation,rotation, replay revocation, current/all-device logout, and account security@@ -202,9 +220,9 @@ independent of refresh families.Tickets remain visible to the browser and any upstream component that receivesthe handshake URL, so production clients must initiate HTTPS/WSS directly.-The production nginx TLS log uses `$uri`, which omits query strings. Its-port-80 redirect uses `$request_uri`; ticket-bearing plaintext requests at that-boundary are unsupported. The control does not claim to hide tickets from+The production nginx TLS log and port-80 redirect use `$uri`, which omits query+strings; the redirect deliberately drops them. Production clients must still+connect through HTTPS/WSS. The control does not claim to hide tickets frombrowser developer tools or arbitrary third-party proxies.Backend and frontend rollout is atomic: drain existing main WebSockets, deploydiff --git a/docs/validation-lab.md b/docs/validation-lab.mdindex 64aecfc..dee0385 100644--- a/docs/validation-lab.md+++ b/docs/validation-lab.md@@ -1,23 +1,26 @@# ARES Local Validation Lab-This lab is a safe local harness for checking ARES after UI or backend changes.-It does not attack external systems. By default it only talks to-`127.0.0.1:8080`.+The validation lab exercises safe API workflows through the same public origin+used by the browser. It does not attack external systems and never reads or+prints the HttpOnly refresh cookie.## What It Checks-- API health is online.-- Login and `/auth/me` work.-- Bad campaign target input is rejected with `422`.-- A local dummy campaign can be created, listed, deleted, and verified removed.-- Plan dry-run catches missing module params without touching a target.-- Direct module run rejects missing params with `422`.-- API key create, list, delete, and list-after-delete work.-- HTML report generation and report listing work.+- CSRF bootstrap, cookie-aware login, `/auth/me`, and conclusive logout.+- Rejection of unsafe campaign input.+- Local campaign create, list, dry-run validation, report, and deletion flows.+- API-key create, list, delete, and list-after-delete behavior.-## Run+The lab retains the access token only in process memory. It does not accept a+password or token on the command line, and it does not use refresh JSON,+headers, query parameters, or browser-readable storage.-Start ARES first:+## Supported Local Flow++Use the Vite public origin for both the browser origin and the lab base URL.+Vite proxies HTTP API and WebSocket traffic to the backend.++Start the backend with the matching development policy:```powershell$bytes = [byte[]]::new(32)@@ -25,38 +28,66 @@ $bytes = [byte[]]::new(32)$env:ARES_SECRET_KEY = -join ($bytes | ForEach-Object { $_.ToString("x2") })$env:ARES_ENCRYPTION_KEY = .\.venv\Scripts\python.exe -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"$env:ARES_DEFAULT_ADMIN_PASSWORD = "replace-with-your-own-strong-admin-password"+$env:ARES_DEBUG = "true"+$env:ARES_BROWSER_ORIGIN = "http://127.0.0.1:5173".\.venv\Scripts\ares-api.exe```-In another PowerShell:+Start Vite in another terminal:```powershell-$env:ARES_LAB_PASSWORD="replace-with-your-own-strong-admin-password"-.\scripts\run_validation_lab.ps1+Set-Location .\frontend+npm run dev -- --host 127.0.0.1 --port 5173 --strictPort```-If the admin password has been changed, put the current password in-`ARES_LAB_PASSWORD`.--`ARES_DEFAULT_ADMIN_PASSWORD` is used only when ARES creates the first-`admin` account in an empty user table. Changing that environment variable-after a local admin already exists does not reset the password used by this-lab.--## Direct Python+Then run the lab from a third terminal:```powershell-$env:ARES_LAB_PASSWORD="your-current-admin-password"-.\.venv\Scripts\python.exe .\scripts\validation_lab.py --base-url http://127.0.0.1:8080 --username admin+$env:ARES_LAB_PASSWORD = "replace-with-your-current-admin-password"+.\scripts\run_validation_lab.ps1 `+ -BaseUrl "http://127.0.0.1:5173" `+ -BrowserOrigin "http://127.0.0.1:5173"```-## Safety Guard+If `ARES_LAB_PASSWORD` and `ARES_DEFAULT_ADMIN_PASSWORD` are absent, the lab+uses a hidden interactive prompt. `ARES_DEFAULT_ADMIN_PASSWORD` creates only+the first account in an empty database; changing it later does not reset an+existing account.++The wrapper preserves the Python process exit status. It passes the explicit+browser origin but never forwards passwords or tokens in process arguments.-The script refuses non-local URLs by default. For an explicitly authorized lab-host only:+## Authentication Boundary++The lab performs these steps internally:++1. `GET /auth/csrf` with the exact configured `Origin`.+2. Retain the readable CSRF cookie in a private per-client cookie jar.+3. `POST /auth/token` with the username/password form, the same cookie jar,+ exact `Origin`, and matching `X-ARES-CSRF`.+4. Keep the returned access token in memory for the protected validation calls.+5. Use the newest readable CSRF cookie and the same jar for `POST /auth/logout`.++The login JSON contains no refresh token. The private jar carries the refresh+cookie ambiently; operators must not inspect, extract, serialize, or display+it.++Direct cross-origin backend login is unsupported. The public base URL and+browser origin must be canonical and identical. Plain HTTP is accepted only+for the fixed loopback Vite origins. An explicitly authorized remote lab must+use one exact HTTPS origin and `--allow-remote`; redirects on authentication+requests are rejected.++## Direct Python```powershell-.\.venv\Scripts\python.exe .\scripts\validation_lab.py --base-url http://127.0.0.1:8080+$env:ARES_LAB_PASSWORD = "your-current-admin-password"+.\.venv\Scripts\python.exe .\scripts\validation_lab.py `+ --base-url "http://127.0.0.1:5173" `+ --browser-origin "http://127.0.0.1:5173" `+ --username admin```-Use `--allow-remote` only for a lab you own or are explicitly authorized to test.+The browser origin may instead come from `ARES_LAB_BROWSER_ORIGIN`, then+`ARES_BROWSER_ORIGIN`. Absence is rejected; it is never inferred from the base+URL.diff --git a/frontend/src/api/client.test.ts b/frontend/src/api/client.test.tsindex a176b5e..f1ae71f 100644--- a/frontend/src/api/client.test.ts+++ b/frontend/src/api/client.test.ts@@ -1,381 +1,172 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import {- ApiError,- api,- beginIdentityTransition,- buildModuleRunPayload,- campaignEventsPath,- captureSession,- clearTokens,- getAccessToken,- getRefreshToken,- invalidateSession,- login,- refreshAccessToken,- setAccessToken,- subscribeToSessionInvalidation,- setRefreshToken-} from "./client";-import { installTokenPairIfCurrent } from "./session";-function requireFixed(condition: boolean, message: string): void {- if (!condition) {- throw new Error(message);- }-}--function requireTokensUnavailable(): void {- const accessTokenUnavailable = getAccessToken() === null;- const refreshTokenUnavailable = getRefreshToken() === null;- requireFixed(accessTokenUnavailable, "Access token should remain unavailable.");- requireFixed(refreshTokenUnavailable, "Refresh token should remain unavailable.");-}+const CSRF = "A".repeat(43);+const KEY = "B".repeat(43);-function resetTestSessionStorage(): void {- const keys = Array.from({ length: sessionStorage.length }, (_, index) => sessionStorage.key(index))- .filter((key): key is string => key !== null);- for (const key of keys) {- sessionStorage.removeItem(key);- }+function installBrowserPrimitives(): void {+ localStorage.clear();+ sessionStorage.clear();+ document.cookie = `ares-dev-csrf=${CSRF}; Path=/`;+ Object.defineProperty(navigator, "locks", {+ configurable: true,+ value: { request: vi.fn(async (_name: string, operation: () => unknown) => operation()) }+ });}-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");+function loginResponse(): Response {+ return new Response(JSON.stringify({+ access_token: "memory-access",+ token_type: "bearer",+ expires_in: 3600,+ role: "operator",+ refresh_generation: 0,+ session_coordination_key: KEY+ }), { status: 200, headers: { "Content-Type": "application/json" } });}-describe("api client auth", () => {+describe("browser auth API facade", () => {beforeEach(() => {- clearTokens();- resetTestSessionStorage();- vi.unstubAllGlobals();vi.restoreAllMocks();+ vi.resetModules();+ installBrowserPrimitives();});- it("posts login as form-urlencoded and stores returned tokens", async () => {- let loginCalls = 0;- const fetchMock = vi.fn(async (_path: string, init?: RequestInit) => {- loginCalls += 1;- const headers = new Headers(init?.headers);- requireFixed(- headers.get("Content-Type") === "application/x-www-form-urlencoded",- "expected form content type"- );- requireFixed(init?.body instanceof URLSearchParams, "expected form request body");- const body = new URLSearchParams(String(init?.body));- requireFixed(body.get("username") === "alice", "expected canonical login username");- return new Response(- JSON.stringify({- access_token: "access",- refresh_token: "refresh",- token_type: "bearer",- expires_in: 3600,- role: "operator",- refresh_generation: 0,- session_coordination_key: "coordination-a"- }),- { status: 200 }- );+ it("login performs CSRF, locked logout, CSRF, then credential form", async () => {+ const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {+ void init;+ if (path === "/auth/csrf") return new Response(null, { status: 204 });+ if (path === "/auth/logout") return new Response(null, { status: 204 });+ return loginResponse();});vi.stubGlobal("fetch", fetchMock);- await login("alice", "Secret123!");- expect(loginCalls).toBe(1);- const accessTokenInstalled = getAccessToken() === "access";- const refreshTokenInstalled = getRefreshToken() === "refresh";- requireFixed(accessTokenInstalled, "expected access token installation");- requireFixed(refreshTokenInstalled, "expected refresh token installation");+ const client = await import("./client");+ const response = await client.login("alice", "Secret123!");+ expect(response.access_token).toBe("memory-access");+ expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([+ "/auth/csrf", "/auth/logout", "/auth/csrf", "/auth/token"+ ]);});- it("refreshes the access token from the stored refresh token", async () => {- 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 };- const refreshRequestTokenMatches = body.refresh_token === "refresh-old";- requireFixed(refreshRequestTokenMatches, "expected refresh request token");- return new Response(- JSON.stringify({- access_token: "access-new",- refresh_token: "refresh-new",- token_type: "bearer",- expires_in: 3600,- role: "operator",- refresh_generation: 1,- session_coordination_key: "coordination-a"- }),- { status: 200 }- );+ it("login response and browser storage contain no refresh token", async () => {+ const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {+ void init;+ return path === "/auth/token" ? loginResponse() : new Response(null, { status: 204 });});vi.stubGlobal("fetch", fetchMock);-- await expect(refreshAccessToken()).resolves.toBe(true);- const rotatedAccessTokenCurrent = getAccessToken() === "access-new";- const rotatedRefreshTokenCurrent = getRefreshToken() === "refresh-new";- requireFixed(rotatedAccessTokenCurrent, "expected rotated access token");- requireFixed(rotatedRefreshTokenCurrent, "expected rotated refresh token");- });-- it("clears tokens when refresh fails", async () => {- installSession("expired-access", "expired-refresh");- vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 401 })));-- await expect(refreshAccessToken()).resolves.toBe(false);- requireTokensUnavailable();+ const client = await import("./client");+ const response = await client.login("alice", "Secret123!");+ expect("refresh_token" in response).toBe(false);+ expect(sessionStorage.getItem("ares.refreshToken")).toBeNull();+ expect(JSON.stringify(localStorage)).not.toContain("memory-access");});- it("fails closed when a login token pair cannot be persisted", async () => {- vi.stubGlobal("fetch", vi.fn(async () => new Response(- JSON.stringify({- access_token: "access",- refresh_token: "refresh",- token_type: "bearer",- expires_in: 3600,- role: "operator",- refresh_generation: 0,- session_coordination_key: "coordination-a"- }),- { status: 200 }- )));- const setItem = vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {- throw new DOMException("unavailable", "SecurityError");+ it("login form carries credentials only in the form body", async () => {+ const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {+ void init;+ return path === "/auth/token" ? loginResponse() : new Response(null, { status: 204 });});- try {- let rejectionStatus: number | undefined;- try {- await login("alice", "Secret123!");- } catch (error) {- rejectionStatus = error instanceof ApiError ? error.status : undefined;- }- requireFixed(rejectionStatus === 401, "expected failed token-pair installation");- requireTokensUnavailable();- } finally {- setItem.mockRestore();- }+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ await client.login("alice", "Secret123!");+ const tokenCall = fetchMock.mock.calls.find((call) => call[0] === "/auth/token");+ const init = tokenCall?.[1] as RequestInit;+ expect(init.body).toBeInstanceOf(URLSearchParams);+ expect(new Headers(init.headers).has("Authorization")).toBe(false);+ expect(init.credentials).toBe("same-origin");});- it("clears the logical token pair when refresh-token removal fails", () => {- setAccessToken("access");- setRefreshToken("refresh");- const originalRemoveItem = Storage.prototype.removeItem;- const removeItem = vi.spyOn(Storage.prototype, "removeItem").mockImplementation(function (- this: Storage,- key: string- ) {- if (key === "ares.refreshToken") {- throw new DOMException("unavailable", "SecurityError");- }- return originalRemoveItem.call(this, key);- });- try {- expect(() => clearTokens()).not.toThrow();- requireTokensUnavailable();- const refreshStorageNeutralized = sessionStorage.getItem("ares.refreshToken") === "";- requireFixed(refreshStorageNeutralized, "Refresh-token storage should be neutralized.");- } finally {- removeItem.mockRestore();- setRefreshToken(null);- }+ it("login fails closed without Web Locks", async () => {+ Object.defineProperty(navigator, "locks", { configurable: true, value: undefined });+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ await expect(client.login("alice", "Secret123!")).rejects.toMatchObject({ status: 401 });+ expect(fetchMock).not.toHaveBeenCalled();});- it("continues invalidation after a subscriber throws", () => {- setAccessToken("access");- setRefreshToken("refresh");- let laterSubscriberCalls = 0;- const unsubscribeThrowing = subscribeToSessionInvalidation(() => {- throw new Error("subscriber failed");+ it("logout is cookie-authoritative and has an empty body", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return new Response(null, { status: 204 });});- const unsubscribeLater = subscribeToSessionInvalidation(() => {- laterSubscriberCalls += 1;- });- try {- const invalidated = invalidateSession(captureSession());- expect(invalidated).toBe(true);- expect(laterSubscriberCalls).toBe(1);- requireTokensUnavailable();- } finally {- unsubscribeThrowing();- unsubscribeLater();- }+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ await client.logout();+ const call = fetchMock.mock.calls[0];+ const init = call?.[1] as RequestInit;+ expect(call?.[0]).toBe("/auth/logout");+ expect(init.body).toBeUndefined();+ expect(new Headers(init.headers).has("Authorization")).toBe(false);});- it("fails closed when refresh-token storage reads fail and recovers after a valid install", () => {- setRefreshToken("refresh-before-read-failure");- const originalGetItem = Storage.prototype.getItem;- const getItem = vi.spyOn(Storage.prototype, "getItem").mockImplementation(function (- this: Storage,- key: string- ) {- if (key === "ares.refreshToken") {- throw new DOMException("unavailable", "SecurityError");- }- return originalGetItem.call(this, key);+ it("logout-all sends in-memory bearer plus CSRF", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return new Response(null, { status: 204 });});- const errorLog = vi.spyOn(console, "error").mockImplementation(() => undefined);- const warningLog = vi.spyOn(console, "warn").mockImplementation(() => undefined);- try {- let readThrew = false;- let observedRefreshToken: string | null = null;- try {- observedRefreshToken = getRefreshToken();- } catch {- readThrew = true;- }- requireFixed(!readThrew, "expected storage read failure to remain internal");- const observedRefreshTokenUnavailable = observedRefreshToken === null;- const accessTokenUnavailable = getAccessToken() === null;- requireFixed(observedRefreshTokenUnavailable, "Refresh token should remain unavailable.");- requireFixed(accessTokenUnavailable, "Access token should remain unavailable.");- expect(errorLog).not.toHaveBeenCalled();- expect(warningLog).not.toHaveBeenCalled();- } finally {- getItem.mockRestore();- errorLog.mockRestore();- warningLog.mockRestore();- }-- const recoveredSession = beginIdentityTransition();- const installed = installTokenPairIfCurrent(- recoveredSession,- "access-after-read-failure",- "refresh-after-read-failure",- "coordination-recovered",- 0- );- requireFixed(installed, "expected valid token-pair recovery");- const recoveredAccessTokenCurrent = getAccessToken() === "access-after-read-failure";- const recoveredRefreshTokenCurrent = getRefreshToken() === "refresh-after-read-failure";- requireFixed(recoveredAccessTokenCurrent, "expected recovered access session");- requireFixed(recoveredRefreshTokenCurrent, "expected recovered refresh session");+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ client.setAccessToken("memory-access");+ await client.logoutAll();+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;+ const headers = new Headers(init.headers);+ expect(headers.get("Authorization")).toBe("Bearer memory-access");+ expect(headers.get("X-ARES-CSRF")).toBe(CSRF);});- it("keeps invalidation fail-closed when refresh-token removal and sentinel writes fail", () => {- const activeSession = beginIdentityTransition();- const installed = installTokenPairIfCurrent(- activeSession,- "access-before-clear-failure",- "refresh-before-clear-failure",- "coordination-clear",- 0- );- requireFixed(installed, "expected active session setup");- const beforeInvalidation = captureSession();- let subscriberCalls = 0;- const unsubscribe = subscribeToSessionInvalidation(() => {- subscriberCalls += 1;- });- const originalRemoveItem = Storage.prototype.removeItem;- const originalSetItem = Storage.prototype.setItem;- const removeItem = vi.spyOn(Storage.prototype, "removeItem").mockImplementation(function (- this: Storage,- key: string- ) {- if (key === "ares.refreshToken") {- throw new DOMException("unavailable", "SecurityError");- }- return originalRemoveItem.call(this, key);- });- const setItem = vi.spyOn(Storage.prototype, "setItem").mockImplementation(function (- this: Storage,- key: string,- value: string- ) {- if (key === "ares.refreshToken" && value === "") {- throw new DOMException("unavailable", "SecurityError");- }- return originalSetItem.call(this, key, value);+ it("campaign WebSocket tickets remain bearer API requests", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return new Response(JSON.stringify({+ ticket: "ticket-value", expires_in: 30+ }), { status: 200 });});- const errorLog = vi.spyOn(console, "error").mockImplementation(() => undefined);- const warningLog = vi.spyOn(console, "warn").mockImplementation(() => undefined);- try {- let invalidationThrew = false;- let invalidated = false;- try {- invalidated = invalidateSession(beforeInvalidation);- } catch {- invalidationThrew = true;- }- const afterInvalidation = captureSession();- requireFixed(!invalidationThrew, "expected storage cleanup failures to remain internal");- expect(invalidated).toBe(true);- requireTokensUnavailable();- expect(afterInvalidation.revision).toBeGreaterThan(beforeInvalidation.revision);- expect(subscriberCalls).toBe(1);- expect(errorLog).not.toHaveBeenCalled();- expect(warningLog).not.toHaveBeenCalled();- } finally {- removeItem.mockRestore();- setItem.mockRestore();- errorLog.mockRestore();- warningLog.mockRestore();- unsubscribe();- }+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ client.setAccessToken("memory-access");+ await client.api.websocketTicket("campaign-a");+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;+ expect(new Headers(init.headers).get("Authorization")).toBe("Bearer memory-access");+ });- const recoveredSession = beginIdentityTransition();- const recovered = installTokenPairIfCurrent(- recoveredSession,- "access-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";- const recoveredRefreshTokenCurrent = getRefreshToken() === "refresh-after-clear-failure";- requireFixed(recoveredAccessTokenCurrent, "expected recovered access session");- requireFixed(recoveredRefreshTokenCurrent, "expected recovered refresh session");+ it("WebSocket URL contains only the one-time ticket query", async () => {+ const client = await import("./client");+ const path = client.campaignEventsPath("campaign-a", "ticket-value");+ expect(path).toBe("/ws/campaigns/campaign-a/events?ticket=ticket-value");+ expect(path).not.toContain("access_token");+ expect(path).not.toContain("api_key");});-});-describe("module execution helpers", () => {- it("defaults UI module runs to dry_run true", () => {- expect(buildModuleRunPayload("campaign-1", { target: "dc01" })).toEqual({- campaign_id: "campaign-1",- params: { target: "dc01" },- dry_run: true+ it("account replacement publishes an old-family tombstone", async () => {+ const fetchMock = vi.fn(async (path: string, init?: RequestInit) => {+ void init;+ return path === "/auth/token" ? loginResponse() : new Response(null, { status: 204 });});+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ await client.login("alice", "Secret123!");+ await client.login("bob", "Secret123!");+ expect(fetchMock.mock.calls.filter((call) => call[0] === "/auth/logout")).toHaveLength(2);});-});--describe("live event helpers", () => {- it("requests a fresh ticket with POST and parses the fixed response", async () => {- let requestIsCanonical = false;- vi.stubGlobal("fetch", vi.fn(async (path: string, init?: RequestInit) => {- requestIsCanonical =- path === "/campaigns/camp%2Fone/websocket-ticket"- && init?.method === "POST"- && init.body === undefined;- return new Response(JSON.stringify({- ticket: "A".repeat(43),- expires_in: 30- }), { status: 201 });- }));- const response = await api.websocketTicket("camp/one");- const responseIsCanonical =- response.ticket.length === 43 && response.expires_in === 30;- requireFixed(requestIsCanonical, "expected ticket issuance request contract");- requireFixed(responseIsCanonical, "expected ticket issuance response contract");+ it("API errors keep fixed status metadata", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ detail: "Denied" }), { status: 403 })));+ const client = await import("./client");+ await expect(client.api.health()).rejects.toMatchObject({ status: 403 });});- it("uses only the one-time ticket on the campaign websocket route", () => {- const path = campaignEventsPath("camp/one", "A".repeat(43));- const matchesExpectedRoute =- path === `/ws/campaigns/camp%2Fone/events?ticket=${"A".repeat(43)}`;- const excludesLegacyCredentials =- !path.includes("token=") && !path.includes("api_key=");- requireFixed(matchesExpectedRoute, "expected encoded campaign WebSocket route");- requireFixed(excludesLegacyCredentials, "expected ticket-only WebSocket query");+ it("all generic requests use same-origin credentials", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return new Response(JSON.stringify({ status: "ok" }), { status: 200 });+ });+ vi.stubGlobal("fetch", fetchMock);+ const client = await import("./client");+ await client.api.health();+ expect((fetchMock.mock.calls[0]?.[1] as RequestInit).credentials).toBe("same-origin");});});diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex 9f8b6a3..7f20dcd 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -1,16 +1,23 @@// Compatibility facade: existing feature imports continue to use this stable public API.-export { apiBlobRequest, apiRequest, ApiError, refreshAccessToken } from "./http";+export {+ apiBlobRequest,+ apiRequest,+ ApiError,+ bootstrapBrowserCsrf,+ browserMutationRequest,+ refreshAccessToken,+ withRefreshCookieLock+} from "./http";export { api, buildModuleRunPayload, campaignEventsPath, login, logout, logoutAll } from "./endpoints";export {beginIdentityTransition,+ browserCoordinationAvailable,captureSession,clearTokens,getAccessToken,- getRefreshToken,invalidateSession,isSessionCurrent,readCoordinationRecord,subscribeToSessionInvalidation,- setAccessToken,- setRefreshToken+ setAccessToken} from "./session";diff --git a/frontend/src/api/endpoints.ts b/frontend/src/api/endpoints.tsindex 11bf343..506d213 100644--- a/frontend/src/api/endpoints.ts+++ b/frontend/src/api/endpoints.ts@@ -14,27 +14,33 @@ import type {UserProfile,WebSocketTicketResponse} from "./types";-import { apiBlobRequest, apiRequest, ApiError } from "./http";-import { beginIdentityTransition, installTokenPairIfCurrent } from "./session";+import {+ apiBlobRequest,+ apiRequest,+ ApiError,+ bootstrapBrowserCsrf,+ browserMutationRequest,+ withRefreshCookieLock+} from "./http";+import { beginIdentityTransition, installSessionIfCurrent } from "./session";export async function login(username: string, password: string): Promise<TokenResponse> {const loginSession = beginIdentityTransition();- const body = new URLSearchParams();- body.set("username", username);- body.set("password", password);- const token = await apiRequest<TokenResponse>(- "/auth/token",- {- method: "POST",+ const token = await withRefreshCookieLock(async () => {+ await bootstrapBrowserCsrf();+ await browserMutationRequest<null>("/auth/logout");+ await bootstrapBrowserCsrf();+ const body = new URLSearchParams();+ body.set("username", username);+ body.set("password", password);+ return browserMutationRequest<TokenResponse>("/auth/token", {headers: { "Content-Type": "application/x-www-form-urlencoded" },body- },- false- );- if (!installTokenPairIfCurrent(+ });+ });+ if (!installSessionIfCurrent(loginSession,token.access_token,- token.refresh_token,token.session_coordination_key,token.refresh_generation)) {@@ -44,11 +50,15 @@ export async function login(username: string, password: string): Promise<TokenRe}export async function logout(): Promise<void> {- await apiRequest<{ status: string }>("/auth/logout", { method: "POST" }, false);+ await withRefreshCookieLock(async () => {+ await browserMutationRequest<null>("/auth/logout");+ });}export async function logoutAll(): Promise<void> {- await apiRequest<{ status: string }>("/auth/logout-all", { method: "POST" }, false);+ await withRefreshCookieLock(async () => {+ await browserMutationRequest<null>("/auth/logout-all", {}, { authenticated: true });+ });}export function campaignEventsPath(campaignId: string, ticket: string): string {diff --git a/frontend/src/api/http.test.ts b/frontend/src/api/http.test.tsindex 7e3e98f..0044832 100644--- a/frontend/src/api/http.test.ts+++ b/frontend/src/api/http.test.ts@@ -1,422 +1,197 @@-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { apiBlobRequest, apiRequest } from "./http";-import {- beginIdentityTransition,- captureSession,- clearTokens,- getAccessToken,- getRefreshToken,- installTokenPairIfCurrent,- invalidateSession,- subscribeToSessionInvalidation-} from "./session";--function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void;- let reject!: (reason?: unknown) => void;- const promise = new Promise<T>((resolvePromise, rejectPromise) => {- resolve = resolvePromise;- reject = rejectPromise;+import { beforeEach, describe, expect, it, vi } from "vitest";++const CSRF = "A".repeat(43);+const KEY = "B".repeat(43);++function installBrowserPrimitives(): void {+ localStorage.clear();+ sessionStorage.clear();+ document.cookie = `ares-dev-csrf=${CSRF}; Path=/`;+ Object.defineProperty(navigator, "locks", {+ configurable: true,+ value: { request: vi.fn(async (_name: string, operation: () => unknown) => operation()) }});- return { promise, reject, resolve };}-function tokenResponse(- accessToken: string,- refreshToken: string,- generation = 1-): Response {+function tokenResponse(generation = 1): Response {return new Response(JSON.stringify({- access_token: accessToken,- refresh_token: refreshToken,+ access_token: "memory-access",token_type: "bearer",expires_in: 3600,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,- "coordination-a",- 0- )) {- throw new Error("test session setup failed");- }-}--function requireFixed(condition: boolean, message: string): void {- if (!condition) {- throw new Error(message);- }-}--function resetTestSessionStorage(): void {- const keys = Array.from({ length: sessionStorage.length }, (_, index) => sessionStorage.key(index))- .filter((key): key is string => key !== null);- for (const key of keys) {- sessionStorage.removeItem(key);- }+ session_coordination_key: KEY+ }), { status: 200, headers: { "Content-Type": "application/json" } });}-describe("HTTP auth boundary", () => {+describe("cookie-backed HTTP transport", () => {beforeEach(() => {- clearTokens();- resetTestSessionStorage();- vi.unstubAllGlobals();+ vi.restoreAllMocks();+ vi.resetModules();+ installBrowserPrimitives();});- afterEach(() => {- vi.unstubAllGlobals();+ it("reads only one canonical CSRF cookie", async () => {+ const http = await import("./http");+ expect(http.readBrowserCsrfToken()).toBe(CSRF);});- it("shares one refresh across simultaneous JSON requests and retries both once", async () => {- installSession();- const releaseRefresh = deferred<void>();- const refreshStarted = deferred<void>();- let refreshCalls = 0;- let initialCalls = 0;- let retryCalls = 0;- let incorrectRetryAuthorization = false;-- vi.stubGlobal("fetch", vi.fn(async (path: string, init?: RequestInit) => {- const authorization = new Headers(init?.headers).get("Authorization");- if (path === "/auth/refresh") {- refreshCalls += 1;- refreshStarted.resolve();- await releaseRefresh.promise;- return tokenResponse("access-b", "refresh-b");- }- if (authorization === "Bearer access-a") {- initialCalls += 1;- return new Response(null, { status: 401 });- }- if (authorization !== "Bearer access-b") {- incorrectRetryAuthorization = true;- return new Response(null, { status: 403 });- }- retryCalls += 1;- return new Response(JSON.stringify({ status: "ok" }), { status: 200 });- }));-- const first = apiRequest<{ status: string }>("/protected/one");- const second = apiRequest<{ status: string }>("/protected/two");- try {- await refreshStarted.promise;- releaseRefresh.resolve();-- const results = await Promise.all([first, second]);- expect(results.map((result) => result.status)).toEqual(["ok", "ok"]);- expect({ incorrectRetryAuthorization, initialCalls, refreshCalls, retryCalls }).toEqual({- incorrectRetryAuthorization: false,- initialCalls: 2,- refreshCalls: 1,- retryCalls: 2- });- const rotatedAccessTokenCurrent = getAccessToken() === "access-b";- requireFixed(rotatedAccessTokenCurrent, "expected rotated access authorization");- } finally {- releaseRefresh.resolve();- await Promise.allSettled([first, second]);- }+ it("rejects duplicate canonical CSRF cookie names", async () => {+ vi.spyOn(document, "cookie", "get").mockReturnValue(+ `ares-dev-csrf=${CSRF}; ares-dev-csrf=${CSRF}`+ );+ const http = await import("./http");+ expect(http.readBrowserCsrfToken()).toBeNull();});- it("shares the same refresh flight between JSON and blob requests", async () => {- installSession();- const releaseRefresh = deferred<void>();- const refreshStarted = deferred<void>();- let refreshCalls = 0;- let incorrectRetryAuthorization = false;-- vi.stubGlobal("fetch", vi.fn(async (path: string, init?: RequestInit) => {- const authorization = new Headers(init?.headers).get("Authorization");- if (path === "/auth/refresh") {- refreshCalls += 1;- refreshStarted.resolve();- await releaseRefresh.promise;- return tokenResponse("access-b", "refresh-b");- }- if (authorization === "Bearer access-a") {- return new Response(null, { status: 401 });- }- if (authorization !== "Bearer access-b") {- incorrectRetryAuthorization = true;- return new Response(null, { status: 403 });- }- return path === "/blob"- ? new Response("artifact", { status: 200 })- : new Response(JSON.stringify({ status: "ok" }), { status: 200 });- }));-- const jsonRequest = apiRequest<{ status: string }>("/json");- const blobRequest = apiBlobRequest("/blob");- try {- await refreshStarted.promise;- releaseRefresh.resolve();-- const [json, blob] = await Promise.all([jsonRequest, blobRequest]);- expect(json.status).toBe("ok");- expect(blob.size).toBeGreaterThan(0);- expect({ incorrectRetryAuthorization, refreshCalls }).toEqual({- incorrectRetryAuthorization: false,- refreshCalls: 1- });- } finally {- releaseRefresh.resolve();- await Promise.allSettled([jsonRequest, blobRequest]);- }+ it("CSRF bootstrap uses a same-origin credentialed GET", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return new Response(null, { status: 204 });+ });+ vi.stubGlobal("fetch", fetchMock);+ const http = await import("./http");+ await http.bootstrapBrowserCsrf();+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;+ expect(fetchMock.mock.calls[0]?.[0]).toBe("/auth/csrf");+ expect(init.credentials).toBe("same-origin");+ expect(init.method).toBe("GET");});- it("invalidates once when a shared refresh fails and does not retry protected requests", async () => {- installSession();- let refreshCalls = 0;- let protectedCalls = 0;- let invalidations = 0;- const unsubscribe = subscribeToSessionInvalidation(() => {- invalidations += 1;+ it("refresh sends an empty cookie-authoritative request", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return tokenResponse();});- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/refresh") {- refreshCalls += 1;- return new Response(null, { status: 401 });- }- protectedCalls += 1;- return new Response(null, { status: 401 });- }));+ vi.stubGlobal("fetch", fetchMock);+ const session = await import("./session");+ const snapshot = session.beginIdentityTransition();+ session.installSessionIfCurrent(snapshot, "old-access", KEY, 0);+ const http = await import("./http");+ await expect(http.refreshAccessToken(session.captureSession())).resolves.toBe(true);+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;+ const headers = new Headers(init.headers);+ expect(fetchMock.mock.calls[0]?.[0]).toBe("/auth/refresh");+ expect(init.body).toBeUndefined();+ expect(init.credentials).toBe("same-origin");+ expect(headers.get("X-ARES-CSRF")).toBe(CSRF);+ expect(headers.has("Authorization")).toBe(false);+ });- try {- const results = await Promise.allSettled([- apiRequest("/protected/one"),- apiRequest("/protected/two")- ]);- expect(results.every((result) => result.status === "rejected")).toBe(true);- expect({ invalidations, protectedCalls, refreshCalls }).toEqual({- invalidations: 1,- protectedCalls: 2,- refreshCalls: 1- });- const refreshTokenUnavailable = getRefreshToken() === null;- requireFixed(refreshTokenUnavailable, "Refresh token should remain unavailable.");- } finally {- unsubscribe();- }+ it("refresh rejects a response containing a raw refresh token", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({+ access_token: "access",+ refresh_token: "forbidden",+ refresh_generation: 1,+ session_coordination_key: KEY+ }), { status: 200 })));+ const session = await import("./session");+ const snapshot = session.beginIdentityTransition();+ session.installSessionIfCurrent(snapshot, "old", KEY, 0);+ const http = await import("./http");+ await expect(http.refreshAccessToken(session.captureSession())).resolves.toBe(false);+ expect(session.getAccessToken()).toBeNull();});- it("invalidates after one retry receives a second 401 without recursion", async () => {- installSession();- let protectedCalls = 0;- let refreshCalls = 0;- let invalidations = 0;- const unsubscribe = subscribeToSessionInvalidation(() => {- invalidations += 1;+ it("same-tab concurrent refreshes share one flight", async () => {+ let release: (() => void) | undefined;+ const barrier = new Promise<void>((resolve) => { release = resolve; });+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ await barrier;+ return tokenResponse();});- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/refresh") {- refreshCalls += 1;- return tokenResponse("access-b", "refresh-b");- }- protectedCalls += 1;- return new Response(null, { status: 401 });- }));-- try {- await expect(apiRequest("/protected")).rejects.toMatchObject({ status: 401 });- expect({ invalidations, protectedCalls, refreshCalls }).toEqual({- invalidations: 1,- protectedCalls: 2,- refreshCalls: 1- });- } finally {- unsubscribe();- }+ vi.stubGlobal("fetch", fetchMock);+ const session = await import("./session");+ const start = session.beginIdentityTransition();+ session.installSessionIfCurrent(start, "old", KEY, 0);+ const http = await import("./http");+ const snapshot = session.captureSession();+ const first = http.refreshAccessToken(snapshot);+ const second = http.refreshAccessToken(snapshot);+ release?.();+ await expect(Promise.all([first, second])).resolves.toEqual([true, true]);+ expect(fetchMock).toHaveBeenCalledTimes(1);});- it("retries a delayed old-token 401 with the current token without a second refresh", async () => {- installSession();- const releaseDelayed = deferred<void>();- const delayedStarted = deferred<void>();- let refreshCalls = 0;- let delayedCalls = 0;- let incorrectRetryAuthorization = false;-- vi.stubGlobal("fetch", vi.fn(async (path: string, init?: RequestInit) => {- const authorization = new Headers(init?.headers).get("Authorization");- if (path === "/auth/refresh") {- refreshCalls += 1;- return tokenResponse("access-b", "refresh-b");- }- if (path === "/delayed" && authorization === "Bearer access-a") {- delayedStarted.resolve();- await releaseDelayed.promise;- return new Response(null, { status: 401 });- }- if (authorization === "Bearer access-a") {- return new Response(null, { status: 401 });- }- if (authorization !== "Bearer access-b") {- incorrectRetryAuthorization = true;- return new Response(null, { status: 403 });- }- if (path === "/delayed") {- delayedCalls += 1;- }- return new Response(JSON.stringify({ status: "ok" }), { status: 200 });+ it("a peer generation allows the next sequential rotation", async () => {+ localStorage.setItem("ares.sessionCoordination.v2", JSON.stringify({+ version: 2, key: KEY, generation: 2, tombstone: false}));-- const delayed = apiRequest<{ status: string }>("/delayed");- try {- await delayedStarted.promise;- await expect(apiRequest<{ status: string }>("/leading")).resolves.toEqual({ status: "ok" });- releaseDelayed.resolve();- await expect(delayed).resolves.toEqual({ status: "ok" });-- expect({ delayedCalls, incorrectRetryAuthorization, refreshCalls }).toEqual({- delayedCalls: 1,- incorrectRetryAuthorization: false,- refreshCalls: 1- });- } finally {- releaseDelayed.resolve();- await Promise.allSettled([delayed]);- }+ vi.stubGlobal("fetch", vi.fn(async () => tokenResponse(3)));+ const http = await import("./http");+ await expect(http.refreshAccessToken()).resolves.toBe(true);});- it("does not restore a session when a refresh succeeds after logout", async () => {- installSession();- const releaseRefresh = deferred<void>();- const refreshStarted = deferred<void>();- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path !== "/auth/refresh") {- return new Response(null, { status: 401 });- }- refreshStarted.resolve();- await releaseRefresh.promise;- return tokenResponse("access-late", "refresh-late");+ it("a tombstone prevents refresh", async () => {+ localStorage.setItem("ares.sessionCoordination.v2", JSON.stringify({+ version: 2, key: KEY, generation: 0, tombstone: true}));-- const original = captureSession();- const refresh = apiRequest("/protected");- try {- await refreshStarted.promise;- invalidateSession(original);- releaseRefresh.resolve();-- await expect(refresh).rejects.toMatchObject({ status: 401 });- const accessTokenUnavailable = getAccessToken() === null;- const refreshTokenUnavailable = getRefreshToken() === null;- requireFixed(accessTokenUnavailable, "Access token should remain unavailable.");- requireFixed(refreshTokenUnavailable, "Refresh token should remain unavailable.");- } finally {- releaseRefresh.resolve();- await Promise.allSettled([refresh]);- }+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const session = await import("./session");+ const start = session.beginIdentityTransition();+ session.installSessionIfCurrent(start, "old", KEY, 0);+ localStorage.setItem("ares.sessionCoordination.v2", JSON.stringify({+ version: 2, key: KEY, generation: 0, tombstone: true+ }));+ const http = await import("./http");+ await expect(http.refreshAccessToken(session.captureSession())).resolves.toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();});- it.each(["success", "failure"] as const)(- "does not let stale account-A refresh %s alter account B",- async (outcome) => {- installSession();- const releaseRefresh = deferred<void>();- const refreshStarted = deferred<void>();- let invalidations = 0;- const unsubscribe = subscribeToSessionInvalidation(() => {- invalidations += 1;- });- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/refresh") {- refreshStarted.resolve();- await releaseRefresh.promise;- return outcome === "success"- ? tokenResponse("access-a-late", "refresh-a-late")- : new Response(null, { status: 401 });- }- return new Response(null, { status: 401 });- }));-- try {- const refresh = apiRequest("/protected");- try {- await refreshStarted.promise;- const accountB = beginIdentityTransition();- const installed = installTokenPairIfCurrent(- accountB,- "access-b",- "refresh-b",- "coordination-b",- 0- );- expect(installed).toBe(true);- releaseRefresh.resolve();- await expect(refresh).rejects.toMatchObject({ status: 401 });- const accountBAccessTokenCurrent = getAccessToken() === "access-b";- const accountBRefreshTokenCurrent = getRefreshToken() === "refresh-b";- requireFixed(accountBAccessTokenCurrent, "expected account B access token");- requireFixed(accountBRefreshTokenCurrent, "expected account B refresh token");- expect(invalidations).toBe(0);- } finally {- releaseRefresh.resolve();- await Promise.allSettled([refresh]);- }- } finally {- unsubscribe();- }- }- );-- it("never retries an old-account request with the new account authorization", async () => {- installSession();- const releaseRequest = deferred<void>();- const requestStarted = deferred<void>();- let protectedCalls = 0;- let refreshCalls = 0;- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/refresh") {- refreshCalls += 1;- } else {- protectedCalls += 1;- requestStarted.resolve();- await releaseRequest.promise;- }- return new Response(null, { status: 401 });- }));+ it("a 503 produces fixed unavailable state without retry", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return new Response(null, { status: 503 });+ });+ vi.stubGlobal("fetch", fetchMock);+ const http = await import("./http");+ const session = await import("./session");+ await expect(http.refreshAccessToken()).resolves.toBe(false);+ expect(session.isSessionUnavailable()).toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });- const request = apiRequest("/protected");- try {- await requestStarted.promise;- const accountB = beginIdentityTransition();- const installed = installTokenPairIfCurrent(- accountB,- "access-b",- "refresh-b",- "coordination-b",- 0- );- expect(installed).toBe(true);- releaseRequest.resolve();+ it("an indeterminate refresh performs one logout and never retries refresh", async () => {+ const fetchMock = vi.fn()+ .mockRejectedValueOnce(new TypeError("network"))+ .mockResolvedValueOnce(new Response(null, { status: 204 }));+ vi.stubGlobal("fetch", fetchMock);+ const http = await import("./http");+ await expect(http.refreshAccessToken()).resolves.toBe(false);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([+ "/auth/refresh", "/auth/logout"+ ]);+ });- await expect(request).rejects.toMatchObject({ status: 401 });- expect({ protectedCalls, refreshCalls }).toEqual({ protectedCalls: 1, refreshCalls: 0 });- const accountBAccessTokenCurrent = getAccessToken() === "access-b";- requireFixed(accountBAccessTokenCurrent, "expected account B access token");- } finally {- releaseRequest.resolve();- await Promise.allSettled([request]);- }+ it("missing Web Locks fails closed before network", async () => {+ Object.defineProperty(navigator, "locks", { configurable: true, value: undefined });+ const fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ const http = await import("./http");+ await expect(http.refreshAccessToken()).resolves.toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();});- it("removes an invalidation subscriber cleanly", () => {- installSession();- let calls = 0;- const unsubscribe = subscribeToSessionInvalidation(() => {- calls += 1;+ it("ordinary API requests include same-origin credentials and memory bearer", async () => {+ const fetchMock = vi.fn(async (input: string, init?: RequestInit) => {+ void input;+ void init;+ return new Response(JSON.stringify({ ok: true }), { status: 200 });});- unsubscribe();- invalidateSession(captureSession());- expect(calls).toBe(0);+ vi.stubGlobal("fetch", fetchMock);+ const session = await import("./session");+ session.setAccessToken("memory-bearer");+ const http = await import("./http");+ await http.apiRequest("/health", {}, false);+ const init = fetchMock.mock.calls[0]?.[1] as RequestInit;+ expect(init.credentials).toBe("same-origin");+ expect(new Headers(init.headers).get("Authorization")).toBe("Bearer memory-bearer");});});diff --git a/frontend/src/api/http.ts b/frontend/src/api/http.tsindex 9fa4de5..54a7f48 100644--- a/frontend/src/api/http.ts+++ b/frontend/src/api/http.ts@@ -1,13 +1,21 @@import type { TokenResponse } from "./types";import {+ REFRESH_COOKIE_LOCK,+ browserCoordinationAvailable,captureSession,invalidateSession,isSessionCurrent,+ markSessionUnavailable,readCoordinationRecord,- replaceTokenPairIfCurrent,+ replaceSessionIfCurrent,+ type CoordinationRecord,type SessionSnapshot} from "./session";+const CSRF_HEADER = "X-ARES-CSRF";+const CSRF_COOKIE_NAMES = ["__Host-ares-csrf", "ares-dev-csrf"] as const;+const CSRF_PATTERN = /^[A-Za-z0-9_-]{43}$/;+export class ApiError extends Error {readonly status: number;readonly detail: unknown;@@ -38,105 +46,218 @@ function errorDetail(body: unknown): unknown {return body;}+function validTokenResponse(value: unknown): value is TokenResponse {+ return (+ typeof value === "object"+ && value !== null+ && "access_token" in value+ && typeof value.access_token === "string"+ && value.access_token.length > 0+ && !("refresh_token" in value)+ && "session_coordination_key" in value+ && typeof value.session_coordination_key === "string"+ && /^[A-Za-z0-9_-]{43}$/.test(value.session_coordination_key)+ && "refresh_generation" in value+ && typeof value.refresh_generation === "number"+ && Number.isSafeInteger(value.refresh_generation)+ && value.refresh_generation >= 0+ );+}++export function readBrowserCsrfToken(): string | null {+ let source: string;+ try {+ source = document.cookie;+ } catch {+ return null;+ }+ const found: string[] = [];+ for (const item of source.split(";")) {+ const separator = item.indexOf("=");+ if (separator < 1) {+ continue;+ }+ const name = item.slice(0, separator).trim();+ const value = item.slice(separator + 1);+ if ((CSRF_COOKIE_NAMES as readonly string[]).includes(name)) {+ found.push(value);+ }+ }+ source = "";+ return found.length === 1 && CSRF_PATTERN.test(found[0]) ? found[0] : null;+}++export async function bootstrapBrowserCsrf(): Promise<void> {+ const response = await fetch("/auth/csrf", {+ method: "GET",+ credentials: "same-origin",+ cache: "no-store"+ });+ if (response.status !== 204) {+ const body = await parseResponse(response);+ throw new ApiError(response.status, errorDetail(body));+ }+}++async function requireBrowserCsrf(): Promise<string> {+ let value = readBrowserCsrfToken();+ if (value === null) {+ await bootstrapBrowserCsrf();+ value = readBrowserCsrfToken();+ }+ if (value === null) {+ throw new ApiError(403, "Browser request rejected");+ }+ return value;+}++export async function withRefreshCookieLock<T>(operation: () => Promise<T>): Promise<T> {+ if (!browserCoordinationAvailable()) {+ throw new ApiError(401, "Browser session coordination unavailable");+ }+ return navigator.locks.request(REFRESH_COOKIE_LOCK, operation);+}++async function browserMutationResponse(+ path: string,+ init: RequestInit,+ options: { authenticated: boolean }+): Promise<Response> {+ const csrf = await requireBrowserCsrf();+ const headers = new Headers(init.headers);+ headers.set(CSRF_HEADER, csrf);+ const requestInit = {+ ...init,+ method: "POST",+ credentials: "same-origin" as RequestCredentials,+ cache: "no-store" as RequestCache,+ headers+ };+ return options.authenticated+ ? fetchWithSession(path, requestInit, false)+ : fetch(path, requestInit);+}++export async function browserMutationRequest<T>(+ path: string,+ init: RequestInit = {},+ options: { authenticated?: boolean } = {}+): Promise<T> {+ const response = await browserMutationResponse(path, init, {+ authenticated: options.authenticated ?? false+ });+ const body = await parseResponse(response);+ if (!response.ok) {+ throw new ApiError(response.status, errorDetail(body));+ }+ return body as T;+}+interface RefreshFlight {readonly revision: number;- readonly refreshToken: string;promise: Promise<boolean>;}let refreshFlight: RefreshFlight | null = null;+const INVALID_EXPECTATION = Symbol("invalid-refresh-expectation");-async function performRefresh(snapshot: SessionSnapshot): Promise<boolean> {+function refreshExpectation(+ snapshot: SessionSnapshot+): CoordinationRecord | null | typeof INVALID_EXPECTATION {+ const shared = readCoordinationRecord();+ if (shared === null) {+ return snapshot.coordinationKey === null ? null : INVALID_EXPECTATION;+ }+ if (shared.tombstone) {+ return INVALID_EXPECTATION;+ }if (- !snapshot.refreshToken- || !snapshot.coordinationKey- || snapshot.refreshGeneration === null+ snapshot.coordinationKey !== null+ && (shared.key !== snapshot.coordinationKey+ || snapshot.refreshGeneration === null+ || shared.generation < snapshot.refreshGeneration)) {- return false;+ return INVALID_EXPECTATION;}+ return shared;+}+async function settleIndeterminateRefresh(snapshot: SessionSnapshot): Promise<void> {+ invalidateSession(snapshot);+ try {+ await browserMutationResponse("/auth/logout", {}, { authenticated: false });+ } catch {+ // Reauthentication is mandatory; no refresh or logout retry loop is permitted.+ }+}++async function performRefresh(snapshot: SessionSnapshot): Promise<boolean> {+ if (!isSessionCurrent(snapshot)) {+ return false;+ }+ const expected = refreshExpectation(snapshot);+ if (expected === INVALID_EXPECTATION) {+ invalidateSession(snapshot);+ return false;+ }try {- const response = await fetch("/auth/refresh", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ refresh_token: snapshot.refreshToken })+ const response = await browserMutationResponse("/auth/refresh", {}, {+ authenticated: false});if (!response.ok) {+ if (response.status === 503) {+ markSessionUnavailable(snapshot);+ } else {+ invalidateSession(snapshot);+ }+ return false;+ }+ const body = await parseResponse(response);+ if (!validTokenResponse(body)) {invalidateSession(snapshot);return false;}- const token = (await response.json()) as TokenResponse;if (- !token.access_token- || !token.refresh_token- || token.session_coordination_key !== snapshot.coordinationKey- || token.refresh_generation !== snapshot.refreshGeneration + 1+ expected !== null+ && (body.session_coordination_key !== expected.key+ || body.refresh_generation !== expected.generation + 1)) {invalidateSession(snapshot);return false;}- return replaceTokenPairIfCurrent(+ return replaceSessionIfCurrent(snapshot,- token.access_token,- token.refresh_token,- token.session_coordination_key,- token.refresh_generation+ body.access_token,+ body.session_coordination_key,+ body.refresh_generation);- } catch {- invalidateSession(snapshot);+ } catch (error) {+ if (error instanceof ApiError) {+ if (error.status === 503) {+ markSessionUnavailable(snapshot);+ } else {+ invalidateSession(snapshot);+ }+ return false;+ }+ await settleIndeterminateRefresh(snapshot);return false;}}export function refreshAccessToken(snapshot = captureSession()): Promise<boolean> {- if (- !snapshot.refreshToken- || !snapshot.coordinationKey- || snapshot.refreshGeneration === null- ) {+ if (!browserCoordinationAvailable()) {invalidateSession(snapshot);return Promise.resolve(false);}- if (- refreshFlight- && refreshFlight.revision === snapshot.revision- && refreshFlight.refreshToken === snapshot.refreshToken- ) {+ if (refreshFlight && refreshFlight.revision === snapshot.revision) {return refreshFlight.promise;}-const flight: RefreshFlight = {revision: snapshot.revision,- refreshToken: snapshot.refreshToken,promise: Promise.resolve(false)};- 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(() => {+ flight.promise = withRefreshCookieLock(() => performRefresh(snapshot)).finally(() => {if (refreshFlight === flight) {refreshFlight = null;}@@ -159,32 +280,31 @@ async function fetchWithSession(if (snapshot.accessToken) {headers.set("Authorization", `Bearer ${snapshot.accessToken}`);}- const response = await fetch(path, { ...init, headers });+ const response = await fetch(path, {+ ...init,+ credentials: "same-origin",+ headers+ });if (snapshot.accessToken && !isSessionCurrent(snapshot)) {throw sessionChangedError();}-if (response.status !== 401) {return response;}-if (!retry) {if (snapshot.accessToken) {invalidateSession(snapshot);}return response;}-const current = captureSession();if (!isSessionCurrent(snapshot)) {throw sessionChangedError();}-if (current.accessToken && current.accessToken !== snapshot.accessToken) {return fetchWithSession(path, init, false, current);}-if (await refreshAccessToken(current)) {const refreshed = captureSession();if (!isSessionCurrent(snapshot)) {@@ -192,8 +312,6 @@ async function fetchWithSession(}return fetchWithSession(path, init, false, refreshed);}-- invalidateSession(current);return response;}diff --git a/frontend/src/api/session.test.ts b/frontend/src/api/session.test.tsnew file mode 100644index 0000000..9348cb1--- /dev/null+++ b/frontend/src/api/session.test.ts@@ -0,0 +1,133 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const KEY_A = "A".repeat(43);+const KEY_B = "B".repeat(43);++function installLocks(): void {+ Object.defineProperty(navigator, "locks", {+ configurable: true,+ value: { request: vi.fn(async (_name: string, operation: () => unknown) => operation()) }+ });+}++describe("cookie-backed session state", () => {+ beforeEach(async () => {+ sessionStorage.clear();+ localStorage.clear();+ installLocks();+ vi.resetModules();+ });++ it("deletes the legacy refresh token synchronously on module load", async () => {+ sessionStorage.setItem("ares.refreshToken", "legacy-value");+ await import("./session");+ expect(sessionStorage.getItem("ares.refreshToken")).toBeNull();+ });++ it("fails closed when legacy refresh storage cannot be cleared", async () => {+ const failure = vi.spyOn(Storage.prototype, "removeItem").mockImplementationOnce(() => {+ throw new Error("fixed-storage-failure");+ });+ const session = await import("./session");+ expect(session.browserCoordinationAvailable()).toBe(false);+ failure.mockRestore();+ });++ it("keeps access tokens in module memory only", async () => {+ const session = await import("./session");+ session.setAccessToken("memory-only");+ expect(session.getAccessToken()).toBe("memory-only");+ expect(JSON.stringify(sessionStorage)).not.toContain("memory-only");+ expect(JSON.stringify(localStorage)).not.toContain("memory-only");+ });++ it("requires Web Locks and writable localStorage", async () => {+ const session = await import("./session");+ expect(session.browserCoordinationAvailable()).toBe(true);+ Object.defineProperty(navigator, "locks", { configurable: true, value: undefined });+ expect(session.browserCoordinationAvailable()).toBe(false);+ });++ it("publishes only versioned non-secret coordination metadata", async () => {+ const session = await import("./session");+ const snapshot = session.beginIdentityTransition();+ expect(session.installSessionIfCurrent(snapshot, "access", KEY_A, 1)).toBe(true);+ expect(session.readCoordinationRecord()).toEqual({+ version: 2,+ key: KEY_A,+ generation: 1,+ tombstone: false+ });+ expect(localStorage.getItem("ares.sessionCoordination.v2")).not.toContain("access");+ });++ it.each([+ null,+ {},+ { version: 1, key: KEY_A, generation: 0, tombstone: false },+ { version: 2, key: "short", generation: 0, tombstone: false },+ { version: 2, key: KEY_A, generation: -1, tombstone: false },+ { version: 2, key: KEY_A, generation: 0, tombstone: "false" }+ ])("rejects malformed coordination records", async (value) => {+ const session = await import("./session");+ expect(session.parseCoordinationRecord(value)).toBeNull();+ });++ it("normal generation advancement preserves an access token", async () => {+ const session = await import("./session");+ const snapshot = session.beginIdentityTransition();+ session.installSessionIfCurrent(snapshot, "access-a", KEY_A, 1);+ window.dispatchEvent(new StorageEvent("storage", {+ key: "ares.sessionCoordination.v2",+ newValue: JSON.stringify({ version: 2, key: KEY_A, generation: 2, tombstone: false })+ }));+ expect(session.getAccessToken()).toBe("access-a");+ expect(session.captureSession().refreshGeneration).toBe(2);+ });++ it("a matching tombstone clears in-memory access", async () => {+ const session = await import("./session");+ const snapshot = session.beginIdentityTransition();+ session.installSessionIfCurrent(snapshot, "access-a", KEY_A, 1);+ window.dispatchEvent(new StorageEvent("storage", {+ key: "ares.sessionCoordination.v2",+ newValue: JSON.stringify({ version: 2, key: KEY_A, generation: 1, tombstone: true })+ }));+ expect(session.getAccessToken()).toBeNull();+ });++ it("a different-family message cannot alter local authority", async () => {+ const session = await import("./session");+ const snapshot = session.beginIdentityTransition();+ session.installSessionIfCurrent(snapshot, "access-a", KEY_A, 1);+ window.dispatchEvent(new StorageEvent("storage", {+ key: "ares.sessionCoordination.v2",+ newValue: JSON.stringify({ version: 2, key: KEY_B, generation: 2, tombstone: true })+ }));+ expect(session.getAccessToken()).toBe("access-a");+ });++ it("stale revisions cannot install a late response", async () => {+ const session = await import("./session");+ const stale = session.captureSession();+ session.clearTokens();+ expect(session.installSessionIfCurrent(stale, "late", KEY_A, 1)).toBe(false);+ expect(session.getAccessToken()).toBeNull();+ });++ it("identity transitions publish a tombstone for the old family", async () => {+ const session = await import("./session");+ const first = session.beginIdentityTransition();+ session.installSessionIfCurrent(first, "access", KEY_A, 3);+ session.beginIdentityTransition();+ expect(session.readCoordinationRecord()?.tombstone).toBe(true);+ });++ it("unavailable state is fixed and contains no credential", async () => {+ const session = await import("./session");+ const snapshot = session.captureSession();+ expect(session.markSessionUnavailable(snapshot)).toBe(true);+ expect(session.isSessionUnavailable()).toBe(true);+ expect(session.getAccessToken()).toBeNull();+ });+});diff --git a/frontend/src/api/session.ts b/frontend/src/api/session.tsindex b3aa111..731c5a8 100644--- a/frontend/src/api/session.ts+++ b/frontend/src/api/session.ts@@ -1,132 +1,157 @@-const REFRESH_TOKEN_KEY = "ares.refreshToken";-const COORDINATION_KEY = "ares.sessionCoordination";-const COORDINATION_CHANNEL = "ares.session-control";+const LEGACY_REFRESH_TOKEN_KEY = "ares.refreshToken";+const COORDINATION_KEY = "ares.sessionCoordination.v2";+const COORDINATION_CHANNEL = "ares.session-control-v2";+const COORDINATION_VERSION = 2;+const MAX_GENERATION = 1_000_000_000;++// Rollout hygiene is synchronous and precedes every possible network operation.+let legacyStorageCleared = true;+try {+ sessionStorage.removeItem(LEGACY_REFRESH_TOKEN_KEY);+} catch {+ legacyStorageCleared = false;+}let accessToken: string | null = null;let sessionRevision = 0;-let refreshTokenSuppressed = false;let coordinationKey: string | null = null;let refreshGeneration: number | null = null;+let unavailable = false;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 {+export interface CoordinationRecord {+ readonly version: 2;readonly key: string;readonly generation: number;readonly tombstone: boolean;}-function publishCoordination(record: CoordinationRecord): void {+function isCoordinationKey(value: unknown): value is string {+ return typeof value === "string" && /^[A-Za-z0-9_-]{43}$/.test(value);+}++export function parseCoordinationRecord(value: unknown): CoordinationRecord | null {+ if (+ typeof value !== "object"+ || value === null+ || !("version" in value)+ || !("key" in value)+ || !("generation" in value)+ || !("tombstone" in value)+ || value.version !== COORDINATION_VERSION+ || !isCoordinationKey(value.key)+ || typeof value.generation !== "number"+ || !Number.isSafeInteger(value.generation)+ || value.generation < 0+ || value.generation > MAX_GENERATION+ || typeof value.tombstone !== "boolean"+ ) {+ return null;+ }+ return value as CoordinationRecord;+}++function notifyInvalidation(): void {+ for (const listener of [...invalidationListeners]) {+ try {+ listener();+ } catch {+ // One local subscriber cannot prevent the remaining cleanup subscribers.+ }+ }+}++export function browserCoordinationAvailable(): boolean {+ if (+ !legacyStorageCleared+ || !navigator.locks+ || typeof navigator.locks.request !== "function"+ ) {+ return false;+ }+ try {+ const probe = "ares.sessionCoordination.probe";+ localStorage.setItem(probe, "2");+ const writable = localStorage.getItem(probe) === "2";+ localStorage.removeItem(probe);+ return writable;+ } catch {+ return false;+ }+}++export function publishCoordination(record: CoordinationRecord): boolean {+ if (parseCoordinationRecord(record) === null) {+ return false;+ }try {localStorage.setItem(COORDINATION_KEY, JSON.stringify(record));+ if (localStorage.getItem(COORDINATION_KEY) !== JSON.stringify(record)) {+ return false;+ }} catch {- // In-memory state remains fail-closed when cross-tab storage is unavailable.+ return false;}try {const channel = new BroadcastChannel(COORDINATION_CHANNEL);channel.postMessage(record);channel.close();} catch {- // Web Locks plus local state still protect the current tab.+ // Strictly validated localStorage events are the required fallback.}+ return true;}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"- ) {+ const raw = localStorage.getItem(COORDINATION_KEY);+ if (raw === null) {return null;}- return value as CoordinationRecord;+ return parseCoordinationRecord(JSON.parse(raw) as unknown);} catch {return null;}}-function persistRefreshToken(token: string | null): boolean {- try {- if (token) {- sessionStorage.setItem(REFRESH_TOKEN_KEY, token);- } else {- sessionStorage.removeItem(REFRESH_TOKEN_KEY);- }- refreshTokenSuppressed = false;- return true;- } catch {- if (token) {- try {- sessionStorage.removeItem(REFRESH_TOKEN_KEY);- } catch {- try {- sessionStorage.setItem(REFRESH_TOKEN_KEY, "");- } catch {- // In-memory suppression remains authoritative while storage is unavailable.- }- }- } else {- try {- sessionStorage.setItem(REFRESH_TOKEN_KEY, "");- } catch {- // In-memory suppression remains authoritative while storage is unavailable.- }- }- refreshTokenSuppressed = true;- return false;- }-}--function writeTokenPair(+function writeLocalSession(nextAccessToken: string | null,- nextRefreshToken: string | null,- nextCoordinationKey: string | null = null,- nextGeneration: number | null = null+ nextCoordinationKey: string | null,+ nextGeneration: number | null,+ options: { publish: boolean }): 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;- }- if (!persistRefreshToken(nextRefreshToken)) {- accessToken = null;- return false;- }accessToken = nextAccessToken;coordinationKey = nextCoordinationKey;refreshGeneration = nextGeneration;- if (coordinationKey !== null && refreshGeneration !== null) {- publishCoordination({- key: coordinationKey,- generation: refreshGeneration,- tombstone: false- });+ unavailable = false;+ if (!options.publish || nextCoordinationKey === null || nextGeneration === null) {+ return true;}- return true;+ return publishCoordination({+ version: COORDINATION_VERSION,+ key: nextCoordinationKey,+ generation: nextGeneration,+ tombstone: false+ });+}++function publishTombstone(): boolean {+ if (coordinationKey === null || refreshGeneration === null) {+ return true;+ }+ return publishCoordination({+ version: COORDINATION_VERSION,+ key: coordinationKey,+ generation: refreshGeneration,+ tombstone: true+ });}export function setAccessToken(token: string | null): void {@@ -137,27 +162,10 @@ export function getAccessToken(): string | null {return accessToken;}-export function setRefreshToken(token: string | null): void {- persistRefreshToken(token);-}--export function getRefreshToken(): string | null {- if (refreshTokenSuppressed) {- return null;- }- try {- return sessionStorage.getItem(REFRESH_TOKEN_KEY) || null;- } catch {- refreshTokenSuppressed = true;- return null;- }-}-export function captureSession(): SessionSnapshot {return {revision: sessionRevision,accessToken,- refreshToken: getRefreshToken(),coordinationKey,refreshGeneration};@@ -168,68 +176,114 @@ export function isSessionCurrent(snapshot: Pick<SessionSnapshot, "revision">): b}export function beginIdentityTransition(): SessionSnapshot {+ publishTombstone();sessionRevision += 1;- writeTokenPair(null, null);+ writeLocalSession(null, null, null, { publish: false });return captureSession();}+export function installSessionIfCurrent(+ snapshot: Pick<SessionSnapshot, "revision">,+ nextAccessToken: string,+ nextCoordinationKey: string,+ nextGeneration: number+): boolean {+ if (+ !isSessionCurrent(snapshot)+ || !nextAccessToken+ || !isCoordinationKey(nextCoordinationKey)+ || !Number.isSafeInteger(nextGeneration)+ || nextGeneration < 0+ || nextGeneration > MAX_GENERATION+ ) {+ return false;+ }+ if (!writeLocalSession(+ nextAccessToken,+ nextCoordinationKey,+ nextGeneration,+ { publish: true }+ )) {+ accessToken = null;+ coordinationKey = null;+ refreshGeneration = null;+ return false;+ }+ return true;+}++// Compatibility signature for the protected dashboard test surface. The legacy+// refresh argument is deliberately discarded and can never enter browser state.export function installTokenPairIfCurrent(snapshot: Pick<SessionSnapshot, "revision">,nextAccessToken: string,- nextRefreshToken: string,+ _legacyRefreshToken: string,nextCoordinationKey: string | null = null,nextGeneration: number | null = null): boolean {- if (!isSessionCurrent(snapshot)) {- return false;+ if (nextCoordinationKey === null || nextGeneration === null) {+ if (!isSessionCurrent(snapshot) || !nextAccessToken) {+ return false;+ }+ accessToken = nextAccessToken;+ return true;}- return writeTokenPair(+ return installSessionIfCurrent(+ snapshot,nextAccessToken,- nextRefreshToken,nextCoordinationKey,nextGeneration);}-export function replaceTokenPairIfCurrent(- snapshot: SessionSnapshot,+export function replaceSessionIfCurrent(+ snapshot: Pick<SessionSnapshot, "revision">,nextAccessToken: string,- nextRefreshToken: string,- nextCoordinationKey: string | null = snapshot.coordinationKey,- nextGeneration: number | null = snapshot.refreshGeneration+ nextCoordinationKey: string,+ nextGeneration: number): boolean {- if (- !isSessionCurrent(snapshot)- || getRefreshToken() !== snapshot.refreshToken- ) {- return false;- }- return writeTokenPair(+ return installSessionIfCurrent(+ snapshot,nextAccessToken,- nextRefreshToken,nextCoordinationKey,nextGeneration);}export function clearTokens(): void {+ publishTombstone();sessionRevision += 1;- writeTokenPair(null, null);+ writeLocalSession(null, null, null, { publish: false });}-export function invalidateSession(snapshot?: Pick<SessionSnapshot, "revision">): boolean {+export function markSessionUnavailable(+ snapshot?: Pick<SessionSnapshot, "revision">+): boolean {if (snapshot && !isSessionCurrent(snapshot)) {return false;}+ publishTombstone();sessionRevision += 1;- writeTokenPair(null, null);- for (const listener of [...invalidationListeners]) {- try {- listener();- } catch {- // One subscriber must not prevent the remaining local cleanup subscribers.- }+ accessToken = null;+ coordinationKey = null;+ refreshGeneration = null;+ unavailable = true;+ notifyInvalidation();+ return true;+}++export function isSessionUnavailable(): boolean {+ return unavailable;+}++export function invalidateSession(snapshot?: Pick<SessionSnapshot, "revision">): boolean {+ if (snapshot && !isSessionCurrent(snapshot)) {+ return false;}+ publishTombstone();+ sessionRevision += 1;+ writeLocalSession(null, null, null, { publish: false });+ notifyInvalidation();return true;}@@ -240,41 +294,44 @@ export function subscribeToSessionInvalidation(listener: () => void): () => void};}-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)- ) {+function applyPeerRecord(value: unknown): void {+ const record = parseCoordinationRecord(value);+ if (record === null || coordinationKey === null || record.key !== coordinationKey) {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.- }+ if (record.tombstone) {+ sessionRevision += 1;+ writeLocalSession(null, null, null, { publish: false });+ notifyInvalidation();+ return;+ }+ if (refreshGeneration !== null && record.generation > refreshGeneration) {+ refreshGeneration = record.generation;}}try {const peerChannel = new BroadcastChannel(COORDINATION_CHANNEL);peerChannel.onmessage = (event: MessageEvent<unknown>) => {- applyPeerInvalidation(event.data);+ applyPeerRecord(event.data);};} catch {- // Lack of a safe channel is handled by the refresh fail-closed path.+ // Validated storage events remain the notification fallback.}++try {+ window.addEventListener("storage", (event: StorageEvent) => {+ if (event.key !== COORDINATION_KEY || event.newValue === null) {+ return;+ }+ try {+ applyPeerRecord(JSON.parse(event.newValue) as unknown);+ } catch {+ // Invalid records never alter local authority.+ }+ });+} catch {+ // Browser coordination availability is checked before session operations.+}++export const REFRESH_COOKIE_LOCK = "ares-refresh-cookie-v2";diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.tsindex 24b94d7..fe644dd 100644--- a/frontend/src/api/types.ts+++ b/frontend/src/api/types.ts@@ -2,7 +2,6 @@ export type Role = "team_lead" | "operator" | "recon" | "reporter" | string;export interface TokenResponse {access_token: string;- refresh_token: string;token_type: string;expires_in: number;role: Role;diff --git a/frontend/src/features/auth/AuthProvider.test.tsx b/frontend/src/features/auth/AuthProvider.test.tsxindex 84515b6..c198f52 100644--- a/frontend/src/features/auth/AuthProvider.test.tsx+++ b/frontend/src/features/auth/AuthProvider.test.tsx@@ -1,693 +1,154 @@import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { act, cleanup, render, waitFor } from "@testing-library/react";-import { StrictMode } from "react";+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { apiRequest } from "../../api/http";-import {- beginIdentityTransition,- clearTokens,- getAccessToken,- getRefreshToken,- installTokenPairIfCurrent,- setRefreshToken-} from "../../api/session";-import { useDashboardSessionWriter } from "../dashboard/dashboardUiState";-import { AuthProvider } from "./AuthProvider";-import { type AuthState, useAuth } from "./authContext";--let currentAuth: AuthState | undefined;-let currentDashboardWriter: ((key: string, value: unknown) => boolean) | undefined;--function deferred<T>() {- let resolve!: (value: T | PromiseLike<T>) => void;- let reject!: (reason?: unknown) => void;- const promise = new Promise<T>((resolvePromise, rejectPromise) => {- resolve = resolvePromise;- reject = rejectPromise;- });- return { promise, reject, resolve };-}--function requireFixed(condition: boolean, message: string): void {- if (!condition) {- throw new Error(message);+import type { ReactNode } from "react";++const runtime = vi.hoisted(() => ({+ revision: 0,+ refresh: vi.fn(async () => false),+ login: vi.fn(async () => undefined),+ logout: vi.fn(async () => undefined),+ logoutAll: vi.fn(async () => undefined),+ me: vi.fn(async () => ({ username: "alice", role: "operator" })),+ invalidation: null as (() => void) | null+}));++vi.mock("../../api/client", () => ({+ api: { me: runtime.me },+ browserCoordinationAvailable: () => true,+ captureSession: () => ({+ revision: runtime.revision,+ accessToken: null,+ coordinationKey: null,+ refreshGeneration: null+ }),+ clearTokens: vi.fn(() => { runtime.revision += 1; }),+ invalidateSession: vi.fn((snapshot?: { revision: number }) => {+ if (snapshot && snapshot.revision !== runtime.revision) return false;+ runtime.revision += 1;+ runtime.invalidation?.();+ return true;+ }),+ isSessionCurrent: (snapshot: { revision: number }) => snapshot.revision === runtime.revision,+ login: runtime.login,+ logout: runtime.logout,+ logoutAll: runtime.logoutAll,+ refreshAccessToken: runtime.refresh,+ subscribeToSessionInvalidation: (listener: () => void) => {+ runtime.invalidation = listener;+ return () => { runtime.invalidation = null; };}-}--function requireTokensUnavailable(): void {- const accessTokenUnavailable = getAccessToken() === null;- const refreshTokenUnavailable = getRefreshToken() === null;- requireFixed(accessTokenUnavailable, "Access token should remain unavailable.");- requireFixed(refreshTokenUnavailable, "Refresh token should remain unavailable.");-}+}));-function requireRefreshTokenUnavailable(): void {- const refreshTokenUnavailable = getRefreshToken() === null;- requireFixed(refreshTokenUnavailable, "Refresh token should remain unavailable.");-}--function AuthProbe() {- currentAuth = useAuth();- currentDashboardWriter = useDashboardSessionWriter();- return <span>{currentAuth.user?.username ?? "logged-out"}</span>;-}+vi.mock("../dashboard/dashboardUiState", () => ({+ bindDashboardPrincipal: vi.fn(),+ clearDashboardSession: vi.fn()+}));-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",- refresh_generation: generation,- session_coordination_key: coordinationKey- }), { status: 200 });-}+import { AuthProvider } from "./AuthProvider";+import { useAuth } from "./authContext";-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");-}+let latestAuth: ReturnType<typeof useAuth> | null = null;-function profileResponse(username: string, role = "operator"): Response {- return new Response(JSON.stringify({ username, role }), { status: 200 });+function Probe() {+ latestAuth = useAuth();+ return <div>{latestAuth.user?.username ?? "signed-out"}</div>;}-function createQueryClient(): QueryClient {- return new QueryClient({- defaultOptions: {- queries: { retry: false },- mutations: { retry: false }- }- });-}--function renderProvider(queryClient: QueryClient, strict = false) {- const tree = (+function renderProvider(children: ReactNode = <Probe />) {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ return render(<QueryClientProvider client={queryClient}>- <AuthProvider>- <AuthProbe />- </AuthProvider>+ <AuthProvider>{children}</AuthProvider></QueryClientProvider>);- return render(strict ? <StrictMode>{tree}</StrictMode> : tree);}-function auth(): AuthState {- if (!currentAuth) {- throw new Error("auth probe has not rendered");- }- return currentAuth;-}--function dashboardWriter(): (key: string, value: unknown) => boolean {- if (!currentDashboardWriter) {- throw new Error("dashboard writer probe has not rendered");- }- return currentDashboardWriter;-}--async function waitForLoggedOut(): Promise<void> {- await waitFor(() => {- expect(auth().loading).toBe(false);- expect(auth().user).toBeNull();- });-}--function seedAccountState(queryClient: QueryClient): void {- queryClient.setQueryData(["account-query"], { owner: "account-a" });- queryClient.getMutationCache().build(queryClient, {- mutationKey: ["account-mutation"],- mutationFn: async () => ({ ok: true })- });- sessionStorage.setItem("ares.dashboard.modules.search", JSON.stringify("account-a"));- sessionStorage.setItem("unrelated.same-origin", "keep");-}--function expectAccountStateCleared(queryClient: QueryClient): void {- expect(queryClient.getQueryCache().getAll()).toHaveLength(0);- expect(queryClient.getMutationCache().getAll()).toHaveLength(0);- const dashboardStateRemoved = sessionStorage.getItem("ares.dashboard.modules.search") === null;- const principalRemoved = sessionStorage.getItem("ares.dashboard.principal") === null;- const unrelatedStatePreserved = sessionStorage.getItem("unrelated.same-origin") === "keep";- requireFixed(dashboardStateRemoved, "Dashboard-owned state should be removed.");- requireFixed(principalRemoved, "Dashboard principal should be removed.");- requireFixed(unrelatedStatePreserved, "Unrelated session state should be preserved.");-}--function resetTestSessionStorage(): void {- const keys = Array.from({ length: sessionStorage.length }, (_, index) => sessionStorage.key(index))- .filter((key): key is string => key !== null);- for (const key of keys) {- sessionStorage.removeItem(key);- }-}--describe("AuthProvider session isolation", () => {+describe("AuthProvider cookie bootstrap", () => {beforeEach(() => {- currentAuth = undefined;- currentDashboardWriter = undefined;- clearTokens();- resetTestSessionStorage();- vi.unstubAllGlobals();- });-- afterEach(() => {- cleanup();- currentAuth = undefined;- currentDashboardWriter = undefined;- clearTokens();- resetTestSessionStorage();- vi.unstubAllGlobals();- vi.restoreAllMocks();- });-- it.each(["success", "HTTP failure", "network failure"] as const)(- "clears all local account state when logout has remote %s",- async (outcome) => {- const queryClient = createQueryClient();- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/token") {- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- return profileResponse("alice");- }- if (path === "/auth/logout") {- if (outcome === "network failure") {- throw new TypeError("offline");- }- if (outcome === "HTTP failure") {- return new Response(null, { status: 503 });- }- return new Response(JSON.stringify({ status: "ok" }), { status: 200 });- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- await act(async () => {- await auth().login("alice", "password");- });- seedAccountState(queryClient);-- await act(async () => {- await auth().logout();- });-- expect(auth().user).toBeNull();- requireTokensUnavailable();- expectAccountStateCleared(queryClient);- }- );-- it("cleans account state and exits loading when startup refresh fails", async () => {- const queryClient = createQueryClient();- installStoredSession();- seedAccountState(queryClient);- vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 401 })));-- renderProvider(queryClient);- await waitForLoggedOut();-- requireRefreshTokenUnavailable();- expectAccountStateCleared(queryClient);- });-- it("purges legacy dashboard state when startup has no refresh token", async () => {- const queryClient = createQueryClient();- sessionStorage.setItem("ares.dashboard.modules.params", JSON.stringify({ field: "legacy" }));- sessionStorage.setItem("ares.dashboard.live.events", JSON.stringify([{ kind: "legacy" }]));- sessionStorage.setItem("unrelated.same-origin", "keep");-- renderProvider(queryClient);- await waitForLoggedOut();-- const paramsRemoved = sessionStorage.getItem("ares.dashboard.modules.params") === null;- const eventsRemoved = sessionStorage.getItem("ares.dashboard.live.events") === null;- const unrelatedPreserved = sessionStorage.getItem("unrelated.same-origin") === "keep";- requireFixed(paramsRemoved && eventsRemoved, "Unauthenticated startup should purge legacy dashboard state.");- requireFixed(unrelatedPreserved, "Unauthenticated startup should preserve unrelated session state.");- });-- it("cleans account state when startup profile resolution fails", async () => {- const queryClient = createQueryClient();- installStoredSession();- seedAccountState(queryClient);- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/refresh") {- return tokenResponse("access-a", "refresh-b", 1);- }- if (path === "/auth/me") {- return new Response(null, { status: 503 });- }- return new Response(null, { status: 404 });- }));-- renderProvider(queryClient);- await waitForLoggedOut();-- requireTokensUnavailable();- expectAccountStateCleared(queryClient);- });-- it("reacts immediately to runtime refresh invalidation", async () => {- const queryClient = createQueryClient();- let runtime = false;- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/token") {- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- return profileResponse("alice");- }- if (path === "/runtime" && runtime) {- return new Response(null, { status: 401 });- }- if (path === "/auth/refresh" && runtime) {- return new Response(null, { status: 401 });- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- await act(async () => {- await auth().login("alice", "password");- });- seedAccountState(queryClient);- runtime = true;-- await act(async () => {- await apiRequest("/runtime").catch(() => undefined);- });-- expect(auth().user).toBeNull();- expectAccountStateCleared(queryClient);- });-- it("prevents a late refresh from restoring a session after provider logout", async () => {- const queryClient = createQueryClient();- const refreshStarted = deferred<void>();- const releaseRefresh = deferred<void>();- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/token") {- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- return profileResponse("alice");- }- if (path === "/runtime") {- return new Response(null, { status: 401 });- }- if (path === "/auth/refresh") {- refreshStarted.resolve();- await releaseRefresh.promise;- return tokenResponse("access-late", "refresh-late", 1);- }- if (path === "/auth/logout") {- return new Response(JSON.stringify({ status: "ok" }), { status: 200 });- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- await act(async () => {- await auth().login("alice", "password");- });- seedAccountState(queryClient);-- const runtimeRequest = apiRequest("/runtime");- try {- await refreshStarted.promise;- await act(async () => {- await auth().logout();- });- releaseRefresh.resolve();- await act(async () => {- await runtimeRequest.catch(() => undefined);- });-- expect(auth().user).toBeNull();- requireTokensUnavailable();- expectAccountStateCleared(queryClient);- } finally {- releaseRefresh.resolve();- await Promise.allSettled([runtimeRequest]);- }- });-- it.each(["success", "failure"] as const)(- "keeps account B isolated from a late account-A refresh %s",- async (outcome) => {- const queryClient = createQueryClient();- const refreshStarted = deferred<void>();- const releaseRefresh = deferred<void>();- let runtime = false;- vi.stubGlobal("fetch", vi.fn(async (path: string, init?: RequestInit) => {- if (path === "/auth/token") {- const username = new URLSearchParams(String(init?.body)).get("username");- return username === "bob"- ? tokenResponse("access-b", "refresh-b", 0, "coordination-b")- : tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- const authorization = new Headers(init?.headers).get("Authorization");- return profileResponse(authorization === "Bearer access-b" ? "bob" : "alice");- }- if (path === "/runtime" && runtime) {- return new Response(null, { status: 401 });- }- if (path === "/auth/refresh" && runtime) {- refreshStarted.resolve();- await releaseRefresh.promise;- return outcome === "success"- ? tokenResponse("access-a-late", "refresh-a-late", 1)- : new Response(null, { status: 401 });- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- await act(async () => {- await auth().login("alice", "password");- });- seedAccountState(queryClient);- runtime = true;-- const runtimeRequest = apiRequest("/runtime");- try {- await refreshStarted.promise;- await act(async () => {- await auth().login("bob", "password");- });- queryClient.setQueryData(["account-b"], { retained: true });- sessionStorage.setItem("ares.dashboard.modules.category", JSON.stringify("network"));- releaseRefresh.resolve();- await act(async () => {- await runtimeRequest.catch(() => undefined);- });-- expect(auth().user?.username).toBe("bob");- expect(queryClient.getQueryData(["account-b"])).toEqual({ retained: true });- const preferencePreserved =- sessionStorage.getItem("ares.dashboard.modules.category") === JSON.stringify("network");- const principalMatches =- sessionStorage.getItem("ares.dashboard.principal")- === JSON.stringify({ username: "bob", role: "operator" });- requireFixed(preferencePreserved, "Account B preference should be preserved.");- requireFixed(principalMatches, "Account B principal should remain current.");- const accountBAccessTokenCurrent = getAccessToken() === "access-b";- const accountBRefreshTokenCurrent = getRefreshToken() === "refresh-b";- requireFixed(accountBAccessTokenCurrent, "expected account B access token");- requireFixed(accountBRefreshTokenCurrent, "expected account B refresh token");- } finally {- releaseRefresh.resolve();- await Promise.allSettled([runtimeRequest]);- }- }- );-- it.each(["owned session", "newer session"] as const)(- "rejects a deferred login after provider unmount without altering the %s",- async (sessionOwner) => {- const queryClient = createQueryClient();- const profileStarted = deferred<void>();- const releaseProfile = deferred<void>();- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/token") {- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- profileStarted.resolve();- await releaseProfile.promise;- return profileResponse("alice");- }- return new Response(null, { status: 404 });- }));- const provider = renderProvider(queryClient);- await waitForLoggedOut();-- let loginOutcome: Promise<"resolved" | "rejected"> | undefined;- try {- await act(async () => {- const loginPromise = auth().login("alice", "password");- loginOutcome = loginPromise.then(- () => "resolved" as const,- () => "rejected" as const- );- await profileStarted.promise;- });-- provider.unmount();- if (sessionOwner === "newer session") {- const newerSession = beginIdentityTransition();- const installed = installTokenPairIfCurrent(- newerSession,- "access-b",- "refresh-b",- "coordination-b",- 0- );- requireFixed(installed, "expected newer session installation");- }- releaseProfile.resolve();-- if (!loginOutcome) {- throw new Error("login outcome observer was not installed");- }- const outcome = await loginOutcome;- expect(outcome).toBe("rejected");- expect(auth().user).toBeNull();- const principalAbsent = sessionStorage.getItem("ares.dashboard.principal") === null;- requireFixed(principalAbsent, "Abandoned login should not persist a principal.");- if (sessionOwner === "owned session") {- requireTokensUnavailable();- } else {- const newerAccessTokenCurrent = getAccessToken() === "access-b";- const newerRefreshTokenCurrent = getRefreshToken() === "refresh-b";- requireFixed(newerAccessTokenCurrent, "expected newer access session to survive");- requireFixed(newerRefreshTokenCurrent, "expected newer refresh session to survive");- }- } finally {- releaseProfile.resolve();- if (loginOutcome) {- await Promise.allSettled([loginOutcome]);- }- provider.unmount();- }- }- );-- it("finishes local logout when refresh-token removal throws", async () => {- const queryClient = createQueryClient();- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/token") {- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- return profileResponse("alice");- }- if (path === "/auth/logout") {- return new Response(JSON.stringify({ status: "ok" }), { status: 200 });- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- await act(async () => {- await auth().login("alice", "password");- });- seedAccountState(queryClient);-- const originalRemoveItem = Storage.prototype.removeItem;- const removeItem = vi.spyOn(Storage.prototype, "removeItem").mockImplementation(function (- this: Storage,- key: string- ) {- if (key === "ares.refreshToken") {- throw new DOMException("unavailable", "SecurityError");- }- return originalRemoveItem.call(this, key);- });- try {- await act(async () => {- await auth().logout();- });- expect(auth().user).toBeNull();- requireTokensUnavailable();- expectAccountStateCleared(queryClient);- } finally {- removeItem.mockRestore();- setRefreshToken(null);- }- });-- it("shares startup refresh under StrictMode and applies one current profile", async () => {- const queryClient = createQueryClient();- installStoredSession();- sessionStorage.setItem(- "ares.dashboard.principal",- JSON.stringify({ username: "alice", role: "operator" })- );- sessionStorage.setItem("ares.dashboard.modules.category", JSON.stringify("network"));- sessionStorage.setItem("ares.dashboard.modules.dryRun", JSON.stringify(false));- let refreshCalls = 0;- let profileCalls = 0;- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/refresh") {- refreshCalls += 1;- return tokenResponse("access-a", "refresh-b", 1);- }- if (path === "/auth/me") {- profileCalls += 1;- return profileResponse("alice");- }- return new Response(null, { status: 404 });- }));-- renderProvider(queryClient, true);- await waitFor(() => expect(auth().user?.username).toBe("alice"));-- expect({ profileCalls, refreshCalls }).toEqual({ profileCalls: 1, refreshCalls: 1 });- const preferencePreserved =- sessionStorage.getItem("ares.dashboard.modules.category") === JSON.stringify("network");- const legacySafetyStatePurged =- sessionStorage.getItem("ares.dashboard.modules.dryRun") === null;- requireFixed(preferencePreserved, "StrictMode startup should preserve dashboard preference.");- requireFixed(legacySafetyStatePurged, "StrictMode startup should purge disallowed legacy state.");- });-- it("clears account A data before account B is authenticated or rendered", async () => {- const queryClient = createQueryClient();- let accountBStartedClean = false;- vi.stubGlobal("fetch", vi.fn(async (path: string, init?: RequestInit) => {- if (path === "/auth/token") {- const username = new URLSearchParams(String(init?.body)).get("username");- if (username === "bob") {- accountBStartedClean = (- queryClient.getQueryCache().getAll().length === 0- && queryClient.getMutationCache().getAll().length === 0- && sessionStorage.getItem("ares.dashboard.modules.search") === null- );- return tokenResponse("access-b", "refresh-b", 0, "coordination-b");- }- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- const authorization = new Headers(init?.headers).get("Authorization");- return profileResponse(authorization === "Bearer access-b" ? "bob" : "alice");- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- await act(async () => {- await auth().login("alice", "password");- });- seedAccountState(queryClient);- const accountAWriter = dashboardWriter();-- await act(async () => {- await auth().login("bob", "password");- });-- expect(accountBStartedClean).toBe(true);- expect(auth().user?.username).toBe("bob");- const principalMatches =- sessionStorage.getItem("ares.dashboard.principal")- === JSON.stringify({ username: "bob", role: "operator" });- const unrelatedStatePreserved = sessionStorage.getItem("unrelated.same-origin") === "keep";- requireFixed(principalMatches, "Account B principal should be current.");- requireFixed(unrelatedStatePreserved, "Unrelated session state should be preserved.");- expect(accountAWriter("ares.dashboard.templates.tab", "stale")).toBe(false);- expect(dashboardWriter()("ares.dashboard.templates.tab", "Plan Builder")).toBe(true);- const currentWriterPersisted =- sessionStorage.getItem("ares.dashboard.templates.tab") === JSON.stringify("Plan Builder");- requireFixed(currentWriterPersisted, "Current dashboard writer should persist state.");- });-- it("leaves no local session when profile resolution fails after login", async () => {- const queryClient = createQueryClient();- vi.stubGlobal("fetch", vi.fn(async (path: string) => {- if (path === "/auth/token") {- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- return new Response(null, { status: 500 });- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- seedAccountState(queryClient);-- let rejected = false;- await act(async () => {- try {- await auth().login("alice", "password");- } catch {- rejected = true;- }- });-- expect(rejected).toBe(true);- expect(auth().user).toBeNull();- requireTokensUnavailable();- expectAccountStateCleared(queryClient);- });-- it("preserves user, cache, and dashboard preferences after same-session runtime refresh", async () => {- const queryClient = createQueryClient();- let runtime = false;- vi.stubGlobal("fetch", vi.fn(async (path: string, init?: RequestInit) => {- if (path === "/auth/token") {- return tokenResponse("access-a", "refresh-a");- }- if (path === "/auth/me") {- return profileResponse("alice");- }- if (path === "/auth/refresh" && runtime) {- return tokenResponse("access-b", "refresh-b", 1);- }- if (path === "/runtime" && runtime) {- const authorization = new Headers(init?.headers).get("Authorization");- return authorization === "Bearer access-b"- ? new Response(JSON.stringify({ status: "ok" }), { status: 200 })- : new Response(null, { status: 401 });- }- return new Response(null, { status: 404 });- }));- renderProvider(queryClient);- await waitForLoggedOut();- await act(async () => {- await auth().login("alice", "password");- });- queryClient.setQueryData(["safe-preference"], { retained: true });- sessionStorage.setItem("ares.dashboard.modules.category", JSON.stringify("network"));- runtime = true;-- await act(async () => {- await apiRequest("/runtime");- });-- expect(auth().user?.username).toBe("alice");- expect(queryClient.getQueryData(["safe-preference"])).toEqual({ retained: true });- const preferencePreserved =- sessionStorage.getItem("ares.dashboard.modules.category") === JSON.stringify("network");- requireFixed(preferencePreserved, "Same-session refresh should preserve dashboard preference.");- const rotatedAccessTokenCurrent = getAccessToken() === "access-b";- requireFixed(rotatedAccessTokenCurrent, "expected same-session rotated access token");+ runtime.revision = 0;+ runtime.refresh.mockReset().mockResolvedValue(false);+ runtime.login.mockReset().mockResolvedValue(undefined);+ runtime.logout.mockReset().mockResolvedValue(undefined);+ runtime.logoutAll.mockReset().mockResolvedValue(undefined);+ runtime.me.mockReset().mockResolvedValue({ username: "alice", role: "operator" });+ runtime.invalidation = null;+ latestAuth = null;+ sessionStorage.clear();+ localStorage.clear();+ });++ afterEach(() => cleanup());++ it("performs exactly one startup cookie refresh", async () => {+ renderProvider();+ await waitFor(() => expect(screen.getByText("signed-out")).toBeTruthy());+ expect(runtime.refresh).toHaveBeenCalledTimes(1);+ });++ it("loads the current profile after a valid cookie bootstrap", async () => {+ runtime.refresh.mockResolvedValue(true);+ renderProvider();+ await waitFor(() => expect(screen.getByText("alice")).toBeTruthy());+ expect(runtime.me).toHaveBeenCalledTimes(1);+ });++ it("does not call the profile endpoint when the cookie is invalid", async () => {+ renderProvider();+ await waitFor(() => expect(screen.getByText("signed-out")).toBeTruthy());+ expect(runtime.me).not.toHaveBeenCalled();+ });++ it("login resolves the current profile", async () => {+ renderProvider();+ await waitFor(() => expect(latestAuth?.loading).toBe(false));+ await act(async () => { await latestAuth?.login("alice", "password"); });+ expect(runtime.login).toHaveBeenCalledTimes(1);+ expect(screen.getByText("alice")).toBeTruthy();+ });++ it("logout clears local state even when remote revocation fails", async () => {+ runtime.refresh.mockResolvedValue(true);+ runtime.logout.mockRejectedValue(new Error("unavailable"));+ renderProvider();+ await waitFor(() => expect(screen.getByText("alice")).toBeTruthy());+ await act(async () => { await latestAuth?.logout(); });+ expect(screen.getByText("signed-out")).toBeTruthy();+ });++ it("logout-all clears local state after remote success", async () => {+ runtime.refresh.mockResolvedValue(true);+ renderProvider();+ await waitFor(() => expect(screen.getByText("alice")).toBeTruthy());+ await act(async () => { await latestAuth?.logoutAll(); });+ expect(runtime.logoutAll).toHaveBeenCalledTimes(1);+ expect(screen.getByText("signed-out")).toBeTruthy();+ });++ it("a session invalidation notification clears current UI authority", async () => {+ runtime.refresh.mockResolvedValue(true);+ renderProvider();+ await waitFor(() => expect(screen.getByText("alice")).toBeTruthy());+ act(() => runtime.invalidation?.());+ expect(screen.getByText("signed-out")).toBeTruthy();+ });++ it("a late startup profile cannot restore an unmounted provider", async () => {+ let release: ((value: { username: string; role: string }) => void) | undefined;+ runtime.refresh.mockResolvedValue(true);+ runtime.me.mockReturnValue(new Promise((resolve) => { release = resolve; }));+ const view = renderProvider();+ await waitFor(() => expect(runtime.me).toHaveBeenCalledTimes(1));+ view.unmount();+ await act(async () => { release?.({ username: "alice", role: "operator" }); });+ expect(latestAuth?.user ?? null).toBeNull();+ });++ it("browser-readable storage never receives a refresh token", async () => {+ runtime.refresh.mockResolvedValue(true);+ renderProvider();+ await waitFor(() => expect(screen.getByText("alice")).toBeTruthy());+ expect(sessionStorage.getItem("ares.refreshToken")).toBeNull();+ expect(JSON.stringify(localStorage)).not.toContain("refresh_token");});});diff --git a/frontend/src/features/auth/AuthProvider.tsx b/frontend/src/features/auth/AuthProvider.tsxindex b27d32b..2ca9d6c 100644--- a/frontend/src/features/auth/AuthProvider.tsx+++ b/frontend/src/features/auth/AuthProvider.tsx@@ -2,9 +2,9 @@ import { useQueryClient } from "@tanstack/react-query";import { Fragment, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";import {api,+ browserCoordinationAvailable,captureSession,clearTokens,- getRefreshToken,invalidateSession,isSessionCurrent,login as loginRequest,@@ -30,7 +30,7 @@ function LoadingSession() {export function AuthProvider({ children }: { children: ReactNode }) {const [user, setUser] = useState<UserProfile | null>(null);- const [loading, setLoading] = useState(Boolean(getRefreshToken()));+ const [loading, setLoading] = useState(browserCoordinationAvailable());const [accountBoundary, setAccountBoundary] = useState(0);const providerLifecycle = useRef({ generation: 0, mounted: false });const queryClient = useQueryClient();@@ -70,7 +70,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {useEffect(() => {let active = true;- if (!getRefreshToken()) {+ if (!browserCoordinationAvailable()) {resetLocalSession();setLoading(false);return;diff --git a/frontend/vite.app.config.mjs b/frontend/vite.app.config.mjsindex 0ce6323..ff07d56 100644--- a/frontend/vite.app.config.mjs+++ b/frontend/vite.app.config.mjs@@ -7,6 +7,13 @@ import { defineConfig } from "vite";const apiOrigin = process.env.VITE_API_ORIGIN ?? "http://127.0.0.1:8080";const wsOrigin = apiOrigin.replace(/^http/, "ws");+function apiProxy() {+ return {+ target: apiOrigin,+ changeOrigin: false,+ };+}+function dashboardBasePathRedirect() {return {name: "dashboard-base-path-redirect",@@ -31,20 +38,21 @@ export default defineConfig({base: "/dashboard/",server: {proxy: {- "/auth": apiOrigin,- "/campaigns": apiOrigin,- "/modules": apiOrigin,- "/reports": apiOrigin,- "/stats": apiOrigin,- "/telemetry": apiOrigin,- "/graph": apiOrigin,- "/security": apiOrigin,- "/strategy": apiOrigin,- "/edr": apiOrigin,- "/templates": apiOrigin,- "/health": apiOrigin,+ "/auth": apiProxy(),+ "/campaigns": apiProxy(),+ "/modules": apiProxy(),+ "/reports": apiProxy(),+ "/stats": apiProxy(),+ "/telemetry": apiProxy(),+ "/graph": apiProxy(),+ "/security": apiProxy(),+ "/strategy": apiProxy(),+ "/edr": apiProxy(),+ "/templates": apiProxy(),+ "/health": apiProxy(),"/ws": {target: wsOrigin,+ changeOrigin: false,ws: true,},},diff --git a/scripts/run_validation_lab.ps1 b/scripts/run_validation_lab.ps1index e953c44..cbe445f 100644--- a/scripts/run_validation_lab.ps1+++ b/scripts/run_validation_lab.ps1@@ -1,5 +1,8 @@param(- [string]$BaseUrl = "http://localhost:8080",+ [ValidateNotNullOrEmpty()]+ [string]$BaseUrl = "http://127.0.0.1:5173",+ [ValidateNotNullOrEmpty()]+ [string]$BrowserOrigin = "http://127.0.0.1:5173",[string]$Username = "admin")@@ -11,4 +14,8 @@ if (-not (Test-Path $Python)) {$Python = "python"}-& $Python (Join-Path $PSScriptRoot "validation_lab.py") --base-url $BaseUrl --username $Username+& $Python (Join-Path $PSScriptRoot "validation_lab.py") `+ --base-url $BaseUrl `+ --browser-origin $BrowserOrigin `+ --username $Username+exit $LASTEXITCODEdiff --git a/scripts/validation_lab.py b/scripts/validation_lab.pyindex 30dd36d..ded8cba 100644--- a/scripts/validation_lab.py+++ b/scripts/validation_lab.py@@ -1,44 +1,157 @@-"""Local ARES validation lab.--This harness exercises safe localhost-only API flows:-- health check-- login + /auth/me-- campaign input validation-- campaign create/list/delete/list-- module dry-run validation-- API key create/list/delete/list-- report generate/list--It intentionally refuses non-localhost targets unless --allow-remote is passed.-"""-+"""Bounded validation lab using the real browser-cookie authentication contract."""from __future__ import annotationsimport argparse+import base64import getpass+import hmac+import http.cookiejarimport jsonimport os+import reimport sysimport time-from dataclasses import dataclass+from dataclasses import dataclass, fieldfrom typing import Anyfrom urllib import error, parse, request+_LOOPBACK_ORIGINS = {+ "http://127.0.0.1:5173",+ "http://localhost:5173",+}+_CSRF_COOKIE_NAMES = {"__Host-ares-csrf", "ares-dev-csrf"}+_CSRF_PATTERN = re.compile(r"[A-Za-z0-9_-]{43}\Z")+_BLOCKED_DRY_RUN_FORBIDDEN_FIELDS = frozenset(+ {+ "artifact",+ "artifacts",+ "credential",+ "credentials",+ "executed",+ "execution",+ "execution_result",+ "execution_status",+ "finding",+ "findings",+ "output",+ "outputs",+ "result",+ "results",+ "succeeded",+ "success",+ }+)+++class ValidationLabError(RuntimeError):+ """Fixed, non-sensitive validation-lab failure."""++ def __init__(self, operation: str, *, status: int | None = None) -> None:+ self.operation = operation+ self.status = status+ suffix = "" if status is None else f":status-{status}"+ super().__init__(f"validation-lab:{operation}{suffix}")+++@dataclass(frozen=True, slots=True, eq=False)+class ApiResult:+ status: int+ body: Any = field(repr=False)-LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}+class _RejectRedirects(request.HTTPRedirectHandler):+ """Turn every redirect into an ordinary fixed-status failure."""-@dataclass-class ApiResult:- status: int- body: Any- headers: dict[str, str]+ def redirect_request(+ self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str+ ) -> None:+ del req, fp, code, msg, headers, newurl+ return None+++def _canonical_public_origin(value: object, *, allow_remote: bool) -> str:+ if not isinstance(value, str) or not value or value != value.strip() or "," in value:+ raise ValidationLabError("origin-invalid")+ try:+ parsed = parse.urlsplit(value)+ port = parsed.port+ except (TypeError, ValueError):+ raise ValidationLabError("origin-invalid") from None+ if (+ parsed.scheme not in {"http", "https"}+ or parsed.hostname is None+ or parsed.hostname.endswith(".")+ or parsed.username is not None+ or parsed.password is not None+ or parsed.path+ or parsed.query+ or parsed.fragment+ ):+ raise ValidationLabError("origin-invalid")+ try:+ host = parsed.hostname.encode("ascii").decode("ascii").lower()+ except UnicodeError:+ raise ValidationLabError("origin-invalid") from None+ if host != parsed.hostname.lower() or ":" in host:+ raise ValidationLabError("origin-invalid")+ default_port = 80 if parsed.scheme == "http" else 443+ if port == default_port:+ raise ValidationLabError("origin-invalid")+ authority = host if port is None else f"{host}:{port}"+ canonical = f"{parsed.scheme}://{authority}"+ if not hmac.compare_digest(canonical, value):+ raise ValidationLabError("origin-invalid")+ if parsed.scheme == "http" and canonical not in _LOOPBACK_ORIGINS:+ raise ValidationLabError("origin-insecure")+ if canonical not in _LOOPBACK_ORIGINS and not allow_remote:+ raise ValidationLabError("remote-not-authorized")+ return canonical+++def _is_canonical_csrf(value: object) -> bool:+ if not isinstance(value, str) or _CSRF_PATTERN.fullmatch(value) is None:+ return False+ try:+ decoded = base64.urlsafe_b64decode(value + "=")+ except (TypeError, ValueError):+ return False+ canonical = base64.urlsafe_b64encode(decoded).rstrip(b"=").decode("ascii")+ return len(decoded) == 32 and hmac.compare_digest(canonical, value)class ApiClient:- def __init__(self, base_url: str) -> None:- self.base_url = base_url.rstrip("/")+ """Cookie-aware client whose representations never contain credentials."""++ def __init__(self, base_url: str, browser_origin: str, *, allow_remote: bool = False) -> None:+ canonical_base = _canonical_public_origin(base_url, allow_remote=allow_remote)+ canonical_origin = _canonical_public_origin(browser_origin, allow_remote=allow_remote)+ if not hmac.compare_digest(canonical_base, canonical_origin):+ raise ValidationLabError("origin-mismatch")+ self.base_url = canonical_base+ self.browser_origin = canonical_originself.access_token: str | None = None+ self._csrf_cookie_name = (+ "ares-dev-csrf"+ if canonical_origin in _LOOPBACK_ORIGINS+ else "__Host-ares-csrf"+ )+ self._cookie_jar = http.cookiejar.CookieJar()+ self._opener = request.build_opener(+ request.HTTPCookieProcessor(self._cookie_jar),+ _RejectRedirects(),+ )++ def _current_csrf(self) -> str:+ matches: list[http.cookiejar.Cookie] = []+ for cookie in self._cookie_jar:+ if cookie.name in _CSRF_COOKIE_NAMES and not cookie.is_expired():+ matches.append(cookie)+ if len(matches) != 1 or matches[0].name != self._csrf_cookie_name:+ raise ValidationLabError("csrf-cookie-invalid")+ value = matches[0].value+ if not _is_canonical_csrf(value):+ raise ValidationLabError("csrf-cookie-invalid")+ return valuedef request(self,@@ -47,41 +160,109 @@ class ApiClient:body: Any = None,form: dict[str, str] | None = None,expect: set[int] | None = None,+ *,+ authenticated: bool = True,+ browser_headers: bool = False,+ empty_body: bool = False,) -> ApiResult:- expect = expect or {200}+ expected = expect or {200}url = f"{self.base_url}{path}"headers: dict[str, str] = {"Accept": "application/json"}- data: bytes | None = None-+ data: bytes | None = b"" if empty_body else Noneif form is not None:data = parse.urlencode(form).encode("utf-8")headers["Content-Type"] = "application/x-www-form-urlencoded"elif body is not None:data = json.dumps(body).encode("utf-8")headers["Content-Type"] = "application/json"-- if self.access_token:+ if browser_headers:+ headers["Origin"] = self.browser_origin+ if method.upper() != "GET":+ headers["X-ARES-CSRF"] = self._current_csrf()+ if authenticated:+ if self.access_token is None:+ raise ValidationLabError("access-authority-missing")headers["Authorization"] = f"Bearer {self.access_token}"- req = request.Request(url, data=data, headers=headers, method=method)+ outgoing = request.Request( # noqa: S310 - URL origin was strictly validated+ url, data=data, headers=headers, method=method+ )try:- with request.urlopen(req, timeout=15) as resp:- raw = resp.read().decode("utf-8", errors="replace")- parsed = _parse_body(raw)- result = ApiResult(resp.status, parsed, dict(resp.headers.items()))+ with self._opener.open(outgoing, timeout=15) as response: # noqa: S310+ raw = response.read().decode("utf-8", errors="replace")+ result = ApiResult(response.status, _parse_body(raw))except error.HTTPError as exc:raw = exc.read().decode("utf-8", errors="replace")- result = ApiResult(exc.code, _parse_body(raw), dict(exc.headers.items()))- except error.URLError as exc:- raise RuntimeError(f"Cannot reach {url}: {exc}") from exc-- if result.status not in expect:- raise RuntimeError(- f"{method} {path} expected {sorted(expect)}, got {result.status}: "- f"{_compact(result.body)}"- )+ result = ApiResult(exc.code, _parse_body(raw))+ except (error.URLError, TimeoutError, OSError):+ raise ValidationLabError("request-unavailable") from None+ if result.status not in expected:+ raise ValidationLabError("request-status", status=result.status)return result+ def bootstrap_csrf(self) -> None:+ self.request(+ "GET",+ "/auth/csrf",+ expect={204},+ authenticated=False,+ browser_headers=True,+ )+ self._current_csrf()++ def login(self, username: str, password: str) -> None:+ self.bootstrap_csrf()+ result = self.request(+ "POST",+ "/auth/token",+ form={"username": username, "password": password},+ authenticated=False,+ browser_headers=True,+ )+ body = result.body+ if (+ not isinstance(body, dict)+ or "refresh_token" in body+ or not isinstance(body.get("access_token"), str)+ or not body["access_token"]+ ):+ raise ValidationLabError("login-contract-invalid")+ self.access_token = body["access_token"]+ self._current_csrf()++ def refresh(self) -> None:+ result = self.request(+ "POST",+ "/auth/refresh",+ expect={200},+ authenticated=False,+ browser_headers=True,+ empty_body=True,+ )+ body = result.body+ if (+ not isinstance(body, dict)+ or "refresh_token" in body+ or not isinstance(body.get("access_token"), str)+ or not body["access_token"]+ ):+ raise ValidationLabError("refresh-contract-invalid")+ self.access_token = body["access_token"]+ self._current_csrf()++ def logout(self) -> None:+ try:+ self.request(+ "POST",+ "/auth/logout",+ expect={204},+ authenticated=False,+ browser_headers=True,+ empty_body=True,+ )+ finally:+ self.access_token = None+def _parse_body(raw: str) -> Any:if not raw:@@ -89,223 +270,258 @@ def _parse_body(raw: str) -> Any:try:return json.loads(raw)except json.JSONDecodeError:- return raw---def _compact(value: Any) -> str:- return json.dumps(value, separators=(",", ":"), default=str)[:500]---def _require_localhost(base_url: str, allow_remote: bool) -> None:- parsed = parse.urlparse(base_url)- host = parsed.hostname or ""- if allow_remote or host in LOCAL_HOSTS:- return- raise SystemExit(- f"Refusing to run validation lab against non-local host {host!r}. "- "Use --allow-remote only for an explicitly authorized lab."- )+ return None-def _password_from_env_or_prompt(username: str) -> str:+def _password_from_env_or_prompt() -> str:password = os.getenv("ARES_LAB_PASSWORD") or os.getenv("ARES_DEFAULT_ADMIN_PASSWORD")if password:return password- return getpass.getpass(f"Password for {username}: ")+ return getpass.getpass("Validation lab password: ")-def _ok(label: str, detail: str = "") -> None:- suffix = f" - {detail}" if detail else ""- print(f"[OK] {label}{suffix}")+def _ok(label: str) -> None:+ print(f"[OK] {label}")def _fail(label: str, exc: Exception) -> None:- print(f"[FAIL] {label} - {exc}")+ if isinstance(exc, ValidationLabError) and exc.status is not None:+ print(f"[FAIL] {label} - status={exc.status}")+ else:+ print(f"[FAIL] {label} - type={type(exc).__name__}")+++def _raise_fixed() -> None:+ raise ValidationLabError("contract-check-failed")+++def _validate_blocked_module_dry_run(value: object) -> None:+ """Require the fixed, side-effect-free response for missing module parameters."""+ if not isinstance(value, dict):+ _raise_fixed()+ missing_params = value.get("missing_params")+ if (+ value.get("dry_run") is not True+ or value.get("status") != "dry_run_blocked"+ or value.get("would_execute") is not False+ or not isinstance(missing_params, list)+ or not missing_params+ or any(not isinstance(item, str) or not item for item in missing_params)+ ):+ _raise_fixed()++ pending: list[object] = [value]+ while pending:+ item = pending.pop()+ if isinstance(item, dict):+ for key, child in item.items():+ if (+ isinstance(key, str)+ and key.casefold() in _BLOCKED_DRY_RUN_FORBIDDEN_FIELDS+ ):+ _raise_fixed()+ pending.append(child)+ elif isinstance(item, list):+ pending.extend(item)def run_lab(args: argparse.Namespace) -> int:- _require_localhost(args.base_url, args.allow_remote)- client = ApiClient(args.base_url)+ if not args.browser_origin:+ raise ValidationLabError("browser-origin-required")+ client = ApiClient(+ args.base_url,+ args.browser_origin,+ allow_remote=bool(args.allow_remote),+ )username = args.username- password = args.password or _password_from_env_or_prompt(username)+ password = _password_from_env_or_prompt()failures: list[str] = []- def step(label: str, fn) -> Any:+ def step(label: str, fn: Any) -> Any:try:result = fn()- _ok(label, result if isinstance(result, str) else "")+ _ok(label)return result- except Exception as exc: # noqa: BLE001 - lab should continue and report all failures+ except Exception as exc: # noqa: BLE001 - continue bounded independent checksfailures.append(label)_fail(label, exc)return None- step("health endpoint", lambda: client.request("GET", "/health").body.get("status"))-- def login() -> str:- token = client.request(- "POST",- "/auth/token",- form={"username": username, "password": password},- ).body- client.access_token = token["access_token"]- return "token accepted"-- step("login", login)- me = step("current profile", lambda: client.request("GET", "/auth/me").body)- if isinstance(me, dict):- _ok("profile role", f"{me.get('username')} / {me.get('role')}")-- def invalid_campaign_target() -> str:- client.request(- "POST",- "/campaigns",- body={- "name": "ARES Validation Bad Target",- "client": "Local Lab",- "targets": ["../not-a-target"],- "scope_cidrs": [],- },- expect={422},+ try:+ step(+ "health endpoint",+ lambda: client.request(+ "GET", "/health", authenticated=False+ ).body.get("status"),)- return "422 rejected traversal-like target"-- step("campaign target validation", invalid_campaign_target)- campaign_id_holder: dict[str, str] = {}+ step("browser login", lambda: client.login(username, password))+ password = ""+ step("current profile", lambda: client.request("GET", "/auth/me").body)- def create_campaign() -> str:- campaign = client.request(- "POST",- "/campaigns",- body={- "name": f"ARES Validation Lab {int(time.time())}",- "client": "Local Lab",- "targets": ["127.0.0.1"],- "scope_cidrs": ["127.0.0.1/32"],- },- ).body- campaign_id_holder["id"] = campaign["id"]- return campaign["id"]-- step("create local campaign", create_campaign)- campaign_id = campaign_id_holder.get("id")-- if campaign_id:step(- "campaign appears in list",- lambda: "found"- if any(c.get("id") == campaign_id for c in client.request("GET", "/campaigns").body)- else (_raise("campaign not found in list")),+ "campaign target validation",+ lambda: client.request(+ "POST",+ "/campaigns",+ body={+ "name": "ARES Validation Bad Target",+ "client": "Local Lab",+ "targets": ["../not-a-target"],+ "scope_cidrs": [],+ },+ expect={422},+ ),)- def plan_dry_run_validation() -> str:- body = {- "plan": {- "stages": [- {- "name": "validation-only",- "modules": ["ad.kerberoast"],- }- ]- },- "global_params": {},- "dry_run": True,- }- result = client.request(+ campaign_id_holder: dict[str, str] = {}++ def create_campaign() -> None:+ campaign = client.request("POST",- f"/campaigns/{parse.quote(campaign_id)}/run",- body=body,+ "/campaigns",+ body={+ "name": f"ARES Validation Lab {int(time.time())}",+ "client": "Local Lab",+ "targets": ["127.0.0.1"],+ "scope_cidrs": ["127.0.0.1/32"],+ },).body- if result.get("param_validation", {}).get("ok") is not False:- raise RuntimeError("expected dry-run param_validation.ok=false")- return "dry-run caught missing params"-- step("module dry-run validation", plan_dry_run_validation)+ campaign_id = campaign.get("id") if isinstance(campaign, dict) else None+ if not isinstance(campaign_id, str) or not campaign_id:+ _raise_fixed()+ campaign_id_holder["id"] = campaign_id++ step("create local campaign", create_campaign)+ campaign_id = campaign_id_holder.get("id")+ if campaign_id:+ def campaign_present() -> None:+ rows = client.request("GET", "/campaigns").body+ if not isinstance(rows, list) or not any(+ isinstance(row, dict) and row.get("id") == campaign_id for row in rows+ ):+ _raise_fixed()++ step("campaign appears in list", campaign_present)++ def plan_dry_run_validation() -> None:+ result = client.request(+ "POST",+ f"/campaigns/{parse.quote(campaign_id)}/run",+ body={+ "plan": {+ "stages": [+ {"name": "validation-only", "modules": ["ad.kerberoast"]}+ ]+ },+ "global_params": {},+ "dry_run": True,+ },+ ).body+ if (+ not isinstance(result, dict)+ or result.get("param_validation", {}).get("ok") is not False+ ):+ _raise_fixed()++ step("module dry-run validation", plan_dry_run_validation)+ def module_param_dry_run_validation() -> None:+ result = client.request(+ "POST",+ "/modules/ad.kerberoast/run",+ body={"campaign_id": campaign_id, "params": {}, "dry_run": True},+ expect={200},+ ).body+ _validate_blocked_module_dry_run(result)++ step(+ "dry-run blocked missing parameters",+ module_param_dry_run_validation,+ )- def direct_module_param_validation() -> str:- client.request(- "POST",- "/modules/ad.kerberoast/run",- body={"campaign_id": campaign_id, "params": {}, "dry_run": True},- expect={422},+ def generate_report() -> None:+ result = client.request(+ "POST", f"/reports/{parse.quote(campaign_id)}?fmt=html"+ ).body+ filename = result.get("filename") if isinstance(result, dict) else None+ if not isinstance(filename, str) or not filename.endswith(".html"):+ _raise_fixed()++ step("report generation", generate_report)+ step(+ "report list",+ lambda: client.request("GET", f"/reports/{parse.quote(campaign_id)}").body,)- return "422 rejected missing module params"- step("module API param validation", direct_module_param_validation)+ api_key_id_holder: dict[str, str] = {}- def generate_report() -> str:- result = client.request(+ def api_key_create() -> None:+ body = client.request("POST",- f"/reports/{parse.quote(campaign_id)}?fmt=html",+ "/auth/api-keys",+ body={"name": f"validation-lab-{int(time.time())}", "scopes": "read"},).body- filename = result.get("filename", "")- if not filename.endswith(".html"):- raise RuntimeError(f"unexpected report filename: {filename}")- return filename-- step("report generation", generate_report)- step(- "report list",- lambda: f"{len(client.request('GET', f'/reports/{parse.quote(campaign_id)}').body.get('reports', []))} report(s)",- )-- api_key_id_holder: dict[str, str] = {}-- def api_key_create() -> str:- result = client.request(- "POST",- "/auth/api-keys",- body={"name": f"validation-lab-{int(time.time())}", "scopes": "read"},- ).body- key_id = result.get("id")- if not key_id:- raise RuntimeError(f"missing id in API key response: {_compact(result)}")- api_key_id_holder["id"] = key_id- return key_id-- step("API key create", api_key_create)-- def api_key_list_contains() -> str:- key_id = api_key_id_holder["id"]- keys = client.request("GET", "/auth/api-keys").body- if not any(k.get("id") == key_id for k in keys):- raise RuntimeError("new API key not visible in list")- return "visible"-- if api_key_id_holder.get("id"):- step("API key list after create", api_key_list_contains)- step(- "API key delete",- lambda: client.request(- "DELETE", f"/auth/api-keys/{parse.quote(api_key_id_holder['id'])}"- ).body.get("status", ""),- )-- def api_key_removed_from_list() -> str:- key_id = api_key_id_holder["id"]- keys = client.request("GET", "/auth/api-keys").body- if any(k.get("id") == key_id for k in keys):- raise RuntimeError("deleted API key is still visible")- return "removed"-- step("API key list after delete", api_key_removed_from_list)-- if campaign_id:- step(- "campaign delete",- lambda: client.request(- "DELETE", f"/campaigns/{parse.quote(campaign_id)}"- ).body.get("status", ""),- )+ key_id = body.get("id") if isinstance(body, dict) else None+ if not isinstance(key_id, str) or not key_id:+ _raise_fixed()+ api_key_id_holder["id"] = key_id++ step("API key create", api_key_create)+ if api_key_id_holder.get("id"):+ def api_key_present() -> None:+ key_id = api_key_id_holder["id"]+ rows = client.request("GET", "/auth/api-keys").body+ if not isinstance(rows, list) or not any(+ isinstance(row, dict) and row.get("id") == key_id for row in rows+ ):+ _raise_fixed()++ step("API key list after create", api_key_present)+ step(+ "API key delete",+ lambda: client.request(+ "DELETE",+ f"/auth/api-keys/{parse.quote(api_key_id_holder['id'])}",+ ),+ )- def campaign_removed_from_list() -> str:- campaigns = client.request("GET", "/campaigns").body- if any(c.get("id") == campaign_id for c in campaigns):- raise RuntimeError("deleted campaign is still visible")- return "removed"+ def api_key_absent() -> None:+ key_id = api_key_id_holder["id"]+ rows = client.request("GET", "/auth/api-keys").body+ if not isinstance(rows, list) or any(+ isinstance(row, dict) and row.get("id") == key_id for row in rows+ ):+ _raise_fixed()++ step("API key list after delete", api_key_absent)++ if campaign_id:+ step(+ "campaign delete",+ lambda: client.request(+ "DELETE", f"/campaigns/{parse.quote(campaign_id)}"+ ),+ )- step("campaign list after delete", campaign_removed_from_list)+ def campaign_absent() -> None:+ rows = client.request("GET", "/campaigns").body+ if not isinstance(rows, list) or any(+ isinstance(row, dict) and row.get("id") == campaign_id for row in rows+ ):+ _raise_fixed()++ step("campaign list after delete", campaign_absent)+ finally:+ password = ""+ if client.access_token is not None:+ try:+ client.logout()+ _ok("browser logout cleanup")+ except Exception as exc: # noqa: BLE001 - cleanup failure becomes a fixed gate+ failures.append("browser logout cleanup")+ _fail("browser logout cleanup", exc)+ finally:+ client.access_token = Noneprint()if failures:@@ -317,25 +533,27 @@ def run_lab(args: argparse.Namespace) -> int:return 0-def _raise(message: str) -> None:- raise RuntimeError(message)--def build_parser() -> argparse.ArgumentParser:- parser = argparse.ArgumentParser(description="Run local ARES validation lab checks.")- parser.add_argument("--base-url", default=os.getenv("ARES_LAB_BASE_URL", "http://localhost:8080"))+ parser = argparse.ArgumentParser(description="Run bounded ARES validation lab checks.")+ parser.add_argument("--base-url", default=os.getenv("ARES_LAB_BASE_URL"))+ parser.add_argument(+ "--browser-origin",+ default=os.getenv("ARES_LAB_BROWSER_ORIGIN") or os.getenv("ARES_BROWSER_ORIGIN"),+ )parser.add_argument("--username", default=os.getenv("ARES_LAB_USERNAME", "admin"))- parser.add_argument("--password", default=os.getenv("ARES_LAB_PASSWORD"))parser.add_argument("--allow-remote",action="store_true",- help="Allow a non-localhost base URL. Use only for an authorized lab.",+ help="Allow one exact HTTPS origin for an explicitly authorized remote lab.",)return parserdef main() -> int:- return run_lab(build_parser().parse_args())+ args = build_parser().parse_args()+ if not args.base_url:+ raise ValidationLabError("base-url-required")+ return run_lab(args)if __name__ == "__main__":diff --git a/tests/integration/test_api_post.py b/tests/integration/test_api_post.pyindex 7a7ebde..b0f6871 100644--- a/tests/integration/test_api_post.py+++ b/tests/integration/test_api_post.py@@ -43,6 +43,8 @@ def isolated_api_post_environment():"ARES_ENCRYPTION_KEY": _ENCKEY,"ARES_DEFAULT_ADMIN_PASSWORD": _ADMIN,"ARES_DATABASE_URL": _DBURL,+ "ARES_DEBUG": "true",+ "ARES_BROWSER_ORIGIN": "http://localhost:5173",}original = {key: os.environ.get(key) for key in updates}os.environ.update(updates)@@ -66,12 +68,40 @@ def _fresh_client() -> TestClient:from ares.core.config import get_settingsget_settings.cache_clear() # clear lru_cache — force re-read from envfrom ares.api.server import app- return TestClient(app, base_url="http://localhost", raise_server_exceptions=False)+ return TestClient(app, base_url="http://localhost:5173", raise_server_exceptions=False)+++def _csrf(client: TestClient) -> str:+ value = client.cookies.get("ares-dev-csrf")+ if not value:+ response = client.get(+ "/auth/csrf",+ headers={"Origin": "http://localhost:5173"},+ )+ assert response.status_code == 204+ value = client.cookies.get("ares-dev-csrf")+ assert value+ return value+++def _browser_post(client: TestClient, path: str, **kwargs):+ headers = dict(kwargs.pop("headers", {}))+ headers.update(+ {+ "Origin": "http://localhost:5173",+ "Sec-Fetch-Site": "same-origin",+ "X-ARES-CSRF": _csrf(client),+ }+ )+ return client.post(path, headers=headers, **kwargs)def _login(client: TestClient, password: str = _ADMIN) -> str:- r = client.post("/auth/token",- data={"username": "admin", "password": password})+ r = _browser_post(+ client,+ "/auth/token",+ data={"username": "admin", "password": password},+ )assert r.status_code == 200, f"Login failed ({r.status_code}): {r.text}"return r.json()["access_token"]@@ -94,38 +124,42 @@ class TestAuthPostEndpoints:return _login(c)def test_login_valid_returns_tokens(self, c):- r = c.post("/auth/token", data={"username": "admin", "password": _ADMIN})+ r = _browser_post(c, "/auth/token", data={"username": "admin", "password": _ADMIN})assert r.status_code == 200body = r.json()assert "access_token" in body- assert "refresh_token" in body+ assert "refresh_token" not in bodyassert body["token_type"] == "bearer"assert body["role"] == "team_lead"def test_login_wrong_password_returns_401(self, c):- r = c.post("/auth/token", data={"username": "admin", "password": "WrongPass!"})+ r = _browser_post(c, "/auth/token", data={"username": "admin", "password": "WrongPass!"})assert r.status_code == 401def test_login_unknown_user_returns_401(self, c):- r = c.post("/auth/token", data={"username": "nobody", "password": "anything"})+ r = _browser_post(c, "/auth/token", data={"username": "nobody", "password": "anything"})assert r.status_code == 401def test_refresh_invalid_token_returns_401(self, c):- r = c.post("/auth/refresh", json={"refresh_token": "not-a-real-token"})- assert r.status_code == 401+ r = _browser_post(c, "/auth/refresh", json={"refresh_token": "not-a-real-token"})+ assert r.status_code == 400def test_refresh_valid_rotates_token(self, c):- r = c.post("/auth/token", data={"username": "admin", "password": _ADMIN})+ r = _browser_post(c, "/auth/token", data={"username": "admin", "password": _ADMIN})assert r.status_code == 200- old_refresh = r.json()["refresh_token"]+ old_refresh = c.cookies.get("ares-dev-refresh")+ assert old_refresh- r2 = c.post("/auth/refresh", json={"refresh_token": old_refresh})+ r2 = _browser_post(c, "/auth/refresh")assert r2.status_code == 200assert "access_token" in r2.json()- assert "refresh_token" in r2.json()+ assert "refresh_token" not in r2.json()# Old refresh token must now be revoked- r3 = c.post("/auth/refresh", json={"refresh_token": old_refresh})+ c.cookies.set(+ "ares-dev-refresh", old_refresh, domain="localhost.local", path="/"+ )+ r3 = _browser_post(c, "/auth/refresh")assert r3.status_code == 401def test_register_new_operator(self, c, token):@@ -150,8 +184,11 @@ class TestAuthPostEndpoints:def test_register_forbidden_for_non_team_lead(self, c, token):# Log in as the new operator- login = c.post("/auth/token",- data={"username": "op_post_test", "password": "OpPass1!Test99"})+ login = _browser_post(+ c,+ "/auth/token",+ data={"username": "op_post_test", "password": "OpPass1!Test99"},+ )assert login.status_code == 200op_token = login.json()["access_token"]@@ -171,8 +208,11 @@ class TestAuthPostEndpoints:)assert r.status_code == 200# Change it back- login2 = c.post("/auth/token",- data={"username": "admin", "password": _ADMIN + "New"})+ login2 = _browser_post(+ c,+ "/auth/token",+ data={"username": "admin", "password": _ADMIN + "New"},+ )new_tok = login2.json()["access_token"]c.post("/auth/change-password",diff --git a/tests/integration/test_postgres_refresh_token_families.py b/tests/integration/test_postgres_refresh_token_families.pyindex 736764e..9fe6b0e 100644--- a/tests/integration/test_postgres_refresh_token_families.py+++ b/tests/integration/test_postgres_refresh_token_families.py@@ -164,3 +164,42 @@ async def test_real_postgres_logout_all_advances_epoch_across_pools() -> None:)finally:await observer.close()+++async def test_real_postgres_cookie_logout_expiry_and_replay_contract() -> None:+ async with _postgres_harness() as harness:+ database = harness.database+ await database.create_user(+ "cookie-family-pg-user",+ "CookieFamilyPass1!",+ "operator",+ )+ issued = await database.create_login_session(+ "cookie-family-pg-user",+ "CookieFamilyPass1!",+ _access_factory,+ )+ _require(issued.session is not None, "PostgreSQL cookie session missing")+ predecessor = issued.session.refresh_token+ expiry_is_authoritative = (+ issued.session.absolute_expires_at.tzinfo is not None+ and issued.session.absolute_expires_at > datetime.now(timezone.utc)+ )+ rotated = await database.rotate_refresh_session(predecessor, _access_factory)+ _require(rotated.session is not None, "PostgreSQL cookie successor missing")+ revoked = await database.revoke_refresh_cookie_session(predecessor)+ successor = await database.rotate_refresh_session(+ rotated.session.refresh_token,+ _access_factory,+ )+ repeated = await database.revoke_refresh_cookie_session(predecessor)+ unknown = await database.revoke_refresh_cookie_session("u" * 64)+ _require(+ expiry_is_authoritative+ and revoked.status is SessionRevocationStatus.REVOKED+ and successor.status is not RefreshRotationStatus.ROTATED+ and repeated.status is SessionRevocationStatus.ALREADY_REVOKED+ and unknown.status is SessionRevocationStatus.INVALID,+ "PostgreSQL cookie logout/replay contract changed",+ )diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.pyindex 1c2bb16..c0032fd 100644--- a/tests/unit/test_api_endpoints.py+++ b/tests/unit/test_api_endpoints.py@@ -20,6 +20,7 @@ import asyncioimport base64import hashlibimport os+from datetime import datetime, timedelta, timezonefrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch@@ -33,6 +34,8 @@ from fastapi.security import OAuth2PasswordRequestFormos.environ.setdefault("ARES_SECRET_KEY", "test-api-secret-key-min32-chars!!")os.environ.setdefault("ARES_ENCRYPTION_KEY", "test-enc-key-min32-chars-xxxxxxx")os.environ.setdefault("ARES_DEFAULT_ADMIN_PASSWORD", "TestApiPass1!")+os.environ.setdefault("ARES_DEBUG", "true")+os.environ.setdefault("ARES_BROWSER_ORIGIN", "http://localhost:5173")# ── helpers ───────────────────────────────────────────────────────────────────@@ -85,11 +88,12 @@ def _issued_session(username: str = "admin", role: str = "team_lead"):SessionIssueStatus.ISSUED,IssuedTokenSession(access_token=token,- refresh_token="test-refresh-token", # noqa: S106 - fixed test value+ refresh_token="r" * 64, # noqa: S106 - fixed test valueuser_id="test-user-id",subject=username,family_id=family_id,auth_epoch=1,+ absolute_expires_at=datetime.now(timezone.utc) + timedelta(days=30),refresh_generation=0,role=role,),@@ -146,6 +150,9 @@ def _make_mock_db():db.revoke_current_session = AsyncMock(return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED))+ db.revoke_refresh_cookie_session = AsyncMock(+ return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED)+ )db.revoke_all_sessions = AsyncMock(return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED))@@ -280,10 +287,40 @@ def _app_mock_db():@pytest.fixture(scope="module")def aclient(_app_mock_db):- """Async httpx client with ASGITransport. base_url=localhost passes TrustedHostMiddleware."""+ """Async same-origin browser client with a rotating CSRF header."""_app, mock_db = _app_mock_dbtransport = httpx.ASGITransport(app=_app)- client = httpx.AsyncClient(transport=transport, base_url="http://localhost")+ client: httpx.AsyncClient++ async def _browser_headers(request: httpx.Request) -> None:+ if request.url.path in {+ "/auth/token",+ "/auth/refresh",+ "/auth/logout",+ "/auth/logout-all",+ }:+ request.headers["Origin"] = "http://localhost:5173"+ request.headers["Sec-Fetch-Site"] = "same-origin"+ try:+ csrf = client.cookies.get("ares-dev-csrf")+ except httpx.CookieConflict:+ csrf = None+ csrf = csrf or ("A" * 43)+ request.headers["X-ARES-CSRF"] = csrf+ cookie = request.headers.get("Cookie", "")+ if "ares-dev-csrf=" not in cookie:+ request.headers["Cookie"] = (+ f"{cookie}; ares-dev-csrf={csrf}" if cookie else f"ares-dev-csrf={csrf}"+ )++ client = httpx.AsyncClient(+ transport=transport,+ base_url="http://localhost:5173",+ event_hooks={"request": [_browser_headers]},+ )+ client.cookies.set(+ "ares-dev-csrf", "A" * 43, domain="localhost.local", path="/"+ )yield client, mock_db, _appasyncio.run(client.aclose())@@ -367,6 +404,32 @@ class TestSecurityHeaders:hdrs = {k.lower() for k in (await c.get("/health")).headers}assert "server" not in hdrs+ @pytest.mark.asyncio+ async def test_cors_is_exact_and_never_credentialed(self, aclient):+ c, _, __ = aclient+ allowed = await c.options(+ "/health",+ headers={+ "Origin": "http://localhost:3000",+ "Access-Control-Request-Method": "GET",+ },+ )+ denied = await c.options(+ "/health",+ headers={+ "Origin": "https://untrusted.example",+ "Access-Control-Request-Method": "GET",+ },+ )+ reduced = (+ allowed.headers.get("access-control-allow-origin")+ == "http://localhost:3000",+ "access-control-allow-credentials" not in allowed.headers,+ denied.headers.get("access-control-allow-origin") is None,+ "access-control-allow-credentials" not in denied.headers,+ )+ _require_fixed(all(reduced), "CORS credential boundary differed")+# ── Auth flow ─────────────────────────────────────────────────────────────────@@ -396,6 +459,24 @@ class TestAuthFlow:assert r.json().get("username") == "admin"assert r.json().get("role") == "team_lead"+ @pytest.mark.asyncio+ async def test_csrf_bootstrap_is_empty_uncacheable_and_cookie_only(self, aclient):+ c, _, __ = aclient+ response = await c.get("/auth/csrf")+ cookie_headers = response.headers.get_list("set-cookie")+ reduced = (+ response.status_code == 204,+ response.content == b"",+ response.headers.get("cache-control") == "no-store",+ response.headers.get("pragma") == "no-cache",+ len(cookie_headers) == 1,+ cookie_headers[0].startswith("ares-dev-csrf=") if cookie_headers else False,+ "httponly" not in cookie_headers[0].lower() if cookie_headers else False,+ "max-age=600" in cookie_headers[0].lower() if cookie_headers else False,+ )+ del cookie_headers+ _require_fixed(all(reduced), "CSRF bootstrap contract differed")+@pytest.mark.asyncioasync def test_login_invalid_credentials_returns_401(self, aclient):"""Login with mocked OAuth2PasswordRequestForm — invalid creds → 401."""@@ -437,8 +518,20 @@ class TestAuthFlow:assert r.status_code == 200body = r.json()assert "access_token" in body- assert "refresh_token" in body+ assert "refresh_token" not in bodyassert body["token_type"] == "bearer" # noqa: S105 - OAuth token type+ cookie_headers = r.headers.get_list("set-cookie")+ reduced = (+ len(cookie_headers) == 2,+ any(value.startswith("ares-dev-refresh=") for value in cookie_headers),+ any(value.startswith("ares-dev-csrf=") for value in cookie_headers),+ sum("httponly" in value.lower() for value in cookie_headers) == 1,+ all("samesite=strict" in value.lower() for value in cookie_headers),+ all("path=/" in value.lower() for value in cookie_headers),+ all("domain=" not in value.lower() for value in cookie_headers),+ )+ del cookie_headers+ _require_fixed(all(reduced), "Committed login cookie contract differed")finally:del _app.dependency_overrides[OAuth2PasswordRequestForm]db.create_login_session.return_value = None@@ -492,33 +585,89 @@ class TestAuthFlow:_reset_rate_limiter()db.rotate_refresh_session.reset_mock()db.create_refresh_token.reset_mock()-- response = await c.post(- "/auth/refresh",- json={"refresh_token": "inactive-refresh-fixture"},+ c.cookies.set(+ "ares-dev-refresh", "r" * 64, domain="localhost.local", path="/")++ response = await c.post("/auth/refresh")response_body = response.json()generic_failure = (response_body.get("code") == 401- and response_body.get("detail") == "Refresh token invalid or expired"+ and response_body.get("detail") == "Session is not valid"and response_body.get("type") == "api_error")- if not (- response.status_code == 401- and generic_failure- and db.rotate_refresh_session.await_count == 1- and db.create_refresh_token.await_count == 0- ):- pytest.fail(- "expected inactive refresh to fail generically without a successor",- pytrace=False,- )+ _require_fixed(response.status_code == 401, "inactive refresh status differed")+ _require_fixed(generic_failure, "inactive refresh detail differed")+ _require_fixed(+ db.rotate_refresh_session.await_count == 1,+ "inactive refresh lookup count differed",+ )+ _require_fixed(+ db.create_refresh_token.await_count == 0,+ "inactive refresh created successor",+ )if "inactive" in response.text.lower():pytest.fail("expected refresh authentication failure not to disclose account status",pytrace=False,)+ @pytest.mark.asyncio+ async def test_refresh_json_transport_is_rejected_before_database(self, aclient):+ c, db, _ = aclient+ _reset_rate_limiter()+ db.rotate_refresh_session.reset_mock()+ c.cookies.set(+ "ares-dev-csrf", "A" * 43, domain="localhost.local", path="/"+ )+ response = await c.post(+ "/auth/refresh",+ json={"refresh_token": "legacy-transport"},+ )+ _require_fixed(response.status_code == 400, "legacy refresh body was accepted")+ _require_fixed(db.rotate_refresh_session.await_count == 0, "legacy body reached database")++ @pytest.mark.asyncio+ async def test_refresh_backend_uncertainty_publishes_no_cookie(self, aclient):+ c, db, _ = aclient+ _reset_rate_limiter()+ c.cookies.set(+ "ares-dev-refresh", "r" * 64, domain="localhost.local", path="/"+ )+ db.rotate_refresh_session.side_effect = RuntimeError("fixed-test-canary")+ try:+ response = await c.post("/auth/refresh")+ reduced = (+ response.status_code == 503,+ not response.headers.get_list("set-cookie"),+ )+ _require_fixed(all(reduced), "Indeterminate refresh published browser state")+ finally:+ db.rotate_refresh_session.side_effect = None++ @pytest.mark.asyncio+ async def test_cookie_logout_commits_then_clears_exact_cookies(self, aclient):+ c, db, _ = aclient+ _reset_rate_limiter()+ c.cookies.set(+ "ares-dev-refresh", "r" * 64, domain="localhost.local", path="/"+ )+ db.revoke_refresh_cookie_session.reset_mock()+ response = await c.post("/auth/logout")+ cookie_headers = response.headers.get_list("set-cookie")+ reduced = (+ response.status_code == 204,+ response.content == b"",+ db.revoke_refresh_cookie_session.await_count == 1,+ len(cookie_headers) == 2,+ all("max-age=0" in value.lower() for value in cookie_headers),+ all("path=/" in value.lower() for value in cookie_headers),+ all("samesite=strict" in value.lower() for value in cookie_headers),+ all("domain=" not in value.lower() for value in cookie_headers),+ )+ del cookie_headers+ _require_fixed(all(reduced), "Cookie logout contract differed")+@pytest.mark.asyncioasync def test_real_sqlite_inactive_credentials_fail_at_api_boundary(self,@@ -595,10 +744,15 @@ class TestAuthFlow:"/campaigns",headers={"X-API-Key": raw_key},)- refresh_response = await c.post(- "/auth/refresh",- json={"refresh_token": refresh_token},+ c.cookies.set(+ "ares-dev-csrf", "A" * 43,+ domain="localhost.local", path="/",+ )+ c.cookies.set(+ "ares-dev-refresh", refresh_token,+ domain="localhost.local", path="/",)+ refresh_response = await c.post("/auth/refresh")api_body = api_response.json()refresh_body = refresh_response.json()@@ -611,8 +765,7 @@ class TestAuthFlow:)refresh_contract = (refresh_response.status_code == 401- and refresh_body.get("detail")- == "Refresh token invalid or expired"+ and refresh_body.get("detail") == "Session is not valid"and "inactive" not in refresh_response.text.lower()and "refresh_token" not in refresh_body)@@ -818,7 +971,6 @@ class TestAPIKeyScopeEnforcement:),("get", "/auth/api-keys", {}),("delete", "/auth/api-keys/api-key-1", {}),- ("post", "/auth/logout", {}),],)@pytest.mark.asyncio@@ -832,6 +984,20 @@ class TestAPIKeyScopeEnforcement:assert r.status_code == 401+ @pytest.mark.asyncio+ async def test_cookie_logout_does_not_use_or_revoke_api_key(self, aclient):+ c, db, _ = aclient+ db.verify_api_key.reset_mock()+ db.revoke_refresh_cookie_session.reset_mock()+ c.cookies.delete("ares-dev-refresh")+ response = await c.post("/auth/logout", headers=_api_key_headers())+ _require_fixed(response.status_code == 204, "cookie logout was not idempotent")+ _require_fixed(db.verify_api_key.await_count == 0, "cookie logout verified API key")+ _require_fixed(+ db.revoke_refresh_cookie_session.await_count == 0,+ "cookie logout revoked family",+ )+@pytest.mark.asyncioasync def test_jwt_auth_can_create_list_and_delete_api_keys(self, aclient):c, db, _ = aclientdiff --git a/tests/unit/test_browser_cookie_security.py b/tests/unit/test_browser_cookie_security.pynew file mode 100644index 0000000..a5d5094--- /dev/null+++ b/tests/unit/test_browser_cookie_security.py@@ -0,0 +1,1029 @@+"""Deterministic browser-cookie, Origin, and CSRF boundary tests."""+from __future__ import annotations++import base64+import io+import json+import threading+from contextlib import contextmanager, redirect_stderr, redirect_stdout+from datetime import datetime, timedelta, timezone+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from types import MappingProxyType, SimpleNamespace+from typing import Any+from urllib.parse import parse_qs++import httpx+import pytest+from starlette.applications import Starlette+from starlette.requests import Request+from starlette.responses import JSONResponse, Response+from starlette.routing import Route++from ares.core.browser_sessions import (+ DEVELOPMENT_CSRF_COOKIE,+ DEVELOPMENT_REFRESH_COOKIE,+ MAX_REFRESH_COOKIE_AGE_SECONDS,+ PRELOGIN_CSRF_LIFETIME_SECONDS,+ PRODUCTION_CSRF_COOKIE,+ PRODUCTION_REFRESH_COOKIE,+ BrowserRequestContext,+ BrowserSessionBoundaryMiddleware,+ BrowserSessionConfigurationError,+ build_browser_session_policy,+ canonical_noncredentialed_origins,+ clear_session_cookies,+ generate_csrf_token,+ is_canonical_csrf_token,+ is_canonical_refresh_token,+ publish_prelogin_csrf,+ publish_session_cookies,+ remaining_cookie_seconds,+)+from scripts.validation_lab import (+ ApiClient,+ ApiResult,+ ValidationLabError,+ _fail,+ build_parser,+ run_lab,+)+++def _settings(*, debug: bool, origin: str, trusted: tuple[str, ...]) -> SimpleNamespace:+ return SimpleNamespace(+ ares_debug=debug,+ ares_browser_origin=origin,+ trusted_hosts_list=list(trusted),+ )+++def _require(condition: bool, message: str) -> None:+ if not condition:+ pytest.fail(message, pytrace=False)+++def _cookie_flags(response: Response) -> list[dict[str, bool]]:+ rows: list[dict[str, bool]] = []+ for value in response.headers.getlist("set-cookie"):+ lowered = value.lower()+ rows.append(+ {+ "host_refresh": value.startswith(f"{PRODUCTION_REFRESH_COOKIE}="),+ "host_csrf": value.startswith(f"{PRODUCTION_CSRF_COOKIE}="),+ "dev_refresh": value.startswith(f"{DEVELOPMENT_REFRESH_COOKIE}="),+ "dev_csrf": value.startswith(f"{DEVELOPMENT_CSRF_COOKIE}="),+ "secure": "; secure" in lowered,+ "httponly": "; httponly" in lowered,+ "strict": "samesite=strict" in lowered,+ "root": "path=/" in lowered,+ "domain": "domain=" in lowered,+ "cleared": "max-age=0" in lowered,+ }+ )+ return rows+++def test_csrf_generation_is_canonical_and_unique() -> None:+ first = generate_csrf_token()+ second = generate_csrf_token()+ _require(is_canonical_csrf_token(first), "CSRF token was not canonical.")+ _require(is_canonical_csrf_token(second), "Second CSRF token was not canonical.")+ _require(first != second, "CSRF tokens were not independently generated.")+++ "value",+ ["", "a" * 42, "a" * 44, "a" * 42 + "=", "a" * 42 + "%"],+)+def test_csrf_rejects_noncanonical_values(value: str) -> None:+ _require(not is_canonical_csrf_token(value), "Malformed CSRF value was accepted.")+++def test_refresh_token_shape_is_exact() -> None:+ _require(is_canonical_refresh_token("a" * 64), "Canonical refresh shape rejected.")+ _require(not is_canonical_refresh_token("a" * 63), "Short refresh shape accepted.")+++def test_production_policy_is_host_only_secure() -> None:+ policy = build_browser_session_policy(+ _settings(debug=False, origin="https://ares.example", trusted=("ares.example",))+ )+ _require(policy.refresh_cookie_name == PRODUCTION_REFRESH_COOKIE, "Wrong refresh cookie name.")+ _require(policy.csrf_cookie_name == PRODUCTION_CSRF_COOKIE, "Wrong CSRF cookie name.")+ _require(policy.secure, "Production cookie policy was not secure.")+++ "origin",+ [+ "",+ "http://ares.example",+ "https://ares.example/unsafe",+ "https://ares.example.",+ "null",+ "https://[email protected]",+ "https://ares.example,https://other.example",+ ],+)+def test_production_policy_rejects_invalid_origins(origin: str) -> None:+ with pytest.raises(BrowserSessionConfigurationError, match="configuration invalid"):+ build_browser_session_policy(+ _settings(debug=False, origin=origin, trusted=("ares.example",))+ )+++ ("origin", "host"),+ [("http://localhost:5173", "localhost"), ("http://127.0.0.1:5173", "127.0.0.1")],+)+def test_debug_policy_accepts_only_fixed_loopback(origin: str, host: str) -> None:+ policy = build_browser_session_policy(+ _settings(debug=True, origin=origin, trusted=(host,))+ )+ _require(not policy.secure, "Debug policy unexpectedly required Secure.")+ _require(policy.refresh_cookie_name == DEVELOPMENT_REFRESH_COOKIE, "Wrong debug refresh name.")+++def test_debug_policy_rejects_nonloopback_host() -> None:+ with pytest.raises(BrowserSessionConfigurationError, match="configuration invalid"):+ build_browser_session_policy(+ _settings(debug=True, origin="http://localhost:5173", trusted=("example.test",))+ )+++def test_noncredentialed_cors_origins_are_exact() -> None:+ values = canonical_noncredentialed_origins(+ ["http://localhost:3000", "https://integration.example"]+ )+ _require(len(values) == 2, "Exact CORS origins were not retained.")++[email protected]("origin", ["*", "null", "https://example.test/path", "https://example.test,"])+def test_noncredentialed_cors_rejects_unsafe_values(origin: str) -> None:+ with pytest.raises(BrowserSessionConfigurationError, match="configuration invalid"):+ canonical_noncredentialed_origins([origin])+++def test_remaining_cookie_lifetime_is_clamped() -> None:+ now = datetime.now(timezone.utc)+ long_lived = remaining_cookie_seconds(now + timedelta(days=60), now=now)+ expired = remaining_cookie_seconds(now - timedelta(seconds=1), now=now)+ _require(long_lived == MAX_REFRESH_COOKIE_AGE_SECONDS, "Cookie lifetime was not clamped.")+ _require(expired == 0, "Expired family produced a cookie lifetime.")+++def test_prelogin_cookie_has_fixed_lifetime_and_no_refresh_cookie() -> None:+ policy = build_browser_session_policy(+ _settings(debug=False, origin="https://ares.example", trusted=("ares.example",))+ )+ response = Response()+ publish_prelogin_csrf(response, policy)+ flags = _cookie_flags(response)+ header = response.headers.getlist("set-cookie")[0].lower()+ _require(len(flags) == 1 and flags[0]["host_csrf"], "Prelogin CSRF cookie missing.")+ _require(not flags[0]["httponly"], "CSRF cookie was not browser-readable.")+ _require(f"max-age={PRELOGIN_CSRF_LIFETIME_SECONDS}" in header, "Wrong prelogin lifetime.")+++def test_production_session_cookie_attributes_are_exact() -> None:+ policy = build_browser_session_policy(+ _settings(debug=False, origin="https://ares.example", trusted=("ares.example",))+ )+ response = Response()+ published = publish_session_cookies(+ response,+ policy,+ refresh_token="a" * 64,+ absolute_expiry=datetime.now(timezone.utc) + timedelta(days=30),+ )+ flags = _cookie_flags(response)+ _require(published and len(flags) == 2, "Session cookies were not both published.")+ secure = all(row["secure"] and row["strict"] and row["root"] for row in flags)+ _require(secure, "Cookie security attributes differ.")+ _require(all(not row["domain"] for row in flags), "A Domain attribute was emitted.")+ _require(sum(row["httponly"] for row in flags) == 1, "HttpOnly boundary is incorrect.")+++def test_expired_family_publishes_no_cookie() -> None:+ policy = build_browser_session_policy(+ _settings(debug=False, origin="https://ares.example", trusted=("ares.example",))+ )+ response = Response()+ published = publish_session_cookies(+ response,+ policy,+ refresh_token="a" * 64,+ absolute_expiry=datetime.now(timezone.utc) - timedelta(seconds=1),+ )+ absent = not published and not response.headers.getlist("set-cookie")+ _require(absent, "Expired cookie was published.")++[email protected]("debug", [False, True])+def test_cookie_clearing_matches_creation_policy(debug: bool) -> None:+ origin = "http://localhost:5173" if debug else "https://ares.example"+ host = "localhost" if debug else "ares.example"+ policy = build_browser_session_policy(+ _settings(debug=debug, origin=origin, trusted=(host,))+ )+ response = Response()+ clear_session_cookies(response, policy)+ flags = _cookie_flags(response)+ _require(len(flags) == 2 and all(row["cleared"] for row in flags), "Cookies were not cleared.")+ _require(all(row["secure"] is (not debug) for row in flags), "Clear security flag differed.")+++def _boundary_app() -> Starlette:+ async def _endpoint(request: Request) -> JSONResponse:+ context = getattr(request.state, "browser_session", None)+ safe = (+ isinstance(context, BrowserRequestContext)+ and request.scope.get("query_string") == b""+ and not any(key.lower() == b"cookie" for key, _ in request.scope["headers"])+ and not any(key.lower() == b"origin" for key, _ in request.scope["headers"])+ )+ return JSONResponse({"safe": safe})++ app = Starlette(+ routes=[+ Route("/auth/csrf", _endpoint, methods=["GET"]),+ Route("/auth/token", _endpoint, methods=["POST"]),+ Route("/auth/refresh", _endpoint, methods=["POST"]),+ Route("/auth/logout", _endpoint, methods=["POST"]),+ Route("/auth/logout-all", _endpoint, methods=["POST"]),+ ]+ )+ settings = _settings(+ debug=True,+ origin="http://localhost:5173",+ trusted=("localhost", "127.0.0.1"),+ )+ app.add_middleware(+ BrowserSessionBoundaryMiddleware,+ settings_provider=lambda: settings,+ )+ return app+++def _boundary_headers() -> dict[str, str]:+ return {+ "Origin": "http://localhost:5173",+ "Sec-Fetch-Site": "same-origin",+ "X-ARES-CSRF": "A" * 43,+ "Cookie": f"ares-dev-csrf={'A' * 43}; ares-dev-refresh={'r' * 64}",+ }+++async def test_boundary_scrubs_query_cookie_and_origin_before_handler() -> None:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_boundary_app()),+ base_url="http://localhost:5173",+ ) as client:+ response = await client.post("/auth/refresh", headers=_boundary_headers())+ _require(response.status_code == 200, "Canonical boundary request failed.")+ _require(response.json().get("safe") is True, "Sensitive scope was not scrubbed.")+++async def test_uvicorn_access_logging_receives_only_scrubbed_auth_scope() -> None:+ import asyncio+ from unittest.mock import AsyncMock, MagicMock++ import h11+ from uvicorn.protocols.http.h11_impl import RequestResponseCycle++ marker = "Z" * 43+ scope = {+ "type": "http",+ "asgi": {"version": "3.0", "spec_version": "2.3"},+ "http_version": "1.1",+ "server": ("localhost", 5173),+ "client": ("127.0.0.1", 41000),+ "scheme": "http",+ "method": "GET",+ "root_path": "",+ "path": "/auth/csrf",+ "raw_path": b"/auth/csrf",+ "query_string": f"legacy={marker}".encode("ascii"),+ "headers": (+ (b"host", b"localhost:5173"),+ (b"cookie", f"unrelated={marker}".encode("ascii")),+ ),+ "state": {},+ }+ received = False++ async def _receive() -> dict[str, object]:+ nonlocal received+ if received:+ return {"type": "http.disconnect"}+ received = True+ return {"type": "http.request", "body": b"", "more_body": False}++ sent: list[dict[str, object]] = []++ async def _send(message: dict[str, object]) -> None:+ sent.append(message)++ await BrowserSessionBoundaryMiddleware(+ _boundary_app(),+ settings_provider=lambda: _settings(+ debug=True,+ origin="http://localhost:5173",+ trusted=("localhost", "127.0.0.1"),+ ),+ )(scope, _receive, _send)++ access_logger = MagicMock()+ flow = MagicMock(write_paused=False)+ flow.drain = AsyncMock()+ transport = MagicMock()+ cycle = RequestResponseCycle(+ scope=scope,+ conn=h11.Connection(h11.SERVER),+ transport=transport,+ flow=flow,+ logger=MagicMock(),+ access_logger=access_logger,+ access_log=True,+ default_headers=[],+ message_event=asyncio.Event(),+ on_response=MagicMock(),+ )+ await cycle.send({"type": "http.response.start", "status": 400, "headers": []})+ logged = access_logger.info.call_args.args+ reduced = (+ bool(sent),+ scope["query_string"] == b"",+ not any(key.lower() == b"cookie" for key, _ in scope["headers"]),+ marker not in "".join(str(value) for value in logged),+ )+ del logged, marker+ _require(all(reduced), "Uvicorn observed unsanitized browser-auth scope.")+++ "path",+ ["/auth/token", "/auth/refresh", "/auth/logout", "/auth/logout-all"],+)+async def test_boundary_rejects_missing_origin(path: str) -> None:+ headers = _boundary_headers()+ del headers["Origin"]+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_boundary_app()),+ base_url="http://localhost:5173",+ ) as client:+ response = await client.post(path, headers=headers)+ _require(response.status_code == 403, "Missing Origin was accepted.")+++async def test_csrf_bootstrap_allows_missing_origin_on_same_host() -> None:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_boundary_app()),+ base_url="http://localhost:5173",+ ) as client:+ response = await client.get("/auth/csrf")+ _require(response.status_code == 200, "Same-origin CSRF bootstrap was rejected.")+++ "mutation",+ [+ "untrusted-origin",+ "null-origin",+ "host-mismatch",+ "cross-site",+ "missing-csrf",+ "mismatched-csrf",+ ],+)+async def test_boundary_rejects_invalid_origin_host_and_csrf(mutation: str) -> None:+ headers = _boundary_headers()+ base_url = "http://localhost:5173"+ if mutation == "untrusted-origin":+ headers["Origin"] = "https://untrusted.example"+ elif mutation == "null-origin":+ headers["Origin"] = "null"+ elif mutation == "host-mismatch":+ base_url = "http://127.0.0.1:5173"+ elif mutation == "cross-site":+ headers["Sec-Fetch-Site"] = "cross-site"+ elif mutation == "missing-csrf":+ del headers["X-ARES-CSRF"]+ else:+ headers["X-ARES-CSRF"] = "B" * 43+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_boundary_app()),+ base_url=base_url,+ ) as client:+ response = await client.post("/auth/refresh", headers=headers)+ _require(response.status_code == 403, "Invalid browser boundary was accepted.")++[email protected]("transport", ["query", "body", "header", "authorization"])+async def test_refresh_rejects_every_legacy_transport(transport: str) -> None:+ headers = _boundary_headers()+ path = "/auth/refresh"+ content: bytes | None = None+ if transport == "query":+ path += "?refresh_token=legacy"+ elif transport == "body":+ content = b"{}"+ elif transport == "header":+ headers["X-Refresh-Token"] = "legacy"+ else:+ headers["Authorization"] = "Bearer legacy"+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_boundary_app()),+ base_url="http://localhost:5173",+ ) as client:+ response = await client.post(path, headers=headers, content=content)+ _require(response.status_code == 400, "Legacy refresh transport was accepted.")+++async def test_boundary_rejects_duplicate_canonical_cookie() -> None:+ headers = _boundary_headers()+ headers["Cookie"] += f"; ares-dev-refresh={'s' * 64}"+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_boundary_app()),+ base_url="http://localhost:5173",+ ) as client:+ response = await client.post("/auth/refresh", headers=headers)+ _require(response.status_code == 403, "Duplicate refresh cookie was accepted.")+++async def test_boundary_rejects_duplicate_origin_header() -> None:+ pairs = list(_boundary_headers().items())+ pairs.append(("Origin", "http://localhost:5173"))+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=_boundary_app()),+ base_url="http://localhost:5173",+ ) as client:+ response = await client.post("/auth/refresh", headers=pairs)+ _require(response.status_code == 403, "Duplicate Origin was accepted.")+++_LAB_CSRF_INITIAL = "A" * 43+_LAB_CSRF_ROTATED = base64.urlsafe_b64encode(bytes([1]) * 32).rstrip(b"=").decode("ascii")+_LAB_REFRESH = "r" * 64+_LAB_ACCESS = "t" * 64+++@contextmanager+def _validation_lab_server(mode: str = "normal") -> Any:+ state: dict[str, Any] = {"events": [], "checks": []}++ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, format_string: str, *args: object) -> None:+ del format_string, args++ def _empty(self, status: int, cookies: tuple[str, ...] = ()) -> None:+ self.send_response(status)+ for cookie in cookies:+ self.send_header("Set-Cookie", cookie)+ self.send_header("Content-Length", "0")+ self.end_headers()++ def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler contract+ path_ok = self.path == "/auth/csrf"+ origin_ok = self.headers.get_all("Origin", failobj=[]) == [+ "http://127.0.0.1:5173"+ ]+ state["events"].append("csrf")+ state["checks"].append(path_ok and origin_ok)+ if mode == "redirect":+ self.send_response(302)+ self.send_header("Location", "/auth/token")+ self.send_header("Content-Length", "0")+ self.end_headers()+ return+ if mode == "missing":+ self._empty(204)+ return+ if mode == "malformed":+ self._empty(204, ("ares-dev-csrf=short; Path=/; SameSite=Strict",))+ return+ if mode == "duplicate":+ self._empty(+ 204,+ (+ f"ares-dev-csrf={_LAB_CSRF_INITIAL}; Path=/; SameSite=Strict",+ f"ares-dev-csrf={_LAB_CSRF_ROTATED}; Path=/auth; SameSite=Strict",+ ),+ )+ return+ self._empty(+ 204,+ (f"ares-dev-csrf={_LAB_CSRF_INITIAL}; Path=/; SameSite=Strict",),+ )++ def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler contract+ length = int(self.headers.get("Content-Length", "0"))+ body = self.rfile.read(length)+ origin_ok = self.headers.get_all("Origin", failobj=[]) == [+ "http://127.0.0.1:5173"+ ]+ csrf_values = self.headers.get_all("X-ARES-CSRF", failobj=[])+ cookie_values = self.headers.get_all("Cookie", failobj=[])+ auth_values = self.headers.get_all("Authorization", failobj=[])+ forbidden_refresh_header = any(+ self.headers.get_all(name, failobj=[])+ for name in ("Refresh-Token", "X-Refresh-Token", "X-ARES-Refresh-Token")+ )+ if self.path == "/auth/token":+ form = parse_qs(body.decode("ascii"), strict_parsing=True)+ form_ok = set(form) == {"username", "password"} and all(+ len(values) == 1 for values in form.values()+ )+ checks = (+ origin_ok,+ csrf_values == [_LAB_CSRF_INITIAL],+ len(cookie_values) == 1+ and _LAB_CSRF_INITIAL in cookie_values[0],+ not auth_values,+ not forbidden_refresh_header,+ form_ok,+ "?" not in self.path,+ )+ state["events"].append("login")+ state["checks"].extend(checks)+ payload = {+ "access_token": _LAB_ACCESS,+ "token_type": "bearer",+ "refresh_generation": 0,+ "session_coordination_key": "c" * 43,+ }+ encoded = json.dumps(payload).encode("ascii")+ self.send_response(200)+ self.send_header(+ "Set-Cookie",+ f"ares-dev-refresh={_LAB_REFRESH}; Path=/; HttpOnly; SameSite=Strict",+ )+ self.send_header(+ "Set-Cookie",+ f"ares-dev-csrf={_LAB_CSRF_ROTATED}; Path=/; SameSite=Strict",+ )+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(encoded)))+ self.end_headers()+ self.wfile.write(encoded)+ elif self.path == "/auth/logout":+ checks = (+ origin_ok,+ csrf_values == [_LAB_CSRF_ROTATED],+ len(cookie_values) == 1+ and _LAB_CSRF_ROTATED in cookie_values[0]+ and _LAB_REFRESH in cookie_values[0],+ not auth_values,+ not forbidden_refresh_header,+ body == b"",+ "?" not in self.path,+ )+ state["events"].append("logout")+ state["checks"].extend(checks)+ self._empty(204)+ else:+ state["events"].append("unexpected")+ self._empty(404)+ del body, cookie_values, csrf_values, auth_values++ try:+ server = ThreadingHTTPServer(("127.0.0.1", 5173), Handler)+ except OSError:+ pytest.fail("Validation-lab loopback listener was unavailable.", pytrace=False)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield state+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+ state["settled"] = not thread.is_alive()+++def test_validation_lab_client_uses_csrf_cookie_rotation_and_logout() -> None:+ with _validation_lab_server() as state:+ client = ApiClient(+ "http://127.0.0.1:5173",+ "http://127.0.0.1:5173",+ )+ client.login("canary-user", "canary-password")+ access_in_memory = client.access_token == _LAB_ACCESS+ client.logout()+ cleared = client.access_token is None+ reduced = (+ state["events"] == ["csrf", "login", "logout"],+ all(state["checks"]),+ access_in_memory,+ cleared,+ state["settled"],+ )+ _require(all(reduced), "Validation-lab browser session sequence differed.")++[email protected]("mode", ["missing", "duplicate", "malformed"])+def test_validation_lab_rejects_invalid_csrf_cookie_sets(mode: str) -> None:+ with _validation_lab_server(mode):+ client = ApiClient(+ "http://127.0.0.1:5173",+ "http://127.0.0.1:5173",+ )+ with pytest.raises(ValidationLabError, match="csrf-cookie-invalid"):+ client.bootstrap_csrf()+++def test_validation_lab_authentication_redirect_fails_closed() -> None:+ with _validation_lab_server("redirect") as state:+ client = ApiClient(+ "http://127.0.0.1:5173",+ "http://127.0.0.1:5173",+ )+ with pytest.raises(ValidationLabError, match="request-status:status-302"):+ client.bootstrap_csrf()+ _require(state["events"] == ["csrf"], "Authentication redirect was followed.")+ _require(state["settled"], "Redirect test server did not settle.")+++ ("base_url", "origin", "allow_remote"),+ [+ ("http://127.0.0.1:5173", "http://localhost:5173", False),+ ("http://example.test", "http://example.test", True),+ ("https://example.test/path", "https://example.test/path", True),+ ("https://[email protected]", "https://[email protected]", True),+ ("https://example.test.", "https://example.test.", True),+ ],+)+def test_validation_lab_rejects_unsafe_or_mismatched_origins(+ base_url: str, origin: str, allow_remote: bool+) -> None:+ with pytest.raises(ValidationLabError):+ ApiClient(base_url, origin, allow_remote=allow_remote)+++def test_validation_lab_parser_has_no_password_argument() -> None:+ parser = build_parser()+ destinations = {action.dest for action in parser._actions}+ _require("password" not in destinations, "Password CLI argument still exists.")+ parsed = parser.parse_args(+ [+ "--base-url",+ "http://127.0.0.1:5173",+ "--browser-origin",+ "http://127.0.0.1:5173",+ ]+ )+ _require(parsed.browser_origin is not None, "Explicit browser origin was lost.")+++def test_validation_lab_diagnostics_and_repr_hide_canaries() -> None:+ canaries = ("canary-password", "canary-access", "canary-csrf")+ result = ApiResult(200, {"access_token": canaries[1]})+ failure = ValidationLabError("request-unavailable")+ stdout = io.StringIO()+ stderr = io.StringIO()+ with redirect_stdout(stdout), redirect_stderr(stderr):+ _fail("fixed-operation", RuntimeError(canaries[0]))+ _fail("fixed-operation", failure)+ rendered = repr(result) + repr(failure) + stdout.getvalue() + stderr.getvalue()+ safe = all(canary not in rendered for canary in canaries)+ del rendered, stdout, stderr, result, failure, canaries+ _require(safe, "Validation-lab diagnostics exposed a canary.")+++_LAB_BLOCKED_DRY_RUN_CONTRACT = MappingProxyType(+ {+ "dry_run": True,+ "status": "dry_run_blocked",+ "would_execute": False,+ "missing_params": ("canary-required-field",),+ }+)+++def _module_payload_for_case(case: str) -> tuple[int, object]:+ payload: object = {+ "dry_run": _LAB_BLOCKED_DRY_RUN_CONTRACT["dry_run"],+ "status": _LAB_BLOCKED_DRY_RUN_CONTRACT["status"],+ "would_execute": _LAB_BLOCKED_DRY_RUN_CONTRACT["would_execute"],+ "missing_params": list(_LAB_BLOCKED_DRY_RUN_CONTRACT["missing_params"]),+ "warnings": ["canary-warning"],+ "operator_next_steps": ["canary-next-step"],+ }+ if case == "canonical":+ return 200, payload+ if case == "status-422":+ return 422, payload+ if case == "non-object":+ return 200, [payload]+ if not isinstance(payload, dict):+ pytest.fail("Validation-lab mutation setup was invalid.", pytrace=False)+ if case == "dry-run-missing":+ payload.pop("dry_run")+ elif case == "dry-run-false":+ payload["dry_run"] = False+ elif case == "status-wrong":+ payload["status"] = "dry_run_ok"+ elif case == "would-execute":+ payload["would_execute"] = True+ elif case == "missing-empty":+ payload["missing_params"] = []+ elif case == "missing-malformed":+ payload["missing_params"] = "canary-required-field"+ elif case == "execution-result":+ payload["execution_result"] = {"state": "canary-success"}+ elif case == "success-publication":+ payload["success"] = True+ elif case == "credential-publication":+ payload["credentials"] = ["canary-credential"]+ elif case == "finding-publication":+ payload["findings"] = ["canary-finding"]+ elif case == "artifact-publication":+ payload["artifacts"] = ["canary-artifact"]+ else:+ pytest.fail("Validation-lab mutation case was unknown.", pytrace=False)+ return 200, payload+++@contextmanager+def _full_validation_lab_server(module_case: str) -> Any:+ module_status, module_payload = _module_payload_for_case(module_case)+ state: dict[str, Any] = {+ "events": [],+ "checks": [],+ "campaign_active": False,+ "api_key_active": False,+ }++ class Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def log_message(self, format_string: str, *args: object) -> None:+ del format_string, args++ def _json(self, status: int, payload: object) -> None:+ encoded = json.dumps(payload).encode("ascii")+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(encoded)))+ self.end_headers()+ self.wfile.write(encoded)++ def _empty(self, status: int, cookies: tuple[str, ...] = ()) -> None:+ self.send_response(status)+ for cookie in cookies:+ self.send_header("Set-Cookie", cookie)+ self.send_header("Content-Length", "0")+ self.end_headers()++ def _body(self) -> bytes:+ return self.rfile.read(int(self.headers.get("Content-Length", "0")))++ def do_GET(self) -> None: # noqa: N802 - BaseHTTPRequestHandler contract+ if self.path == "/auth/csrf":+ state["events"].append("csrf")+ state["checks"].append(+ self.headers.get_all("Origin", failobj=[])+ == ["http://127.0.0.1:5173"]+ )+ self._empty(+ 204,+ (f"ares-dev-csrf={_LAB_CSRF_INITIAL}; Path=/; SameSite=Strict",),+ )+ elif self.path == "/health":+ state["events"].append("health")+ self._json(200, {"status": "ok"})+ elif self.path == "/auth/me":+ state["events"].append("profile")+ self._json(200, {"role": "admin"})+ elif self.path == "/campaigns":+ state["events"].append("campaign-list")+ rows = [{"id": "fixed-campaign"}] if state["campaign_active"] else []+ self._json(200, rows)+ elif self.path == "/reports/fixed-campaign":+ state["events"].append("report-list")+ self._json(200, [])+ elif self.path == "/auth/api-keys":+ state["events"].append("api-key-list")+ rows = [{"id": "fixed-key"}] if state["api_key_active"] else []+ self._json(200, rows)+ else:+ self._empty(404)++ def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler contract+ body = self._body()+ if self.path == "/auth/token":+ form = parse_qs(body.decode("ascii"), strict_parsing=True)+ state["events"].append("login")+ state["checks"].extend(+ (+ set(form) == {"username", "password"},+ self.headers.get_all("Origin", failobj=[])+ == ["http://127.0.0.1:5173"],+ self.headers.get_all("X-ARES-CSRF", failobj=[])+ == [_LAB_CSRF_INITIAL],+ )+ )+ payload = {+ "access_token": _LAB_ACCESS,+ "token_type": "bearer",+ "refresh_generation": 0,+ "session_coordination_key": "c" * 43,+ }+ encoded = json.dumps(payload).encode("ascii")+ self.send_response(200)+ self.send_header(+ "Set-Cookie",+ f"ares-dev-refresh={_LAB_REFRESH}; Path=/; HttpOnly; SameSite=Strict",+ )+ self.send_header(+ "Set-Cookie",+ f"ares-dev-csrf={_LAB_CSRF_ROTATED}; Path=/; SameSite=Strict",+ )+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(encoded)))+ self.end_headers()+ self.wfile.write(encoded)+ elif self.path == "/auth/logout":+ state["events"].append("logout")+ state["checks"].extend(+ (+ body == b"",+ self.headers.get_all("Origin", failobj=[])+ == ["http://127.0.0.1:5173"],+ self.headers.get_all("X-ARES-CSRF", failobj=[])+ == [_LAB_CSRF_ROTATED],+ )+ )+ self._empty(204)+ elif self.path == "/campaigns":+ request_body = json.loads(body)+ if request_body.get("targets") == ["../not-a-target"]:+ state["events"].append("campaign-rejected")+ self._json(422, {})+ else:+ state["events"].append("campaign-create")+ state["campaign_active"] = True+ self._json(200, {"id": "fixed-campaign"})+ elif self.path == "/campaigns/fixed-campaign/run":+ state["events"].append("plan-dry-run")+ self._json(200, {"param_validation": {"ok": False}})+ elif self.path == "/modules/ad.kerberoast/run":+ request_body = json.loads(body)+ state["events"].append("module-dry-run")+ state["module_request"] = {+ "exact_keys": set(request_body)+ == {"campaign_id", "params", "dry_run"},+ "campaign_present": isinstance(request_body.get("campaign_id"), str),+ "params_empty": request_body.get("params") == {},+ "dry_run_true": request_body.get("dry_run") is True,+ "query_empty": "?" not in self.path,+ }+ self._json(module_status, module_payload)+ elif self.path == "/reports/fixed-campaign?fmt=html":+ state["events"].append("report-create")+ self._json(200, {"filename": "fixed.html"})+ elif self.path == "/auth/api-keys":+ state["events"].append("api-key-create")+ state["api_key_active"] = True+ self._json(200, {"id": "fixed-key"})+ else:+ self._empty(404)+ del body++ def do_DELETE(self) -> None: # noqa: N802 - BaseHTTPRequestHandler contract+ if self.path == "/auth/api-keys/fixed-key":+ state["events"].append("api-key-delete")+ state["api_key_active"] = False+ self._json(200, {})+ elif self.path == "/campaigns/fixed-campaign":+ state["events"].append("campaign-delete")+ state["campaign_active"] = False+ self._json(200, {})+ else:+ self._empty(404)++ try:+ server = ThreadingHTTPServer(("127.0.0.1", 5173), Handler)+ except OSError:+ pytest.fail("Full validation-lab listener was unavailable.", pytrace=False)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield state+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=2)+ state["settled"] = not thread.is_alive()+++def _run_full_validation_lab(monkeypatch: pytest.MonkeyPatch, module_case: str) -> dict[str, Any]:+ monkeypatch.setenv("ARES_LAB_PASSWORD", "canary-password")+ stdout = io.StringIO()+ stderr = io.StringIO()+ with _full_validation_lab_server(module_case) as state:+ with redirect_stdout(stdout), redirect_stderr(stderr):+ exit_code = run_lab(+ SimpleNamespace(+ base_url="http://127.0.0.1:5173",+ browser_origin="http://127.0.0.1:5173",+ username="canary-user",+ allow_remote=False,+ )+ )+ rendered = stdout.getvalue() + stderr.getvalue()+ canaries = (+ "canary-password",+ "canary-required-field",+ "canary-warning",+ "canary-next-step",+ "canary-success",+ "canary-credential",+ "canary-finding",+ "canary-artifact",+ )+ reduced = {+ "exit_code": exit_code,+ "success_label": "[OK] dry-run blocked missing parameters" in rendered,+ "fixed_failure_label": (+ "[FAIL] dry-run blocked missing parameters - " in rendered+ ),+ "sensitive_output": any(canary in rendered for canary in canaries),+ "all_checks": all(state["checks"]),+ "module_request": state.get("module_request"),+ "continued_after_module": (+ "module-dry-run" in state["events"]+ and "report-create" in state["events"]+ and "api-key-create" in state["events"]+ and "campaign-delete" in state["events"]+ ),+ "logout": state["events"][-1:] == ["logout"],+ "settled": state["settled"],+ "ok_actions": rendered.count("[OK] "),+ }+ del rendered, stdout, stderr, canaries, state+ return reduced+++def test_validation_lab_accepts_canonical_blocked_module_dry_run(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ result = _run_full_validation_lab(monkeypatch, "canonical")+ request_contract = result["module_request"]+ _require(result["exit_code"] == 0, "Canonical validation lab did not pass.")+ _require(result["success_label"], "Blocked dry-run success label was absent.")+ _require(not result["fixed_failure_label"], "Canonical dry-run was rejected.")+ _require(not result["sensitive_output"], "Dry-run output exposed a canary.")+ _require(result["all_checks"], "Validation-lab request contract differed.")+ _require(+ isinstance(request_contract, dict) and all(request_contract.values()),+ "Module dry-run request contract differed.",+ )+ _require(result["continued_after_module"], "Lab stopped after module dry-run.")+ _require(result["logout"], "Lab logout cleanup did not run.")+ _require(result["settled"], "Full validation-lab server did not settle.")+ _require(result["ok_actions"] == 17, "Validation-lab action count differed.")+++ "module_case",+ [+ "status-422",+ "dry-run-missing",+ "dry-run-false",+ "status-wrong",+ "would-execute",+ "missing-empty",+ "missing-malformed",+ "non-object",+ "execution-result",+ "success-publication",+ "credential-publication",+ "finding-publication",+ "artifact-publication",+ ],+)+def test_validation_lab_rejects_noncanonical_blocked_module_dry_run(+ monkeypatch: pytest.MonkeyPatch,+ module_case: str,+) -> None:+ result = _run_full_validation_lab(monkeypatch, module_case)+ _require(result["exit_code"] == 1, "Unsafe module response was accepted.")+ _require(not result["success_label"], "Unsafe module response reported success.")+ _require(result["fixed_failure_label"], "Fixed module failure label was absent.")+ _require(not result["sensitive_output"], "Module failure output exposed a canary.")+ _require(result["all_checks"], "Validation-lab request contract differed.")+ _require(result["continued_after_module"], "Lab stopped after rejected module result.")+ _require(result["logout"], "Rejected module result bypassed logout cleanup.")+ _require(result["settled"], "Rejected module test server did not settle.")diff --git a/tests/unit/test_refresh_token_families.py b/tests/unit/test_refresh_token_families.pyindex 915125f..876cba0 100644--- a/tests/unit/test_refresh_token_families.py+++ b/tests/unit/test_refresh_token_families.py@@ -187,3 +187,75 @@ async def test_sqlite_logout_all_increments_epoch_and_is_read_only_afterward()finally:await database.close()+++async def test_sqlite_issued_session_exposes_authoritative_absolute_expiry(tmp_path) -> None:+ database = AresDatabase(str(tmp_path / "cookie-expiry.db"))+ await database.connect()+ try:+ await database.create_user("cookie-user", "CookiePassword1!", "operator")+ issued = await database.create_login_session(+ "cookie-user", "CookiePassword1!", _access_factory+ )+ now = datetime.now(timezone.utc)+ _require(+ issued.session is not None+ and issued.session.absolute_expires_at.tzinfo is not None+ and issued.session.absolute_expires_at > now,+ "issued session did not expose authoritative family expiry",+ )+ finally:+ await database.close()+++async def test_sqlite_cookie_logout_revokes_active_family_and_is_idempotent(tmp_path) -> None:+ database = AresDatabase(str(tmp_path / "cookie-logout.db"))+ await database.connect()+ try:+ await database.create_user("logout-user", "LogoutPassword1!", "operator")+ issued = await database.create_login_session(+ "logout-user", "LogoutPassword1!", _access_factory+ )+ _require(issued.session is not None, "login session missing")+ raw = issued.session.refresh_token+ revoked = await database.revoke_refresh_cookie_session(raw)+ repeated = await database.revoke_refresh_cookie_session(raw)+ rotation = await database.rotate_refresh_session(raw, _access_factory)+ _require(+ revoked.status is SessionRevocationStatus.REVOKED+ and repeated.status is SessionRevocationStatus.ALREADY_REVOKED+ and rotation.status is not RefreshRotationStatus.ROTATED,+ "cookie logout did not revoke exactly one family",+ )+ finally:+ await database.close()+++async def test_sqlite_consumed_cookie_logout_triggers_replay_revocation(tmp_path) -> None:+ database = AresDatabase(str(tmp_path / "cookie-replay.db"))+ await database.connect()+ try:+ await database.create_user("replay-user", "ReplayPassword1!", "operator")+ issued = await database.create_login_session(+ "replay-user", "ReplayPassword1!", _access_factory+ )+ _require(issued.session is not None, "login session missing")+ predecessor = issued.session.refresh_token+ rotated = await database.rotate_refresh_session(predecessor, _access_factory)+ _require(rotated.session is not None, "rotation successor missing")+ replay_logout = await database.revoke_refresh_cookie_session(predecessor)+ successor = await database.rotate_refresh_session(+ rotated.session.refresh_token, _access_factory+ )+ unknown = await database.revoke_refresh_cookie_session("u" * 64)+ _require(+ replay_logout.status is SessionRevocationStatus.REVOKED+ and successor.status is not RefreshRotationStatus.ROTATED+ and unknown.status is SessionRevocationStatus.INVALID,+ "consumed-cookie logout did not preserve replay authority",+ )+ finally:+ await database.close()diff --git a/tests/unit/test_security_critical.py b/tests/unit/test_security_critical.pyindex 30630f7..0cf108b 100644--- a/tests/unit/test_security_critical.py+++ b/tests/unit/test_security_critical.py@@ -26,6 +26,8 @@ import pytestos.environ.setdefault("ARES_SECRET_KEY", "test-sec-critical-min32-chars!!!!")os.environ.setdefault("ARES_ENCRYPTION_KEY", "test-enc-critical-min32-chars!!!!")os.environ.setdefault("ARES_DEFAULT_ADMIN_PASSWORD", "TestCriticalPass1!")+os.environ.setdefault("ARES_DEBUG", "true")+os.environ.setdefault("ARES_BROWSER_ORIGIN", "http://localhost:5173")# ── helpers ───────────────────────────────────────────────────────────────────@@ -81,6 +83,9 @@ def _make_mock_db():db.revoke_current_session = AsyncMock(return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED))+ db.revoke_refresh_cookie_session = AsyncMock(+ return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED)+ )db.revoke_all_sessions = AsyncMock(return_value=SessionRevocationResult(SessionRevocationStatus.REVOKED))@@ -122,6 +127,46 @@ def _reset_limiter() -> None:_limiter._windows.clear()+def _browser_client(app):+ import httpx++ client: httpx.AsyncClient++ async def _headers(request: httpx.Request) -> None:+ if request.url.path in {+ "/auth/token",+ "/auth/refresh",+ "/auth/logout",+ "/auth/logout-all",+ }:+ request.headers["Origin"] = "http://localhost:5173"+ request.headers["Sec-Fetch-Site"] = "same-origin"+ try:+ csrf = client.cookies.get("ares-dev-csrf")+ except httpx.CookieConflict:+ csrf = None+ csrf = csrf or ("A" * 43)+ request.headers["X-ARES-CSRF"] = csrf+ cookie = request.headers.get("Cookie", "")+ if "ares-dev-csrf=" not in cookie:+ request.headers["Cookie"] = (+ f"{cookie}; ares-dev-csrf={csrf}" if cookie else f"ares-dev-csrf={csrf}"+ )++ client = httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://localhost:5173",+ event_hooks={"request": [_headers]},+ )+ client.cookies.set(+ "ares-dev-csrf", "A" * 43, domain="localhost.local", path="/"+ )+ client.cookies.set(+ "ares-dev-refresh", "r" * 64, domain="localhost.local", path="/"+ )+ return client++def _run(coro):return asyncio.run(coro)@@ -240,15 +285,11 @@ class TestTokenRevocation:_reset_limiter()def _client(self, mock_db):- import httpxfrom ares.api.server import app, get_db, get_settingsapp.state.db = mock_dbapp.dependency_overrides[get_db] = lambda: mock_dbapp.dependency_overrides[get_settings] = lambda: _settings()- return httpx.AsyncClient(- transport=httpx.ASGITransport(app=app),- base_url="http://localhost",- )+ return _browser_client(app)def test_revoked_token_rejected(self):"""Token whose JTI is in the blacklist must return 401."""@@ -294,8 +335,8 @@ class TestTokenRevocation:)_run(_run_test())- def test_logout_triggers_revocation(self):- """POST /auth/logout must call DB revocation methods."""+ def test_logout_triggers_cookie_family_revocation(self):+ """POST /auth/logout must use refresh-cookie family authority."""db = _make_mock_db()db.is_access_token_revoked = AsyncMock(return_value=False)db.get_user = AsyncMock(return_value={@@ -305,8 +346,9 @@ class TestTokenRevocation:async def _run_test():async with self._client(db) as c:r = await c.post("/auth/logout", headers=_auth("alice", "operator"))- assert r.status_code == 200- db.revoke_current_session.assert_awaited_once()+ assert r.status_code == 204+ db.revoke_refresh_cookie_session.assert_awaited_once()+ db.revoke_current_session.assert_not_awaited()_run(_run_test())@@ -445,16 +487,12 @@ class TestRBACEnforcement:_reset_limiter()def _client(self, mock_db=None):- import httpxfrom ares.api.server import app, get_db, get_settingsdb = mock_db or _make_mock_db()app.state.db = dbapp.dependency_overrides[get_db] = lambda: dbapp.dependency_overrides[get_settings] = lambda: _settings()- return httpx.AsyncClient(- transport=httpx.ASGITransport(app=app),- base_url="http://localhost",- )+ return _browser_client(app)def test_no_token_returns_401(self):"""Unauthenticated request must return 401, not 403."""@@ -576,16 +614,12 @@ class TestRefreshTokenRateLimit:_reset_limiter()def _client(self, mock_db=None):- import httpxfrom ares.api.server import app, get_db, get_settingsdb = mock_db or _make_mock_db()app.state.db = dbapp.dependency_overrides[get_db] = lambda: dbapp.dependency_overrides[get_settings] = lambda: _settings()- return httpx.AsyncClient(- transport=httpx.ASGITransport(app=app),- base_url="http://localhost",- )+ return _browser_client(app)def test_rate_limited_after_many_attempts(self):"""After N refresh calls from same IP, 429 must be returned."""@@ -595,9 +629,8 @@ class TestRefreshTokenRateLimit:async def _run_test():async with self._client() as c:statuses = []- for i in range(limit + 2):- r = await c.post("/auth/refresh",- json={"refresh_token": f"fake-{i}"})+ for _ in range(limit + 2):+ r = await c.post("/auth/refresh")statuses.append(r.status_code)assert 429 in statuses, (f"Expected 429 after {limit} attempts, got statuses: {statuses}"@@ -611,9 +644,8 @@ class TestRefreshTokenRateLimit:async def _run_test():async with self._client() as c:- for i in range(limit + 1):- r = await c.post("/auth/refresh",- json={"refresh_token": f"fake-{i}"})+ for _ in range(limit + 1):+ r = await c.post("/auth/refresh")if r.status_code == 429:headers_lower = {k.lower(): v for k, v in r.headers.items()}assert "retry-after" in headers_lower, (