Skip to content

armgit / ARES

Public Imported from GitHub
0

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

feat(auth): use one-time WebSocket tickets

Mafifrizi2d9a0a2f77c0
diff --git a/ares/api/rbac.py b/ares/api/rbac.py
index 30cd346..95c3346 100644
--- a/ares/api/rbac.py
+++ b/ares/api/rbac.py
@@ -21,13 +21,15 @@ import math
import time
from collections import defaultdict, deque
from collections.abc import Mapping
-from dataclasses import dataclass
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
from enum import Enum
from typing import Any
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from ares.core.logger import get_logger
+from ares.db.websocket_tickets import BearerTicketSource
logger = get_logger("ares.api.rbac")
@@ -53,6 +55,11 @@ class AuthenticatedUser:
auth_type: str = "bearer"
api_key_id: str | None = None
api_key_scopes: tuple[str, ...] = ()
+ websocket_ticket_source: BearerTicketSource | None = field(
+ default=None,
+ repr=False,
+ compare=False,
+ )
@property
def is_api_key(self) -> bool:
@@ -87,6 +94,10 @@ class AuthoritativePrincipal:
user_id: str
username: str
role: str
+ websocket_ticket_source: BearerTicketSource = field(
+ repr=False,
+ compare=False,
+ )
@dataclass(frozen=True)
@@ -129,6 +140,7 @@ async def resolve_bearer_principal(
return PrincipalDecision(PrincipalDecisionStatus.INVALID)
try:
expires_at_is_finite = math.isfinite(float(expires_at))
+ source_expiry = datetime.fromtimestamp(float(expires_at), timezone.utc)
except (TypeError, ValueError, OverflowError):
return PrincipalDecision(PrincipalDecisionStatus.INVALID)
if not expires_at_is_finite:
@@ -169,6 +181,12 @@ async def resolve_bearer_principal(
user_id=user_id,
username=username,
role=role,
+ websocket_ticket_source=BearerTicketSource(
+ user_id=user_id,
+ subject=subject,
+ jti=jti,
+ expires_at=source_expiry,
+ ),
),
)
@@ -454,7 +472,11 @@ async def get_current_user(
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
- return AuthenticatedUser(username=principal.username, role=principal.role)
+ return AuthenticatedUser(
+ username=principal.username,
+ role=principal.role,
+ websocket_ticket_source=principal.websocket_ticket_source,
+ )
def require_role(*allowed_roles: str) -> Any:
diff --git a/ares/api/server.py b/ares/api/server.py
index ad0ae51..10f29b9 100644
--- a/ares/api/server.py
+++ b/ares/api/server.py
@@ -31,6 +31,7 @@ from fastapi import (
HTTPException,
Query,
Request,
+ Response,
WebSocket,
WebSocketDisconnect,
)
@@ -55,7 +56,6 @@ from ares.api.rbac import (
require_any_auth,
require_operator,
require_team_lead,
- resolve_bearer_principal,
)
from ares.core.campaign import Campaign, Finding
from ares.core.config import AresSettings, get_settings
@@ -65,6 +65,12 @@ from ares.core.security import create_access_token
from ares.modules.base import normalize_module_metadata
from ares.core.tracing import get_current_trace_id, instrument_fastapi, setup_tracing
from ares.db.database import AresDatabase
+from ares.db.websocket_tickets import (
+ ApiKeyTicketSource,
+ ConsumedWebSocketTicket,
+ WebSocketTicketPrincipal,
+ is_canonical_websocket_ticket,
+)
logger = get_logger("ares.api.server")
@@ -249,12 +255,11 @@ _db: AresDatabase | None = None
# WebSocket registry: campaign_id → opaque authenticated connection contexts.
@dataclass(eq=False)
class _CampaignWebSocketConnection:
- """Opaque main-WebSocket state; credentials must never appear in repr/logs."""
+ """Opaque main-WebSocket state; ticket material must never be retained."""
websocket: WebSocket = field(repr=False)
campaign_id: str = field(repr=False)
- credential_kind: str
- credential: str = field(repr=False)
+ ticket_handle: ConsumedWebSocketTicket = field(repr=False)
send_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)
closed: bool = False
@@ -670,6 +675,12 @@ _api_key_read_dep = Depends(require_api_key_scope("read", "write", "admin"))
_api_key_write_dep = Depends(require_api_key_scope("write", "admin"))
_current_user_or_apikey_dep = _api_key_read_dep
_db_dep = Depends(get_db)
+_auth_rate_dep = Depends(rate_limit("auth"))
+
+
+class WebSocketTicketResponse(BaseModel):
+ ticket: str
+ expires_in: int
# ── Error schema ──────────────────────────────────────────────────────────────
@@ -1185,6 +1196,80 @@ async def get_campaign(
return c
+ "/campaigns/{campaign_id}/websocket-ticket",
+ tags=["campaigns"],
+ response_model=WebSocketTicketResponse,
+ status_code=201,
+)
+async def issue_campaign_websocket_ticket(
+ campaign_id: str,
+ response: Response,
+ actor: AuthenticatedUser = _api_key_read_dep,
+ _rate: None = _auth_rate_dep,
+ db: AresDatabase = _db_dep,
+) -> WebSocketTicketResponse:
+ """Issue one committed, campaign-bound WebSocket handshake ticket."""
+ try:
+ campaign = await db.get_campaign(campaign_id)
+ except Exception as exc:
+ logger.warning(
+ "websocket_ticket_campaign_lookup_failed",
+ error_type=type(exc).__name__,
+ )
+ raise HTTPException(503, "Authentication service unavailable") from None
+ if not isinstance(campaign, Mapping):
+ raise HTTPException(404, "Campaign not found")
+ await _require_campaign_access(campaign, actor)
+
+ source = actor.websocket_ticket_source
+ if actor.is_api_key:
+ key_id = actor.api_key_id
+ if not isinstance(key_id, str) or not key_id.strip():
+ raise HTTPException(401, "Not authenticated")
+ try:
+ owner = await db.get_user(actor.username)
+ except Exception as exc:
+ logger.warning(
+ "websocket_ticket_owner_lookup_failed",
+ error_type=type(exc).__name__,
+ )
+ raise HTTPException(503, "Authentication service unavailable") from None
+ if not isinstance(owner, Mapping):
+ raise HTTPException(401, "Not authenticated")
+ owner_id = owner.get("id")
+ owner_name = owner.get("username")
+ owner_role = owner.get("role")
+ if (
+ not isinstance(owner_id, str)
+ or not owner_id.strip()
+ or owner_name != actor.username
+ or owner_role != actor.role
+ ):
+ raise HTTPException(401, "Not authenticated")
+ source = ApiKeyTicketSource(
+ user_id=owner_id,
+ api_key_id=key_id,
+ )
+ elif source is None:
+ raise HTTPException(401, "Not authenticated")
+
+ try:
+ issued = await db.issue_websocket_ticket(campaign_id, source)
+ except Exception as exc:
+ logger.warning(
+ "websocket_ticket_issue_failed",
+ error_type=type(exc).__name__,
+ )
+ raise HTTPException(503, "Authentication service unavailable") from None
+ if issued is None:
+ raise HTTPException(401, "Not authenticated")
+ raw_ticket, expires_in = issued
+ response.headers["Cache-Control"] = "no-store"
+ response.headers["Pragma"] = "no-cache"
+ return WebSocketTicketResponse(ticket=raw_ticket, expires_in=expires_in)
+
+
@app.delete("/campaigns/{campaign_id}", tags=["campaigns"])
async def delete_campaign(
campaign_id: str,
@@ -1828,70 +1913,54 @@ def _websocket_database(connection: _CampaignWebSocketConnection) -> Any | None:
async def _authorize_campaign_websocket(
connection: _CampaignWebSocketConnection,
) -> PrincipalDecisionStatus:
- """Revalidate identity, current role, scopes, and campaign access."""
+ """Revalidate the consumed ticket's source authority and campaign access."""
db = _websocket_database(connection)
if db is None:
logger.warning("campaign_websocket_auth_backend_unavailable")
return PrincipalDecisionStatus.BACKEND_UNAVAILABLE
- if connection.credential_kind == "bearer":
- settings = get_settings()
- decision = await resolve_bearer_principal(
- connection.credential,
- db=db,
- secret_key=settings.secret_key_value,
- algorithm=settings.ares_jwt_algorithm,
- )
- if decision.status is not PrincipalDecisionStatus.AUTHORIZED:
- return decision.status
- if decision.principal is None:
- return PrincipalDecisionStatus.INVALID
- actor = AuthenticatedUser(
- username=decision.principal.username,
- role=decision.principal.role,
- )
- elif connection.credential_kind == "api_key":
- try:
- data = await db.verify_api_key(connection.credential)
- except Exception as exc:
- logger.warning(
- "campaign_websocket_api_key_lookup_failed",
- error_type=type(exc).__name__,
- )
- return PrincipalDecisionStatus.BACKEND_UNAVAILABLE
- if not isinstance(data, Mapping):
- return PrincipalDecisionStatus.INVALID
- username = data.get("username")
- role = data.get("role")
- if not isinstance(username, str) or not isinstance(role, str):
- return PrincipalDecisionStatus.INVALID
- actor = AuthenticatedUser(
- username=username,
- role=role,
- auth_type="api_key",
- api_key_id=data.get("key_id") or data.get("id"),
- api_key_scopes=_normalize_api_key_scopes(data.get("scopes")),
- )
- if not actor.has_api_scope("read", "write", "admin"):
- return PrincipalDecisionStatus.INVALID
- else:
- return PrincipalDecisionStatus.INVALID
-
try:
- campaign = await db.get_campaign(connection.campaign_id)
+ principal = await db.resolve_websocket_ticket_principal(
+ connection.ticket_handle
+ )
except Exception as exc:
logger.warning(
- "campaign_websocket_campaign_lookup_failed",
+ "campaign_websocket_principal_lookup_failed",
error_type=type(exc).__name__,
)
return PrincipalDecisionStatus.BACKEND_UNAVAILABLE
- if not isinstance(campaign, Mapping):
+ if not isinstance(principal, WebSocketTicketPrincipal):
return PrincipalDecisionStatus.INVALID
- if actor.role != "team_lead" and campaign.get("operator") != actor.username:
+ if principal.user_id != connection.ticket_handle.user_id:
return PrincipalDecisionStatus.INVALID
return PrincipalDecisionStatus.AUTHORIZED
+def _take_campaign_websocket_ticket(websocket: WebSocket) -> str | None:
+ """Scrub and parse the exact ticket-only query shape without awaiting."""
+ private_query = memoryview(
+ websocket.scope.get("query_string", b"")
+ ).tobytes()
+ websocket.scope["query_string"] = b""
+ raw_ticket: str | None = None
+ try:
+ prefix = b"ticket="
+ if len(private_query) != len(prefix) + 43 or not private_query.startswith(
+ prefix
+ ):
+ return None
+ try:
+ candidate = private_query[len(prefix) :].decode("ascii")
+ except UnicodeDecodeError:
+ return None
+ if not is_canonical_websocket_ticket(candidate):
+ return None
+ raw_ticket = candidate
+ finally:
+ private_query = b""
+ return raw_ticket
+
+
def _websocket_close_details(
status: PrincipalDecisionStatus,
) -> tuple[int, str]:
@@ -1980,30 +2049,43 @@ async def _disconnect_websocket(
async def campaign_events(
websocket: WebSocket,
campaign_id: str,
- token: str | None = Query(None),
- api_key: str | None = Query(None),
) -> None:
- """
- Real-time campaign events stream.
- Auth: ?token=<access_token> or ?api_key=<key>
- Events: module_start, module_complete, finding_discovered, campaign_status_change
-
- Security note: WebSocket protocol does not support Authorization headers,
- so tokens are passed as query params — a known limitation. The token will
- appear in nginx access logs. Mitigations applied:
- 1. nginx log_format redacts ?token= and ?api_key= values (see nginx.conf)
- 2. Token is short-lived (ARES_JWT_EXPIRE_MINUTES, default 60 min)
- 3. nginx access logs should be stored with restricted permissions
- """
- # Explicit bearer credentials remain first and terminal; API keys are only
- # considered when no bearer credential was supplied.
- if token is not None:
- credential_kind = "bearer"
- credential = token
- elif api_key is not None:
- credential_kind = "api_key"
- credential = api_key
- else:
+ """Real-time campaign events authenticated by one single-use ticket."""
+ raw_ticket = _take_campaign_websocket_ticket(websocket)
+ if raw_ticket is None:
+ await _close_websocket_handshake(
+ websocket,
+ PrincipalDecisionStatus.INVALID,
+ )
+ return
+
+ app_instance = websocket.scope.get("app")
+ state = getattr(app_instance, "state", None)
+ db = getattr(state, "db", None)
+ if db is None:
+ await _close_websocket_handshake(
+ websocket,
+ PrincipalDecisionStatus.BACKEND_UNAVAILABLE,
+ )
+ return
+ try:
+ ticket_handle = await db.consume_websocket_ticket(
+ raw_ticket,
+ campaign_id,
+ )
+ except Exception as exc:
+ logger.warning(
+ "campaign_websocket_ticket_consume_failed",
+ error_type=type(exc).__name__,
+ )
+ await _close_websocket_handshake(
+ websocket,
+ PrincipalDecisionStatus.BACKEND_UNAVAILABLE,
+ )
+ return
+ finally:
+ raw_ticket = ""
+ if not isinstance(ticket_handle, ConsumedWebSocketTicket):
await _close_websocket_handshake(
websocket,
PrincipalDecisionStatus.INVALID,
@@ -2013,8 +2095,7 @@ async def campaign_events(
connection = _CampaignWebSocketConnection(
websocket=websocket,
campaign_id=campaign_id,
- credential_kind=credential_kind,
- credential=credential,
+ ticket_handle=ticket_handle,
)
status = await _authorize_campaign_websocket(connection)
if status is not PrincipalDecisionStatus.AUTHORIZED:
diff --git a/docker/nginx.conf b/docker/nginx.conf
index e058ed7..c760ecf 100644
--- a/docker/nginx.conf
+++ b/docker/nginx.conf
@@ -1,8 +1,8 @@
# ARES Production nginx config
# Place TLS certs in docker/certs/ares.crt and docker/certs/ares.key
-# Redact sensitive query params (WebSocket token, api_key) from access logs
-# WebSocket auth uses ?token= query param — must not appear in plain logs
+# TLS access logs use $uri, which omits one-time WebSocket ticket queries.
+# Do not replace $uri with $request_uri in the production access log format.
log_format ares_redacted '$remote_addr - $remote_user [$time_local] '
'"$request_method $uri [REDACTED_QUERY] $server_protocol" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent"';
@@ -15,7 +15,8 @@ map $request_uri $redacted_uri {
# Using server_name _ (catch-all) accepts connections from any hostname.
# Example: server_name ares.corp.local;
-# HTTP → HTTPS redirect
+# HTTP → HTTPS redirect. $request_uri reflects queries on this unsupported
+# plaintext boundary; production clients must connect with HTTPS/WSS directly.
server {
listen 80;
server_name _; # TODO: replace with FQDN, e.g. ares.corp.local
@@ -33,7 +34,7 @@ server {
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
- # Redact ?token= and ?api_key= from logs (WebSocket auth security)
+ # $uri omits the one-time ticket query while preserving TLS access logging.
access_log /var/log/nginx/ares_access.log ares_redacted;
# Security headers
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 278648a..3939c9c 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -585,10 +585,30 @@ System health check. Does not require authentication.
## WebSocket
-### `WS /ws/campaigns/{campaign_id}/events?token=<token>`
+### `POST /campaigns/{campaign_id}/websocket-ticket`
-Real-time event stream for a campaign.
-Auth: `?token=<access_token>` query param (WebSocket cannot send headers before connect).
+Issue a short-lived ticket for the main campaign WebSocket. Authenticate this
+HTTP request with the normal bearer header or `X-API-Key`; API keys require a
+`read`, `write`, or `admin` scope. The response is never cacheable:
+
+```json
+{ "ticket": "<one-time-ticket>", "expires_in": 30 }
+```
+
+The ticket is campaign-bound, expires after 30 seconds if unused, and can be
+consumed successfully only once. Presenting it to a different campaign does
+not consume it. A successful consume remains spent even if WebSocket accept
+subsequently fails, so every connection or reconnect must request a new one.
+
+### `WS /ws/campaigns/{campaign_id}/events?ticket=<one-time-ticket>`
+
+Real-time event stream for a campaign. The main route accepts only the exact
+single `ticket` query parameter. Bearer-token and API-key WebSocket query
+credentials are removed and have no compatibility fallback. After connection,
+ARES revalidates the ticket's original bearer or API-key authority before
+connected, pong, keepalive, module, and strategy event delivery. Ticket expiry
+or row cleanup does not end a connected session while that source authority
+remains valid.
**Events:**
```json
@@ -617,10 +637,21 @@ Windows, and open the Vite-served dashboard at
`http://127.0.0.1:8080` by default.
The dashboard uses `POST /auth/token`, `POST /auth/refresh`, the main REST API,
-and `WS /ws/campaigns/{campaign_id}/events?token=<token>`. Legacy
+`POST /campaigns/{campaign_id}/websocket-ticket`, and the ticket-only main
+campaign WebSocket. Legacy
`/dashboard/api/*` and `/dashboard/ws/live` routes are not the primary data
source.
+Deploy the backend and frontend atomically and drain existing main WebSocket
+connections during rollout. Old-frontend/new-backend and
+new-frontend/old-backend combinations are unsupported. Rollback likewise
+replaces both components together; the additive ticket migrations remain
+installed. Production clients must use HTTPS/WSS directly. The one-time ticket
+can still be visible in browser developer tools or to upstream components that
+receive 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.
+
The supported dashboard is `/dashboard` on the main ARES application. The
older `ares.api.dashboard.app:dashboard_app` FastAPI application is not mounted
by that supported topology. Under normal ASGI lifespan processing, direct
diff --git a/docs/frontend.md b/docs/frontend.md
index 05e32c7..f37a330 100644
--- a/docs/frontend.md
+++ b/docs/frontend.md
@@ -42,6 +42,11 @@ Then open `http://127.0.0.1:5173/dashboard/`.
- Refresh tokens are stored in `sessionStorage`; React output escaping and the
FastAPI CSP reduce script injection risk.
- Logout calls `POST /auth/logout` and clears local token state.
+- 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
+ asynchronous connection barrier and is never stored in React state,
+ `localStorage`, or `sessionStorage`.
## Routes
@@ -54,7 +59,10 @@ Then open `http://127.0.0.1:5173/dashboard/`.
- `/strategy`: `Objective`, `Active`, and `Result` tabs for active engagements and role-gated engagement start
- `/security`: `Account`, `API Keys`, and `Audit` tabs for profile, password change, API keys, audit, and users
- `/edr`: `Knowledge Base` and `Report Outcome` tabs for bypass telemetry and outcome reporting
-- `/live`: `Stream` and `Buffer` tabs backed by `WS /ws/campaigns/{campaign_id}/events?token=<token>`
+- `/live`: `Stream` and `Buffer` tabs backed by the ticket-only `WS
+ /ws/campaigns/{campaign_id}/events?ticket=<one-time-ticket>` route. Every
+ reconnect requests a fresh ticket; bearer/API-key query credentials are no
+ longer supported.
## Shell Controls
@@ -84,4 +92,18 @@ Dashboard result panels are context-aware. Modules, reports, graph ingest, templ
Long-running actions should show a loading state on the button or result area. Operators should be able to tell that ARES is processing a request without watching the terminal.
-The Live page owns a browser WebSocket connection. Navigating away closes that connection, so users reconnect when they return to the page.
+The Live page owns a browser WebSocket connection. It checks the captured
+session revision, campaign, effect, and connection generation after ticket
+issuance and discards a late response after logout, account replacement,
+campaign change, cleanup, or unmount. A same-session access-token refresh does
+not invalidate that barrier. Navigating away closes the connection, so users
+request a fresh ticket when they return.
+
+Production frontend and backend versions must roll out atomically, with
+existing sockets drained. Mixed old/new versions are unsupported, and rollback
+replaces both together while leaving additive migrations installed. Use
+HTTPS/WSS directly: one-time tickets can remain visible in browser developer
+tools 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
+retains its separate limitations.
diff --git a/docs/security-model.md b/docs/security-model.md
index ffecfc5..83be187 100644
--- a/docs/security-model.md
+++ b/docs/security-model.md
@@ -154,6 +154,37 @@ remain. Full retirement is the preferred final control.
Tokens are issued by `POST /auth/token` with valid operator credentials (bcrypt-hashed password). Default expiry: 1 hour.
+### Main WebSocket tickets
+
+The supported main campaign WebSocket never accepts a bearer token or API key
+in its query string. A client authenticates `POST
+/campaigns/{campaign_id}/websocket-ticket` with the normal bearer or API-key
+header, then presents the returned ticket as the sole WebSocket query
+parameter. Tickets have a 30-second issuance lifetime, are bound to one
+campaign, and are globally single-use. A wrong-campaign presentation is denied
+without consuming the ticket; replay and every legacy `token` or `api_key`
+query form are denied.
+
+Consumption is only the handshake authority. A connected socket retains an
+opaque consumed handle and ARES revalidates the original current user,
+bearer-expiry/JTI, API-key scope/lifetime/ownership, role, and campaign access
+before protected events. This resolution is read-only and remains possible
+after the ticket row expires or is purged. No registry entry retains a raw
+ticket, bearer, API key, ticket hash, or original query string.
+
+Tickets remain visible to the browser and any upstream component that receives
+the handshake URL, so production clients must initiate HTTPS/WSS directly.
+The production nginx TLS log uses `$uri`, which omits query strings. Its
+port-80 redirect uses `$request_uri`; ticket-bearing plaintext requests at that
+boundary are unsupported. The control does not claim to hide tickets from
+browser developer tools or arbitrary third-party proxies.
+
+Backend and frontend rollout is atomic: drain existing main WebSockets, deploy
+both components together, and obtain a fresh ticket for every reconnect. Mixed
+old/new component versions are unsupported. A rollback replaces both together
+while leaving additive migrations installed. These controls do not change the
+default-disabled legacy dashboard WebSocket or repair its known limitations.
+
### Authorization
ARES uses four account roles. Role values are lowercase in API requests:
diff --git a/frontend/src/api/client.test.ts b/frontend/src/api/client.test.ts
index 2f6f167..f32d991 100644
--- a/frontend/src/api/client.test.ts
+++ b/frontend/src/api/client.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
ApiError,
+ api,
beginIdentityTransition,
buildModuleRunPayload,
campaignEventsPath,
@@ -319,9 +320,33 @@ describe("module execution helpers", () => {
});
describe("live event helpers", () => {
- it("uses the backend campaign websocket route", () => {
- const path = campaignEventsPath("camp/one", "token value");
- const matchesExpectedRoute = path === "/ws/campaigns/camp%2Fone/events?token=token%20value";
+ 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("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");
});
});
diff --git a/frontend/src/api/endpoints.ts b/frontend/src/api/endpoints.ts
index b768474..6662342 100644
--- a/frontend/src/api/endpoints.ts
+++ b/frontend/src/api/endpoints.ts
@@ -11,7 +11,8 @@ import type {
ReportItem,
TemplateMeta,
TokenResponse,
- UserProfile
+ UserProfile,
+ WebSocketTicketResponse
} from "./types";
import { apiBlobRequest, apiRequest, ApiError } from "./http";
import { beginIdentityTransition, installTokenPairIfCurrent } from "./session";
@@ -40,8 +41,8 @@ export async function logout(): Promise<void> {
await apiRequest<{ status: string }>("/auth/logout", { method: "POST" }, false);
}
-export function campaignEventsPath(campaignId: string, token: string): string {
- return `/ws/campaigns/${encodeURIComponent(campaignId)}/events?token=${encodeURIComponent(token)}`;
+export function campaignEventsPath(campaignId: string, ticket: string): string {
+ return `/ws/campaigns/${encodeURIComponent(campaignId)}/events?ticket=${encodeURIComponent(ticket)}`;
}
export function buildModuleRunPayload(
@@ -65,6 +66,11 @@ export const api = {
body: JSON.stringify(body)
}),
campaign: (id: string) => apiRequest<Campaign>(`/campaigns/${encodeURIComponent(id)}`),
+ websocketTicket: (id: string) =>
+ apiRequest<WebSocketTicketResponse>(
+ `/campaigns/${encodeURIComponent(id)}/websocket-ticket`,
+ { method: "POST" }
+ ),
deleteCampaign: (id: string) =>
apiRequest<Record<string, string>>(`/campaigns/${encodeURIComponent(id)}`, { method: "DELETE" }),
findings: (id: string) => apiRequest<Finding[]>(`/campaigns/${encodeURIComponent(id)}/findings`),
diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts
index 486c072..ce24d92 100644
--- a/frontend/src/api/types.ts
+++ b/frontend/src/api/types.ts
@@ -13,6 +13,11 @@ export interface UserProfile {
role: Role;
}
+export interface WebSocketTicketResponse {
+ ticket: string;
+ expires_in: 30;
+}
+
export interface Campaign {
id: string;
name: string;
diff --git a/frontend/src/features/dashboard/DashboardPages.test.tsx b/frontend/src/features/dashboard/DashboardPages.test.tsx
new file mode 100644
index 0000000..520afb0
--- /dev/null
+++ b/frontend/src/features/dashboard/DashboardPages.test.tsx
@@ -0,0 +1,295 @@
+import { act, cleanup, render, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { api, beginIdentityTransition, clearTokens, setAccessToken } from "../../api/client";
+import { installTokenPairIfCurrent } from "../../api/session";
+import { CampaignEventSocketController } from "./DashboardPages";
+
+interface Deferred<T> {
+ promise: Promise<T>;
+ reject: (reason?: unknown) => void;
+ resolve: (value: T) => void;
+}
+
+function deferred<T>(): Deferred<T> {
+ let resolve!: (value: 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);
+ }
+}
+
+const ticketA = "A".repeat(43);
+const ticketB = "B".repeat(43);
+
+class ReducedWebSocket {
+ static constructorCount = 0;
+ static closeCount = 0;
+ static legacyCredentialObserved = false;
+ static canonicalTicketObserved = false;
+ static freshTicketObserved = false;
+
+ onclose: (() => void) | null = null;
+ onmessage: ((event: MessageEvent) => void) | null = null;
+
+ constructor(url: string | URL) {
+ const candidate = String(url);
+ ReducedWebSocket.constructorCount += 1;
+ ReducedWebSocket.legacyCredentialObserved =
+ ReducedWebSocket.legacyCredentialObserved
+ || candidate.includes("token=")
+ || candidate.includes("api_key=");
+ ReducedWebSocket.canonicalTicketObserved =
+ ReducedWebSocket.canonicalTicketObserved
+ || candidate.endsWith(`?ticket=${ticketA}`)
+ || candidate.endsWith(`?ticket=${ticketB}`);
+ ReducedWebSocket.freshTicketObserved =
+ ReducedWebSocket.freshTicketObserved
+ || candidate.endsWith(`?ticket=${ticketB}`);
+ }
+
+ close(): void {
+ ReducedWebSocket.closeCount += 1;
+ }
+
+ static reset(): void {
+ ReducedWebSocket.constructorCount = 0;
+ ReducedWebSocket.closeCount = 0;
+ ReducedWebSocket.legacyCredentialObserved = false;
+ ReducedWebSocket.canonicalTicketObserved = false;
+ ReducedWebSocket.freshTicketObserved = false;
+ }
+}
+
+function installSession(label = "a"): void {
+ const snapshot = beginIdentityTransition();
+ const installed = installTokenPairIfCurrent(
+ snapshot,
+ `access-${label}`,
+ `refresh-${label}`
+ );
+ requireFixed(installed, "expected test session installation");
+}
+
+function storageExcludesTickets(): boolean {
+ const values: string[] = [];
+ for (const storage of [localStorage, sessionStorage]) {
+ for (let index = 0; index < storage.length; index += 1) {
+ const key = storage.key(index);
+ if (key !== null) {
+ values.push(storage.getItem(key) ?? "");
+ }
+ }
+ }
+ return values.every((value) => !value.includes(ticketA) && !value.includes(ticketB));
+}
+
+describe("campaign WebSocket ticket barrier", () => {
+ beforeEach(() => {
+ clearTokens();
+ localStorage.clear();
+ sessionStorage.clear();
+ installSession();
+ ReducedWebSocket.reset();
+ vi.stubGlobal("WebSocket", ReducedWebSocket);
+ });
+
+ afterEach(() => {
+ cleanup();
+ clearTokens();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ sessionStorage.clear();
+ });
+
+ it("awaits issuance before constructing a ticket-only WebSocket", async () => {
+ const barrier = deferred<{ ticket: string; expires_in: 30 }>();
+ vi.spyOn(api, "websocketTicket").mockReturnValue(barrier.promise);
+ const disconnected = vi.fn();
+ const events = vi.fn();
+
+ render(<CampaignEventSocketController
+ campaignId="campaign-a"
+ enabled
+ onDisconnected={disconnected}
+ onEvent={events}
+ />);
+ expect(ReducedWebSocket.constructorCount).toBe(0);
+
+ await act(async () => {
+ barrier.resolve({ ticket: ticketA, expires_in: 30 });
+ await barrier.promise;
+ });
+ await waitFor(() => expect(ReducedWebSocket.constructorCount).toBe(1));
+ requireFixed(
+ ReducedWebSocket.canonicalTicketObserved
+ && !ReducedWebSocket.legacyCredentialObserved
+ && storageExcludesTickets(),
+ "expected transient ticket-only WebSocket construction",
+ );
+ expect(disconnected).not.toHaveBeenCalled();
+ expect(events).not.toHaveBeenCalled();
+ });
+
+ it("discards a ticket response after logout or another-account login", async () => {
+ const logoutBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ const loginBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ vi.spyOn(api, "websocketTicket")
+ .mockReturnValueOnce(logoutBarrier.promise)
+ .mockReturnValueOnce(loginBarrier.promise);
+
+ const first = render(<CampaignEventSocketController
+ campaignId="campaign-a"
+ enabled
+ onDisconnected={vi.fn()}
+ onEvent={vi.fn()}
+ />);
+ clearTokens();
+ await act(async () => {
+ logoutBarrier.resolve({ ticket: ticketA, expires_in: 30 });
+ await logoutBarrier.promise;
+ });
+ first.unmount();
+
+ installSession("a-again");
+ const second = render(<CampaignEventSocketController
+ campaignId="campaign-a"
+ enabled
+ onDisconnected={vi.fn()}
+ onEvent={vi.fn()}
+ />);
+ installSession("b");
+ await act(async () => {
+ loginBarrier.resolve({ ticket: ticketA, expires_in: 30 });
+ await loginBarrier.promise;
+ });
+ second.unmount();
+
+ expect(ReducedWebSocket.constructorCount).toBe(0);
+ });
+
+ it("discards superseded campaign and unmounted responses", async () => {
+ const firstBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ const secondBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ const unmountBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ vi.spyOn(api, "websocketTicket")
+ .mockReturnValueOnce(firstBarrier.promise)
+ .mockReturnValueOnce(secondBarrier.promise)
+ .mockReturnValueOnce(unmountBarrier.promise);
+ const options = {
+ campaignId: "campaign-a",
+ enabled: true,
+ onDisconnected: vi.fn(),
+ onEvent: vi.fn()
+ };
+ const hook = render(<CampaignEventSocketController {...options} />);
+ hook.rerender(<CampaignEventSocketController
+ {...options}
+ campaignId="campaign-b"
+ />);
+ await act(async () => {
+ firstBarrier.resolve({ ticket: ticketA, expires_in: 30 });
+ await firstBarrier.promise;
+ });
+ expect(ReducedWebSocket.constructorCount).toBe(0);
+ await act(async () => {
+ secondBarrier.resolve({ ticket: ticketB, expires_in: 30 });
+ await secondBarrier.promise;
+ });
+ await waitFor(() => expect(ReducedWebSocket.constructorCount).toBe(1));
+ hook.unmount();
+
+ const unmounted = render(<CampaignEventSocketController
+ {...options}
+ campaignId="campaign-c"
+ />);
+ unmounted.unmount();
+ await act(async () => {
+ unmountBarrier.resolve({ ticket: ticketA, expires_in: 30 });
+ await unmountBarrier.promise;
+ });
+ expect(ReducedWebSocket.constructorCount).toBe(1);
+ expect(ReducedWebSocket.closeCount).toBe(1);
+ });
+
+ it("allows same-session refresh while rejecting malformed issuance", async () => {
+ const validBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ const malformedBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ vi.spyOn(api, "websocketTicket")
+ .mockReturnValueOnce(validBarrier.promise)
+ .mockReturnValueOnce(malformedBarrier.promise);
+ const disconnected = vi.fn();
+ const valid = render(<CampaignEventSocketController
+ campaignId="campaign-a"
+ enabled
+ onDisconnected={disconnected}
+ onEvent={vi.fn()}
+ />);
+ setAccessToken("same-session-refreshed-access");
+ await act(async () => {
+ validBarrier.resolve({ ticket: ticketA, expires_in: 30 });
+ await validBarrier.promise;
+ });
+ await waitFor(() => expect(ReducedWebSocket.constructorCount).toBe(1));
+ valid.unmount();
+
+ const malformed = render(<CampaignEventSocketController
+ campaignId="campaign-a"
+ enabled
+ onDisconnected={disconnected}
+ onEvent={vi.fn()}
+ />);
+ await act(async () => {
+ malformedBarrier.resolve({ ticket: "invalid", expires_in: 30 });
+ await malformedBarrier.promise;
+ });
+ await waitFor(() => expect(disconnected).toHaveBeenCalledTimes(1));
+ malformed.unmount();
+ expect(ReducedWebSocket.constructorCount).toBe(1);
+ });
+
+ it("requests a new ticket after a failed attempt", async () => {
+ const failedBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ const retryBarrier = deferred<{ ticket: string; expires_in: 30 }>();
+ const ticketRequest = vi.spyOn(api, "websocketTicket")
+ .mockReturnValueOnce(failedBarrier.promise)
+ .mockReturnValueOnce(retryBarrier.promise);
+ const disconnected = vi.fn();
+ const options = {
+ campaignId: "campaign-a",
+ enabled: true,
+ onDisconnected: disconnected,
+ onEvent: vi.fn()
+ };
+ const hook = render(<CampaignEventSocketController {...options} />);
+ await act(async () => {
+ failedBarrier.reject(new Error("fixed test failure"));
+ try {
+ await failedBarrier.promise;
+ } catch {
+ // The hook owns the expected failure path.
+ }
+ });
+ await waitFor(() => expect(disconnected).toHaveBeenCalledTimes(1));
+
+ hook.rerender(<CampaignEventSocketController {...options} enabled={false} />);
+ hook.rerender(<CampaignEventSocketController {...options} enabled />);
+ await act(async () => {
+ retryBarrier.resolve({ ticket: ticketB, expires_in: 30 });
+ await retryBarrier.promise;
+ });
+ await waitFor(() => expect(ReducedWebSocket.constructorCount).toBe(1));
+ requireFixed(
+ ticketRequest.mock.calls.length === 2 && ReducedWebSocket.freshTicketObserved,
+ "expected a fresh ticket on the superseding connection attempt",
+ );
+ });
+});
diff --git a/frontend/src/features/dashboard/DashboardPages.tsx b/frontend/src/features/dashboard/DashboardPages.tsx
index 51d9a63..d9f43c6 100644
--- a/frontend/src/features/dashboard/DashboardPages.tsx
+++ b/frontend/src/features/dashboard/DashboardPages.tsx
@@ -40,7 +40,14 @@ import {
} from "react";
import { NavLink, Navigate, useNavigate } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { ApiError, api, buildModuleRunPayload, campaignEventsPath, getAccessToken } from "../../api/client";
+import {
+ ApiError,
+ api,
+ buildModuleRunPayload,
+ campaignEventsPath,
+ captureSession,
+ isSessionCurrent
+} from "../../api/client";
import type { ApiKeyMeta, Campaign, ExecutionChain, Finding, ModuleMeta, MonthlyFindingStats, ParamField, ReportItem } from "../../api/types";
import { useAuth } from "../auth/authContext";
import { DashboardUiProvider } from "./dashboardUi";
@@ -205,6 +212,110 @@ const pageMeta: Record<string, { icon: LucideIcon; eyebrow: string; description:
const brandMarkPath = "/dashboard/brand/ares-mark.png";
+interface CampaignEventSocketOptions {
+ campaignId: string;
+ enabled: boolean;
+ onDisconnected: () => void;
+ onEvent: (event: unknown) => void;
+}
+
+function useCampaignEventSocket({
+ campaignId,
+ enabled,
+ onDisconnected,
+ onEvent
+}: CampaignEventSocketOptions): void {
+ const socketRef = useRef<WebSocket | null>(null);
+ const generationRef = useRef(0);
+ const onDisconnectedRef = useRef(onDisconnected);
+ const onEventRef = useRef(onEvent);
+ onDisconnectedRef.current = onDisconnected;
+ onEventRef.current = onEvent;
+
+ useEffect(() => {
+ generationRef.current += 1;
+ const connectionGeneration = generationRef.current;
+ let disposed = false;
+ let ownedSocket: WebSocket | null = null;
+
+ if (!enabled || !campaignId) {
+ return;
+ }
+
+ const session = captureSession();
+ if (!session.accessToken) {
+ onDisconnectedRef.current();
+ return;
+ }
+
+ void (async () => {
+ try {
+ const response = await api.websocketTicket(campaignId);
+ const responseIsCanonical =
+ response.expires_in === 30
+ && /^[A-Za-z0-9_-]{43}$/.test(response.ticket);
+ if (!responseIsCanonical) {
+ throw new Error("Invalid WebSocket ticket response");
+ }
+ if (
+ disposed
+ || generationRef.current !== connectionGeneration
+ || !isSessionCurrent(session)
+ ) {
+ return;
+ }
+
+ const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
+ const socket = new WebSocket(
+ `${protocol}//${window.location.host}${campaignEventsPath(campaignId, response.ticket)}`
+ );
+ ownedSocket = socket;
+ socketRef.current = socket;
+ socket.onmessage = (event) => {
+ try {
+ onEventRef.current(JSON.parse(event.data));
+ } catch {
+ onEventRef.current(event.data);
+ }
+ };
+ socket.onclose = () => {
+ if (socketRef.current === socket) {
+ socketRef.current = null;
+ onDisconnectedRef.current();
+ }
+ };
+ } catch {
+ if (
+ !disposed
+ && generationRef.current === connectionGeneration
+ && isSessionCurrent(session)
+ ) {
+ onDisconnectedRef.current();
+ }
+ }
+ })();
+
+ return () => {
+ disposed = true;
+ generationRef.current += 1;
+ if (ownedSocket) {
+ ownedSocket.onclose = null;
+ ownedSocket.close();
+ if (socketRef.current === ownedSocket) {
+ socketRef.current = null;
+ }
+ }
+ };
+ }, [campaignId, enabled]);
+}
+
+export function CampaignEventSocketController(
+ options: CampaignEventSocketOptions
+): null {
+ useCampaignEventSocket(options);
+ return null;
+}
+
function formatRole(role?: string): string {
const labels: Record<string, string> = {
team_lead: "Team Lead",
@@ -232,7 +343,6 @@ export function DashboardShell({ children }: { children: ReactNode }) {
const [notificationsOpen, setNotificationsOpen] = useState(false);
const [readNotificationIds, setReadNotificationIds] = useState<string[]>([]);
const [deletedNotificationIds, setDeletedNotificationIds] = useState<string[]>([]);
- const liveSocketRef = useRef<WebSocket | null>(null);
const health = useQuery({ queryKey: ["health"], queryFn: api.health });
const telemetry = useQuery({ queryKey: ["telemetry"], queryFn: api.telemetry });
const campaigns = useQuery({ queryKey: ["campaigns"], queryFn: api.campaigns });
@@ -244,41 +354,12 @@ export function DashboardShell({ children }: { children: ReactNode }) {
enabled: Boolean(selectedCampaignId)
});
- useEffect(() => {
- const accessToken = getAccessToken();
- if (!liveConnected || !liveCampaignId || !accessToken) {
- if (liveSocketRef.current) {
- liveSocketRef.current.close();
- liveSocketRef.current = null;
- }
- return;
- }
-
- const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
- const socket = new WebSocket(`${protocol}//${window.location.host}${campaignEventsPath(liveCampaignId, accessToken)}`);
- liveSocketRef.current = socket;
- socket.onmessage = (event) => {
- try {
- setLiveEvents((items) => [JSON.parse(event.data), ...items].slice(0, 100));
- } catch {
- setLiveEvents((items) => [event.data, ...items].slice(0, 100));
- }
- };
- socket.onclose = () => {
- if (liveSocketRef.current === socket) {
- liveSocketRef.current = null;
- setLiveConnected(false);
- }
- };
-
- return () => {
- socket.onclose = null;
- socket.close();
- if (liveSocketRef.current === socket) {
- liveSocketRef.current = null;
- }
- };
- }, [liveCampaignId, liveConnected, setLiveEvents]);
+ useCampaignEventSocket({
+ campaignId: liveCampaignId,
+ enabled: liveConnected,
+ onDisconnected: () => setLiveConnected(false),
+ onEvent: (event) => setLiveEvents((items) => [event, ...items].slice(0, 100))
+ });
const dashboardUi = useMemo<DashboardUiState>(
() => ({
diff --git a/tests/unit/test_api_endpoints.py b/tests/unit/test_api_endpoints.py
index 25f1382..9410dbb 100644
--- a/tests/unit/test_api_endpoints.py
+++ b/tests/unit/test_api_endpoints.py
@@ -134,6 +134,9 @@ def _make_mock_db():
)
db.delete_campaign = AsyncMock(return_value=False)
db.verify_api_key = AsyncMock(return_value=None)
+ db.issue_websocket_ticket = AsyncMock(return_value=None)
+ db.consume_websocket_ticket = AsyncMock(return_value=None)
+ db.resolve_websocket_ticket_principal = AsyncMock(return_value=None)
return db
@@ -3700,6 +3703,200 @@ class TestAuthoritativeHTTPBearerPrincipal:
"expected an explicitly invalid bearer not to fall through to API-key auth",
)
+ @pytest.mark.asyncio
+ async def test_websocket_ticket_bearer_issuance_is_committed_and_uncached(
+ self,
+ auth_runtime: Any,
+ ) -> None:
+ from ares.core.campaign import Campaign
+
+ client, database, _, _, token, _ = auth_runtime
+ _reset_rate_limiter()
+ campaign = Campaign(
+ name="Ticket Issuance Campaign",
+ operator="separate-owner",
+ )
+ await database.save_campaign(campaign)
+ response = await client.post(
+ f"/campaigns/{campaign.id}/websocket-ticket",
+ headers=self._bearer_headers(token),
+ )
+ body = response.json()
+ ticket = body.get("ticket") if isinstance(body, dict) else None
+ async with database.conn.execute(
+ "SELECT COUNT(*) FROM websocket_tickets"
+ ) as cursor:
+ row_count = int((await cursor.fetchone())[0])
+ contract_is_exact = (
+ response.status_code == 201
+ and set(body) == {"ticket", "expires_in"}
+ and isinstance(ticket, str)
+ and len(ticket) == 43
+ and body.get("expires_in") == 30
+ and response.headers.get("cache-control") == "no-store"
+ and response.headers.get("pragma") == "no-cache"
+ and row_count == 1
+ )
+ _require_fixed(
+ contract_is_exact,
+ "expected one committed uncached bearer WebSocket ticket",
+ )
+
+ @pytest.mark.parametrize("scope", ["read", "write", "admin"])
+ @pytest.mark.asyncio
+ async def test_websocket_ticket_api_key_scopes_update_last_used_once(
+ self,
+ auth_runtime: Any,
+ scope: str,
+ ) -> None:
+ from ares.core.campaign import Campaign
+
+ client, database, user_id, username, _, _ = auth_runtime
+ _reset_rate_limiter()
+ await database.conn.execute(
+ "UPDATE users SET role='operator' WHERE id=?",
+ (user_id,),
+ )
+ campaign = Campaign(
+ name="API Key Ticket Campaign",
+ operator=username,
+ )
+ await database.save_campaign(campaign)
+ with patch("ares.db.database.logger.info"):
+ key_id, raw_key = await database.create_api_key(
+ user_id,
+ "ticket-key",
+ scopes=scope,
+ )
+ verify_calls = [0]
+ original_verify = database.verify_api_key
+
+ async def tracked_verify(candidate: str) -> Any:
+ verify_calls[0] += 1
+ return await original_verify(candidate)
+
+ database.verify_api_key = tracked_verify # type: ignore[method-assign]
+ response = await client.post(
+ f"/campaigns/{campaign.id}/websocket-ticket",
+ headers={"X-API-Key": raw_key},
+ )
+ async with database.conn.execute(
+ "SELECT last_used FROM api_keys WHERE id=?",
+ (key_id,),
+ ) as cursor:
+ last_used_present = (await cursor.fetchone())[0] is not None
+ async with database.conn.execute(
+ "SELECT COUNT(*) FROM websocket_tickets"
+ ) as cursor:
+ row_count = int((await cursor.fetchone())[0])
+ _require_fixed(
+ response.status_code == 201
+ and verify_calls[0] == 1
+ and last_used_present
+ and row_count == 1,
+ "expected one API-key verification and one committed ticket",
+ )
+
+ @pytest.mark.asyncio
+ async def test_websocket_ticket_denials_do_not_insert_rows(
+ self,
+ auth_runtime: Any,
+ monkeypatch: Any,
+ ) -> None:
+ from ares.api import server
+ from ares.core.campaign import Campaign
+
+ client, database, user_id, username, token, _ = auth_runtime
+ _reset_rate_limiter()
+ await database.conn.execute(
+ "UPDATE users SET role='operator' WHERE id=?",
+ (user_id,),
+ )
+ inaccessible = Campaign(
+ name="Inaccessible Ticket Campaign",
+ operator="different-owner",
+ )
+ accessible = Campaign(
+ name="Accessible Ticket Campaign",
+ operator=username,
+ )
+ await database.save_campaign(inaccessible)
+ await database.save_campaign(accessible)
+ with patch("ares.db.database.logger.info"):
+ _, insufficient_key = await database.create_api_key(
+ user_id,
+ "insufficient-ticket-key",
+ scopes="none",
+ )
+
+ invalid = await client.post(
+ f"/campaigns/{accessible.id}/websocket-ticket",
+ headers={"Authorization": "Bearer synthetic.invalid.jwt"},
+ )
+ insufficient = await client.post(
+ f"/campaigns/{accessible.id}/websocket-ticket",
+ headers={"X-API-Key": insufficient_key},
+ )
+ missing = await client.post(
+ "/campaigns/missing-ticket-campaign/websocket-ticket",
+ headers=self._bearer_headers(token),
+ )
+ inaccessible_response = await client.post(
+ f"/campaigns/{inaccessible.id}/websocket-ticket",
+ headers=self._bearer_headers(token),
+ )
+
+ original_issue = database.issue_websocket_ticket
+
+ async def lose_authority(_campaign_id: str, _source: Any) -> None:
+ return None
+
+ database.issue_websocket_ticket = lose_authority # type: ignore[method-assign]
+ revalidation_loss = await client.post(
+ f"/campaigns/{accessible.id}/websocket-ticket",
+ headers=self._bearer_headers(token),
+ )
+
+ async def fail_issue(_campaign_id: str, _source: Any) -> Any:
+ raise RuntimeError
+
+ database.issue_websocket_ticket = fail_issue # type: ignore[method-assign]
+ unavailable = await client.post(
+ f"/campaigns/{accessible.id}/websocket-ticket",
+ headers=self._bearer_headers(token),
+ )
+ database.issue_websocket_ticket = original_issue # type: ignore[method-assign]
+
+ original_limit = server._limiter.is_allowed_async
+
+ async def deny_auth_bucket(key: str, _limit: int) -> tuple[bool, int]:
+ return (False, 0) if key.startswith("auth:") else (True, 1)
+
+ monkeypatch.setattr(server._limiter, "is_allowed_async", deny_auth_bucket)
+ limited = await client.post(
+ f"/campaigns/{accessible.id}/websocket-ticket",
+ headers=self._bearer_headers(token),
+ )
+ monkeypatch.setattr(server._limiter, "is_allowed_async", original_limit)
+
+ async with database.conn.execute(
+ "SELECT COUNT(*) FROM websocket_tickets"
+ ) as cursor:
+ row_count = int((await cursor.fetchone())[0])
+ statuses = (
+ invalid.status_code,
+ insufficient.status_code,
+ missing.status_code,
+ inaccessible_response.status_code,
+ revalidation_loss.status_code,
+ limited.status_code,
+ unavailable.status_code,
+ )
+ _require_fixed(
+ statuses == (401, 403, 404, 404, 401, 429, 503) and row_count == 0,
+ "expected fixed ticket denial statuses without row insertion",
+ )
+
_WS_TEST_DISCONNECT = object()
_WS_TEST_HEARTBEAT = object()
@@ -3750,8 +3947,8 @@ class _FirstBroadcastSendCoordinator:
class _MainWebSocketHarness:
"""Minimal ASGI peer for the real registered WebSocket route."""
- def __init__(self, app: Any) -> None:
- self.scope = {"app": app}
+ def __init__(self, app: Any, query_string: bytes = b"") -> None:
+ self.scope = {"app": app, "query_string": query_string}
self.accepted = asyncio.Event()
self.closed = asyncio.Event()
self.disconnect_observed = asyncio.Event()
@@ -3762,6 +3959,7 @@ class _MainWebSocketHarness:
self.sent = asyncio.Queue[str]()
self.inbound = asyncio.Queue[Any]()
self.fail_next_send = False
+ self.fail_accept = False
self.block_next_send = False
self.send_started = asyncio.Event()
self.send_release = asyncio.Event()
@@ -3770,6 +3968,8 @@ class _MainWebSocketHarness:
) = None
async def accept(self) -> None:
+ if self.fail_accept:
+ raise RuntimeError
self.accepted.set()
async def close(self, *, code: int, reason: str) -> None:
@@ -3844,17 +4044,75 @@ async def _launch_main_websocket(
app: Any,
campaign_id: str,
*,
+ ticket: str | None = None,
token: str | None = None,
api_key: str | None = None,
+ query_string: bytes | None = None,
+ fail_accept: bool = False,
) -> tuple[_MainWebSocketHarness, asyncio.Task[None]]:
- socket = _MainWebSocketHarness(app)
+ if query_string is None:
+ if ticket is None and (token is not None or api_key is not None):
+ ticket = await _issue_main_websocket_ticket(
+ app,
+ campaign_id,
+ token=token,
+ api_key=api_key,
+ )
+ query_string = b"" if ticket is None else b"ticket=" + ticket.encode("ascii")
+ socket = _MainWebSocketHarness(app, query_string)
+ socket.fail_accept = fail_accept
endpoint = _main_campaign_websocket_endpoint(app)
- task = asyncio.create_task(
- endpoint(socket, campaign_id, token=token, api_key=api_key)
- )
+ task = asyncio.create_task(endpoint(socket, campaign_id))
return socket, task
+async def _request_main_websocket_ticket(
+ app: Any,
+ campaign_id: str,
+ *,
+ token: str | None = None,
+ api_key: str | None = None,
+) -> httpx.Response:
+ headers: dict[str, str] = {}
+ if token is not None:
+ headers["Authorization"] = f"Bearer {token}"
+ if api_key is not None:
+ headers["X-API-Key"] = api_key
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app),
+ base_url="http://localhost",
+ ) as client:
+ return await client.post(
+ f"/campaigns/{campaign_id}/websocket-ticket",
+ headers=headers,
+ )
+
+
+async def _issue_main_websocket_ticket(
+ app: Any,
+ campaign_id: str,
+ *,
+ token: str | None = None,
+ api_key: str | None = None,
+) -> str:
+ response = await _request_main_websocket_ticket(
+ app,
+ campaign_id,
+ token=token,
+ api_key=api_key,
+ )
+ body = response.json()
+ ticket = body.get("ticket") if isinstance(body, dict) else None
+ canonical = (
+ response.status_code == 201
+ and isinstance(ticket, str)
+ and len(ticket) == 43
+ and body.get("expires_in") == 30
+ )
+ _require_fixed(canonical, "expected committed WebSocket ticket issuance")
+ return ticket
+
+
async def _settle_main_websocket(
socket: _MainWebSocketHarness,
task: asyncio.Task[None],
@@ -3907,6 +4165,7 @@ class TestMainWebSocketAuthoritativeLifetime:
original_db = getattr(server.app.state, "db", None)
server.app.state.db = database
server._ws_connections.clear()
+ _reset_rate_limiter()
try:
yield server, database, user_id, username, token, campaign, server.app
finally:
@@ -4004,6 +4263,208 @@ class TestMainWebSocketAuthoritativeLifetime:
finally:
await _settle_main_websocket(key_socket, key_task)
+ @pytest.mark.asyncio
+ async def test_ticket_is_single_use_and_concurrent_handshake_has_one_winner(
+ self,
+ ws_runtime: Any,
+ ) -> None:
+ _, _, _, _, token, campaign, app = ws_runtime
+ ticket = await _issue_main_websocket_ticket(app, campaign.id, token=token)
+ first_socket, first_task = await _launch_main_websocket(
+ app, campaign.id, ticket=ticket
+ )
+ second_socket, second_task = await _launch_main_websocket(
+ app, campaign.id, ticket=ticket
+ )
+ try:
+ async def wait_for_outcome(socket: _MainWebSocketHarness) -> None:
+ accepted = asyncio.create_task(socket.accepted.wait())
+ closed = asyncio.create_task(socket.closed.wait())
+ done, pending = await asyncio.wait(
+ {accepted, closed},
+ return_when=asyncio.FIRST_COMPLETED,
+ )
+ for waiter in pending:
+ waiter.cancel()
+ await asyncio.gather(*pending, return_exceptions=True)
+ _require_fixed(bool(done), "expected a handshake outcome")
+
+ await _ws_wait(
+ asyncio.gather(
+ wait_for_outcome(first_socket),
+ wait_for_outcome(second_socket),
+ ),
+ "expected exactly one concurrent ticket winner",
+ )
+ accepted_count = sum(
+ socket.accepted.is_set() for socket in (first_socket, second_socket)
+ )
+ denied_count = sum(
+ socket.close_code == 4001 for socket in (first_socket, second_socket)
+ )
+ _require_fixed(
+ accepted_count == 1 and denied_count == 1,
+ "expected one accepted and one replay-denied handshake",
+ )
+ finally:
+ await _settle_main_websocket(first_socket, first_task)
+ await _settle_main_websocket(second_socket, second_task)
+
+ replay_socket, replay_task = await _launch_main_websocket(
+ app, campaign.id, ticket=ticket
+ )
+ await self._await_denied(replay_socket, replay_task, code=4001)
+
+ @pytest.mark.parametrize(
+ "query_string",
+ [
+ b"",
+ b"ticket=",
+ b"ticket=short",
+ b"ticket%3Dsynthetic",
+ b"%74icket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ b"ticket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%41",
+ b"ticket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&extra=1",
+ b"extra=1&ticket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ b"ticket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&ticket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ b"token=synthetic-legacy-value",
+ b"api_key=synthetic-legacy-value",
+ b"ticket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&token=legacy",
+ b"ticket=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&api_key=legacy",
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_ticket_query_parser_rejects_every_noncanonical_shape_before_db(
+ self,
+ ws_runtime: Any,
+ query_string: bytes,
+ ) -> None:
+ _, database, _, _, _, campaign, app = ws_runtime
+ consume_calls = [0]
+ original_consume = database.consume_websocket_ticket
+
+ async def tracked_consume(raw_ticket: str, campaign_id: str) -> Any:
+ consume_calls[0] += 1
+ return await original_consume(raw_ticket, campaign_id)
+
+ database.consume_websocket_ticket = tracked_consume # type: ignore[method-assign]
+ socket, task = await _launch_main_websocket(
+ app,
+ campaign.id,
+ query_string=query_string,
+ )
+ try:
+ await self._await_denied(socket, task, code=4001)
+ _require_fixed(
+ consume_calls[0] == 0 and socket.scope["query_string"] == b"",
+ "expected malformed query rejection after synchronous scrubbing",
+ )
+ finally:
+ database.consume_websocket_ticket = original_consume # type: ignore[method-assign]
+
+ @pytest.mark.asyncio
+ async def test_wrong_campaign_does_not_consume_ticket(
+ self,
+ ws_runtime: Any,
+ ) -> None:
+ from ares.core.campaign import Campaign
+
+ _, database, _, _, token, campaign, app = ws_runtime
+ other_campaign = Campaign(
+ name="Wrong Ticket Campaign",
+ operator="separate-owner",
+ )
+ await database.save_campaign(other_campaign)
+ ticket = await _issue_main_websocket_ticket(app, campaign.id, token=token)
+ wrong_socket, wrong_task = await _launch_main_websocket(
+ app, other_campaign.id, ticket=ticket
+ )
+ await self._await_denied(wrong_socket, wrong_task, code=4001)
+ correct_socket, correct_task = await _launch_main_websocket(
+ app, campaign.id, ticket=ticket
+ )
+ try:
+ await self._await_connected(correct_socket)
+ finally:
+ await _settle_main_websocket(correct_socket, correct_task)
+
+ @pytest.mark.asyncio
+ async def test_expired_ticket_and_consume_outage_use_fixed_close_codes(
+ self,
+ ws_runtime: Any,
+ ) -> None:
+ _, database, _, _, token, campaign, app = ws_runtime
+ expired_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
+ await database.conn.execute(
+ "UPDATE websocket_tickets SET created_at=?, expires_at=? "
+ "WHERE consumed_at IS NULL",
+ (
+ "1999-12-31T23:59:30.000Z",
+ "2000-01-01T00:00:00.000Z",
+ ),
+ )
+ await database.conn.commit()
+ expired_socket, expired_task = await _launch_main_websocket(
+ app, campaign.id, ticket=expired_ticket
+ )
+ await self._await_denied(expired_socket, expired_task, code=4001)
+
+ unavailable_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
+ original_consume = database.consume_websocket_ticket
+
+ async def fail_consume(_ticket: str, _campaign_id: str) -> Any:
+ raise ConnectionError
+
+ database.consume_websocket_ticket = fail_consume # type: ignore[method-assign]
+ try:
+ unavailable_socket, unavailable_task = await _launch_main_websocket(
+ app, campaign.id, ticket=unavailable_ticket
+ )
+ await self._await_denied(
+ unavailable_socket,
+ unavailable_task,
+ code=1013,
+ )
+ finally:
+ database.consume_websocket_ticket = original_consume # type: ignore[method-assign]
+
+ @pytest.mark.asyncio
+ async def test_failed_accept_keeps_ticket_consumed_and_fresh_ticket_recovers(
+ self,
+ ws_runtime: Any,
+ ) -> None:
+ _, _, _, _, token, campaign, app = ws_runtime
+ ticket = await _issue_main_websocket_ticket(app, campaign.id, token=token)
+ failed_socket, failed_task = await _launch_main_websocket(
+ app, campaign.id, ticket=ticket, fail_accept=True
+ )
+ failed_accept_observed = False
+ try:
+ await failed_task
+ except RuntimeError:
+ failed_accept_observed = True
+ _require_fixed(
+ failed_accept_observed,
+ "expected the synthetic accept failure to propagate",
+ )
+
+ replay_socket, replay_task = await _launch_main_websocket(
+ app, campaign.id, ticket=ticket
+ )
+ await self._await_denied(replay_socket, replay_task, code=4001)
+
+ recovered_socket, recovered_task = await _launch_main_websocket(
+ app, campaign.id, token=token
+ )
+ try:
+ await self._await_connected(recovered_socket)
+ finally:
+ await _settle_main_websocket(recovered_socket, recovered_task)
+
@pytest.mark.asyncio
async def test_bearer_handshake_denies_inactive_renamed_revoked_and_deleted(
self,
@@ -4011,6 +4472,9 @@ class TestMainWebSocketAuthoritativeLifetime:
) -> None:
_, database, user_id, username, token, campaign, app = ws_runtime
+ inactive_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
await database.conn.execute(
"UPDATE users SET is_active=0 WHERE id=?",
(user_id,),
@@ -4019,19 +4483,27 @@ class TestMainWebSocketAuthoritativeLifetime:
inactive_socket, inactive_task = await _launch_main_websocket(
app,
campaign.id,
- token=token,
+ ticket=inactive_ticket,
)
await self._await_denied(inactive_socket, inactive_task, code=4001)
await database.conn.execute(
- "UPDATE users SET is_active=1, username=? WHERE id=?",
+ "UPDATE users SET is_active=1 WHERE id=?",
+ (user_id,),
+ )
+ await database.conn.commit()
+ renamed_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
+ await database.conn.execute(
+ "UPDATE users SET username=? WHERE id=?",
("renamed-main-websocket-principal", user_id),
)
await database.conn.commit()
renamed_socket, renamed_task = await _launch_main_websocket(
app,
campaign.id,
- token=token,
+ ticket=renamed_ticket,
)
await self._await_denied(renamed_socket, renamed_task, code=4001)
@@ -4040,27 +4512,27 @@ class TestMainWebSocketAuthoritativeLifetime:
(username, user_id),
)
await database.conn.commit()
- import jwt
from datetime import datetime, timedelta, timezone
- settings = _settings()
- expired_token = jwt.encode(
- {
- "sub": username,
- "role": "team_lead",
- "jti": "synthetic-expired-websocket-marker",
- "exp": datetime.now(timezone.utc) - timedelta(minutes=1),
- },
- settings.secret_key_value,
- algorithm=settings.ares_jwt_algorithm,
+ expired_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
)
+ await database.conn.execute(
+ "UPDATE websocket_tickets SET bearer_expires_at=? "
+ "WHERE consumed_at IS NULL",
+ ("2000-01-01T00:00:00.000Z",),
+ )
+ await database.conn.commit()
expired_socket, expired_task = await _launch_main_websocket(
app,
campaign.id,
- token=expired_token,
+ ticket=expired_ticket,
)
await self._await_denied(expired_socket, expired_task, code=4001)
+ import jwt
+
+ settings = _settings()
revocation_marker = "synthetic-main-websocket-revocation"
revoked_token = jwt.encode(
{
@@ -4072,6 +4544,9 @@ class TestMainWebSocketAuthoritativeLifetime:
settings.secret_key_value,
algorithm=settings.ares_jwt_algorithm,
)
+ revoked_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=revoked_token
+ )
await database.revoke_access_token(
revocation_marker,
user_id,
@@ -4080,16 +4555,19 @@ class TestMainWebSocketAuthoritativeLifetime:
revoked_socket, revoked_task = await _launch_main_websocket(
app,
campaign.id,
- token=revoked_token,
+ ticket=revoked_ticket,
)
await self._await_denied(revoked_socket, revoked_task, code=4001)
+ deleted_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
await database.conn.execute("DELETE FROM users WHERE id=?", (user_id,))
await database.conn.commit()
deleted_socket, deleted_task = await _launch_main_websocket(
app,
campaign.id,
- token=token,
+ ticket=deleted_ticket,
)
await self._await_denied(deleted_socket, deleted_task, code=4001)
@@ -4099,6 +4577,7 @@ class TestMainWebSocketAuthoritativeLifetime:
ws_runtime: Any,
) -> None:
_, database, user_id, _, token, campaign, app = ws_runtime
+ ticket = await _issue_main_websocket_ticket(app, campaign.id, token=token)
await database.conn.execute(
"UPDATE users SET role='operator' WHERE id=?",
(user_id,),
@@ -4107,7 +4586,7 @@ class TestMainWebSocketAuthoritativeLifetime:
socket, task = await _launch_main_websocket(
app,
campaign.id,
- token=token,
+ ticket=ticket,
)
await self._await_denied(socket, task, code=4001)
@@ -4128,13 +4607,32 @@ class TestMainWebSocketAuthoritativeLifetime:
user_id,
"main-websocket-precedence-key",
)
- socket, task = await _launch_main_websocket(
+ verify_calls = [0]
+ original_verify = database.verify_api_key
+
+ async def tracked_verify(candidate: str) -> Any:
+ verify_calls[0] += 1
+ return await original_verify(candidate)
+
+ database.verify_api_key = tracked_verify # type: ignore[method-assign]
+ response = await _request_main_websocket_ticket(
app,
campaign.id,
token="synthetic.invalid.jwt",
api_key=raw_key,
)
- await self._await_denied(socket, task, code=4001)
+ database.verify_api_key = original_verify # type: ignore[method-assign]
+ _require_fixed(
+ response.status_code == 401 and verify_calls[0] == 0,
+ "expected bearer issuance failure to remain terminal",
+ )
+
+ legacy_socket, legacy_task = await _launch_main_websocket(
+ app,
+ campaign.id,
+ query_string=b"api_key=synthetic-legacy-value",
+ )
+ await self._await_denied(legacy_socket, legacy_task, code=4001)
@pytest.mark.asyncio
async def test_api_key_revocation_and_inactive_owner_deny_handshake(
@@ -4147,6 +4645,9 @@ class TestMainWebSocketAuthoritativeLifetime:
user_id,
"main-websocket-lifecycle-key",
)
+ revoked_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, api_key=raw_key
+ )
await database.conn.execute(
"UPDATE api_keys SET is_active=0 WHERE id=?",
(key_id,),
@@ -4155,7 +4656,7 @@ class TestMainWebSocketAuthoritativeLifetime:
revoked_socket, revoked_task = await _launch_main_websocket(
app,
campaign.id,
- api_key=raw_key,
+ ticket=revoked_ticket,
)
await self._await_denied(revoked_socket, revoked_task, code=4001)
@@ -4163,6 +4664,10 @@ class TestMainWebSocketAuthoritativeLifetime:
"UPDATE api_keys SET is_active=1 WHERE id=?",
(key_id,),
)
+ await database.conn.commit()
+ inactive_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, api_key=raw_key
+ )
await database.conn.execute(
"UPDATE users SET is_active=0 WHERE id=?",
(user_id,),
@@ -4171,7 +4676,7 @@ class TestMainWebSocketAuthoritativeLifetime:
inactive_socket, inactive_task = await _launch_main_websocket(
app,
campaign.id,
- api_key=raw_key,
+ ticket=inactive_ticket,
)
await self._await_denied(inactive_socket, inactive_task, code=4001)
@@ -4181,39 +4686,48 @@ class TestMainWebSocketAuthoritativeLifetime:
ws_runtime: Any,
) -> None:
_, database, _, _, token, campaign, app = ws_runtime
+ absent_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
app.state.db = None
absent_socket, absent_task = await _launch_main_websocket(
app,
campaign.id,
- token=token,
+ ticket=absent_ticket,
)
await self._await_denied(absent_socket, absent_task, code=1013)
app.state.db = database
+ closed_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
await database.close()
closed_socket, closed_task = await _launch_main_websocket(
app,
campaign.id,
- token=token,
+ ticket=closed_ticket,
)
await self._await_denied(closed_socket, closed_task, code=1013)
await database.connect()
- original_resolve = database.resolve_access_token_principal
+ failed_ticket = await _issue_main_websocket_ticket(
+ app, campaign.id, token=token
+ )
+ original_resolve = database.resolve_websocket_ticket_principal
- async def fail_lookup(_subject: str, _jti: str) -> Any:
+ async def fail_lookup(_handle: Any) -> Any:
raise TimeoutError
- database.resolve_access_token_principal = fail_lookup # type: ignore[method-assign]
+ database.resolve_websocket_ticket_principal = fail_lookup # type: ignore[method-assign]
try:
failed_socket, failed_task = await _launch_main_websocket(
app,
campaign.id,
- token=token,
+ ticket=failed_ticket,
)
await self._await_denied(failed_socket, failed_task, code=1013)
finally:
- database.resolve_access_token_principal = original_resolve # type: ignore[method-assign]
+ database.resolve_websocket_ticket_principal = original_resolve # type: ignore[method-assign]
recovered_socket, recovered_task = await _launch_main_websocket(
app,
@@ -4234,7 +4748,6 @@ class TestMainWebSocketAuthoritativeLifetime:
self,
ws_runtime: Any,
state_change: str,
- monkeypatch: Any,
) -> None:
server, database, user_id, username, token, campaign, app = ws_runtime
socket, task = await _launch_main_websocket(
@@ -4284,18 +4797,18 @@ class TestMainWebSocketAuthoritativeLifetime:
(datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(),
)
elif state_change == "expired":
- import jwt.api_jwt
- from datetime import datetime, timedelta, timezone
-
- real_datetime = datetime
-
- class FutureDateTime(datetime):
- @classmethod
- def now(cls, tz: Any = None) -> datetime:
- current = real_datetime.now(timezone.utc) + timedelta(days=2)
- return current if tz is not None else current.replace(tzinfo=None)
+ from dataclasses import replace
+ from datetime import datetime, timezone
- monkeypatch.setattr(jwt.api_jwt, "datetime", FutureDateTime)
+ contexts = list(server._ws_connections.get(campaign.id, set()))
+ _require_fixed(
+ len(contexts) == 1,
+ "expected one registered ticket handle",
+ )
+ contexts[0].ticket_handle = replace(
+ contexts[0].ticket_handle,
+ bearer_expires_at=datetime(2000, 1, 1, tzinfo=timezone.utc),
+ )
else:
await database.conn.execute(
"UPDATE users SET role='operator' WHERE id=?",
@@ -4324,7 +4837,10 @@ class TestMainWebSocketAuthoritativeLifetime:
finally:
await _settle_main_websocket(socket, task)
- @pytest.mark.parametrize("state_change", ["revoked", "inactive", "ownership"])
+ @pytest.mark.parametrize(
+ "state_change",
+ ["revoked", "inactive", "ownership", "scope", "expired", "key_owner"],
+ )
@pytest.mark.asyncio
async def test_api_key_and_ownership_lifetime_revalidation(
self,
@@ -4363,11 +4879,32 @@ class TestMainWebSocketAuthoritativeLifetime:
"UPDATE users SET is_active=0 WHERE id=?",
(user_id,),
)
- else:
+ elif state_change == "ownership":
await database.conn.execute(
"UPDATE campaigns SET operator=? WHERE id=?",
("different-campaign-owner", campaign.id),
)
+ elif state_change == "scope":
+ await database.conn.execute(
+ "UPDATE api_keys SET scopes='none' WHERE id=?",
+ (key_id,),
+ )
+ elif state_change == "expired":
+ await database.conn.execute(
+ "UPDATE api_keys SET expires_at=? WHERE id=?",
+ ("2000-01-01T00:00:00+00:00", key_id),
+ )
+ else:
+ with patch("ares.db.database.logger.info"):
+ replacement_user_id = await database.create_user(
+ "main-websocket-key-owner",
+ "SyntheticKeyOwnerPass1!",
+ "team_lead",
+ )
+ await database.conn.execute(
+ "UPDATE api_keys SET user_id=? WHERE id=?",
+ (replacement_user_id, key_id),
+ )
await database.conn.commit()
await server._broadcast_event(
@@ -4425,6 +4962,116 @@ class TestMainWebSocketAuthoritativeLifetime:
finally:
await _settle_main_websocket(socket, task)
+ @pytest.mark.asyncio
+ async def test_pong_revalidates_without_broadcast(
+ self,
+ ws_runtime: Any,
+ ) -> None:
+ server, database, user_id, _, token, campaign, app = ws_runtime
+ socket, task = await _launch_main_websocket(
+ app,
+ campaign.id,
+ token=token,
+ )
+ try:
+ await self._await_connected(socket)
+ await database.conn.execute(
+ "UPDATE users SET is_active=0 WHERE id=?",
+ (user_id,),
+ )
+ await database.conn.commit()
+ await socket.inbound.put("ping")
+ await _ws_wait(
+ socket.closed.wait(),
+ "expected pong authorization loss to close the connection",
+ )
+ _require_fixed(
+ socket.close_code == 4001
+ and socket.sent_types == ["connected"]
+ and not server._ws_connections.get(campaign.id),
+ "expected principal revalidation before pong delivery",
+ )
+ finally:
+ await _settle_main_websocket(socket, task)
+
+ @pytest.mark.asyncio
+ async def test_consumed_handle_survives_ticket_expiry_and_purge_read_only(
+ self,
+ ws_runtime: Any,
+ ) -> None:
+ server, database, user_id, username, _, campaign, app = ws_runtime
+ await database.conn.execute(
+ "UPDATE users SET role='operator' WHERE id=?",
+ (user_id,),
+ )
+ await database.conn.execute(
+ "UPDATE campaigns SET operator=? WHERE id=?",
+ (username, campaign.id),
+ )
+ await database.conn.commit()
+ with patch("ares.db.database.logger.info"):
+ key_id, raw_key = await database.create_api_key(
+ user_id,
+ "read-only-lifetime-key",
+ scopes="read",
+ )
+ socket, task = await _launch_main_websocket(
+ app,
+ campaign.id,
+ api_key=raw_key,
+ )
+ try:
+ await self._await_connected(socket)
+ async with database.conn.execute(
+ "SELECT last_used FROM api_keys WHERE id=?",
+ (key_id,),
+ ) as cursor:
+ last_used_before = (await cursor.fetchone())[0]
+ await database.conn.execute(
+ "UPDATE websocket_tickets "
+ "SET created_at=?, consumed_at=?, expires_at=?",
+ (
+ "1999-12-31T23:59:00.000Z",
+ "1999-12-31T23:59:15.000Z",
+ "1999-12-31T23:59:30.000Z",
+ ),
+ )
+ await database.conn.commit()
+ await database.purge_expired_websocket_tickets()
+ await server._broadcast_event(
+ campaign.id,
+ {"type": "module_complete"},
+ )
+ await server._broadcast_event(
+ campaign.id,
+ {"type": "strategy_update"},
+ )
+ first = await _ws_wait(
+ socket.sent.get(),
+ "expected module event after ticket purge",
+ )
+ second = await _ws_wait(
+ socket.sent.get(),
+ "expected strategy event after ticket purge",
+ )
+ async with database.conn.execute(
+ "SELECT last_used FROM api_keys WHERE id=?",
+ (key_id,),
+ ) as cursor:
+ last_used_after = (await cursor.fetchone())[0]
+ async with database.conn.execute(
+ "SELECT COUNT(*) FROM websocket_tickets"
+ ) as cursor:
+ ticket_rows = int((await cursor.fetchone())[0])
+ _require_fixed(
+ (first, second) == ("module_complete", "strategy_update")
+ and ticket_rows == 0
+ and last_used_before == last_used_after,
+ "expected purged handle authority with read-only API-key resolution",
+ )
+ finally:
+ await _settle_main_websocket(socket, task)
+
@pytest.mark.asyncio
async def test_delayed_authoritative_lookup_observes_committed_invalidation(
self,
@@ -4438,19 +5085,19 @@ class TestMainWebSocketAuthoritativeLifetime:
)
lookup_started = asyncio.Event()
lookup_release = asyncio.Event()
- original_resolve = database.resolve_access_token_principal
+ original_resolve = database.resolve_websocket_ticket_principal
- async def delayed_resolve(subject: str, jti: str) -> Any:
+ async def delayed_resolve(handle: Any) -> Any:
lookup_started.set()
await _ws_wait(
lookup_release.wait(),
"expected authoritative lookup barrier release",
)
- return await original_resolve(subject, jti)
+ return await original_resolve(handle)
try:
await self._await_connected(socket)
- database.resolve_access_token_principal = delayed_resolve # type: ignore[method-assign]
+ database.resolve_websocket_ticket_principal = delayed_resolve # type: ignore[method-assign]
broadcast_task = asyncio.create_task(
server._broadcast_event(
campaign.id,
@@ -4483,7 +5130,7 @@ class TestMainWebSocketAuthoritativeLifetime:
)
finally:
lookup_release.set()
- database.resolve_access_token_principal = original_resolve # type: ignore[method-assign]
+ database.resolve_websocket_ticket_principal = original_resolve # type: ignore[method-assign]
await _settle_main_websocket(socket, task)
@pytest.mark.asyncio
@@ -4497,14 +5144,14 @@ class TestMainWebSocketAuthoritativeLifetime:
campaign.id,
token=token,
)
- original_resolve = database.resolve_access_token_principal
+ original_resolve = database.resolve_websocket_ticket_principal
- async def fail_lookup(_subject: str, _jti: str) -> Any:
+ async def fail_lookup(_handle: Any) -> Any:
raise ConnectionError
try:
await self._await_connected(socket)
- database.resolve_access_token_principal = fail_lookup # type: ignore[method-assign]
+ database.resolve_websocket_ticket_principal = fail_lookup # type: ignore[method-assign]
await server._broadcast_event(
campaign.id,
{"type": "synthetic_protected_event"},
@@ -4524,7 +5171,7 @@ class TestMainWebSocketAuthoritativeLifetime:
"expected backend outage to prevent protected delivery with 1013",
)
finally:
- database.resolve_access_token_principal = original_resolve # type: ignore[method-assign]
+ database.resolve_websocket_ticket_principal = original_resolve # type: ignore[method-assign]
await _settle_main_websocket(socket, task)
recovered_socket, recovered_task = await _launch_main_websocket(
diff --git a/tests/unit/test_security_critical.py b/tests/unit/test_security_critical.py
index 4663d12..b3dc1d9 100644
--- a/tests/unit/test_security_critical.py
+++ b/tests/unit/test_security_critical.py
@@ -18,9 +18,10 @@ from __future__ import annotations
import asyncio
import os
-import pytest
from unittest.mock import AsyncMock, MagicMock
+import pytest
+
# ── env bootstrap (before any ares import) ────────────────────────────────────
os.environ.setdefault("ARES_SECRET_KEY", "test-sec-critical-min32-chars!!!!")
os.environ.setdefault("ARES_ENCRYPTION_KEY", "test-enc-critical-min32-chars!!!!")
@@ -98,6 +99,106 @@ def _run(coro):
return asyncio.run(coro)
+class _ReducedUvicornLogProbe:
+ def __init__(self, marker: str) -> None:
+ self._marker = marker
+ self.calls = 0
+ self.marker_absent = True
+
+ def info(self, template: str, *args: object) -> None:
+ self.calls += 1
+ rendered = template % args
+ self.marker_absent = self.marker_absent and self._marker not in rendered
+
+
+def _uvicorn_protocol_probe(scope: dict, marker: str):
+ from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol
+
+ protocol = object.__new__(WebSocketProtocol)
+ protocol.scope = scope
+ protocol.logger = _ReducedUvicornLogProbe(marker)
+ protocol.handshake_started_event = asyncio.Event()
+ protocol.handshake_completed_event = asyncio.Event()
+ protocol.closed_event = asyncio.Event()
+ protocol.initial_response = None
+ protocol.accepted_subprotocol = None
+ protocol.extra_headers = []
+ return protocol
+
+
+def test_main_websocket_scrubs_query_before_actual_uvicorn_logging():
+ import ast
+ import inspect
+ import textwrap
+ import warnings
+
+ from ares.api.server import campaign_events, _take_campaign_websocket_ticket
+ from uvicorn.config import UvicornDeprecationWarning
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ warnings.simplefilter("ignore", UvicornDeprecationWarning)
+ from uvicorn.protocols.websockets.websockets_impl import WebSocketProtocol
+
+ marker = "A" * 43
+ scope = {
+ "type": "websocket",
+ "path": "/ws/campaigns/synthetic/events",
+ "query_string": f"ticket={marker}".encode("ascii"),
+ "client": ("127.0.0.1", 1),
+ }
+ websocket = MagicMock()
+ websocket.scope = scope
+ parsed = _take_campaign_websocket_ticket(websocket)
+ parsed_canonical = isinstance(parsed, str) and len(parsed) == 43
+ query_scrubbed = scope["query_string"] == b""
+
+ async def exercise() -> tuple[int, bool]:
+ accepted = _uvicorn_protocol_probe(scope, marker)
+ await WebSocketProtocol.asgi_send(
+ accepted,
+ {"type": "websocket.accept"},
+ )
+ denied = _uvicorn_protocol_probe(scope, marker)
+ await WebSocketProtocol.asgi_send(
+ denied,
+ {"type": "websocket.close", "code": 4001},
+ )
+ return (
+ accepted.logger.calls + denied.logger.calls,
+ accepted.logger.marker_absent and denied.logger.marker_absent,
+ )
+
+ call_count, marker_absent = _run(exercise())
+ route_body = ast.parse(textwrap.dedent(inspect.getsource(campaign_events))).body[0].body
+ helper_body = ast.parse(
+ textwrap.dedent(inspect.getsource(_take_campaign_websocket_ticket))
+ ).body[0].body
+ route_first_operation_is_scrub = (
+ isinstance(route_body[1], ast.Assign)
+ and isinstance(route_body[1].value, ast.Call)
+ and isinstance(route_body[1].value.func, ast.Name)
+ and route_body[1].value.func.id == "_take_campaign_websocket_ticket"
+ )
+ helper_scrubs_before_validation = (
+ isinstance(helper_body[1], ast.Assign)
+ and isinstance(helper_body[2], ast.Assign)
+ and isinstance(helper_body[3], ast.AnnAssign)
+ and isinstance(helper_body[4], ast.Try)
+ )
+ if not (
+ parsed_canonical
+ and query_scrubbed
+ and call_count == 2
+ and marker_absent
+ and route_first_operation_is_scrub
+ and helper_scrubs_before_validation
+ ):
+ pytest.fail(
+ "WebSocket query must be scrubbed before Uvicorn handshake logging.",
+ pytrace=False,
+ )
+
+
# ══════════════════════════════════════════════════════════════════════
# TEST CLASS 1 — TOKEN REVOCATION
# ══════════════════════════════════════════════════════════════════════