Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
fix(security): authenticate WS/SSE realtime connections via short-lived tickets (#239) (#246)
Beenu Arora08123f9e1772
diff --git a/.env.example b/.env.exampleindex 2e6822b19..d48f156d5 100644--- a/.env.example+++ b/.env.example@@ -28,6 +28,24 @@ ENVIRONMENT=developmentLOG_LEVEL=infoSECRET_KEY=change-this-to-a-random-secret-key-at-least-32-chars+# Shared HS256 secret used ONLY for short-lived realtime WS/SSE tickets+# (Issue #239). The API mints tickets at `POST /api/v1/realtime/ticket` and the+# Node realtime service (`services/realtime`) verifies them on every WebSocket+# upgrade and SSE request — both sides MUST read the same value. This is+# intentionally separate from SECRET_KEY so the realtime edge can be rotated+# independently and a leaked ticket can never forge a full API session.+#+# Leave blank in development: both services fall back to a well-known dev secret+# so docker-compose "just works". In production you MUST set a real value —+# the ticket endpoint fails closed (503) and the realtime service rejects every+# connection until this is wired. Generate with:+# python -c "import secrets; print(secrets.token_hex(32))"+AISOC_REALTIME_JWT_SECRET=+# Time-to-live (seconds) for minted realtime tickets. Kept short so a leaked+# ticket is only briefly useful; the frontend re-mints on every (re)connect.+# Clamped to a 60s ceiling by the ticket endpoint regardless of this value.+AISOC_REALTIME_TICKET_TTL_SECONDS=60+# Application-layer encryption key for connector credentials and other# secret payloads stored in Postgres. Generate with:# python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsxindex 3c35198b0..3d347094a 100644--- a/apps/web/src/components/cases/CaseWorkspace.tsx+++ b/apps/web/src/components/cases/CaseWorkspace.tsx@@ -25,6 +25,7 @@ import toast from 'react-hot-toast';import {casesApi,graphApi,+ realtimeApi,type AttackChainTimeline,type AttackChainWindow,type Case,@@ -363,17 +364,29 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {useEffect(() => () => { stopPolling(); closeWs(); }, [stopPolling, closeWs]);/** Connect to the realtime service WebSocket for this run_id */- const connectWs = useCallback((runId: string, tenantId = 'default') => {+ const connectWs = useCallback((runId: string) => {closeWs();- // Determine WS URL: same host, realtime port or proxied- const wsProto = window.location.protocol === 'https:' ? 'wss' : 'ws';- // The Next.js dev server proxies /ws → realtime service on :8086- // In production, nginx handles the proxy.- const wsUrl = `${wsProto}://${window.location.host}/ws/agents?tenant_id=${tenantId}`;- try {- const ws = new WebSocket(wsUrl);- wsRef.current = ws;- ws.onmessage = (evt) => {+ // Mint a short-lived ticket and attach it as `?token=` before opening the+ // socket (Issue #239). The realtime service rejects tokenless upgrades and+ // derives the tenant from the verified claim, so we no longer send a+ // client-chosen `tenant_id`. On failure (signed-out / ticketing not+ // configured) we silently fall back to the polling loop already running.+ void (async () => {+ let token: string;+ try {+ ({ token } = await realtimeApi.ticket());+ } catch {+ // Could not authenticate — polling fallback covers live updates.+ return;+ }+ const wsProto = window.location.protocol === 'https:' ? 'wss' : 'ws';+ // The Next.js dev server proxies /ws → realtime service on :8086.+ // In production, nginx handles the proxy.+ const wsUrl = `${wsProto}://${window.location.host}/ws/agents?token=${encodeURIComponent(token)}`;+ try {+ const ws = new WebSocket(wsUrl);+ wsRef.current = ws;+ ws.onmessage = (evt) => {try {const msg = JSON.parse(evt.data as string) as Record<string, unknown>;const msgRunId = msg.run_id as string | undefined;@@ -416,9 +429,10 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {ws.close();wsRef.current = null;};- } catch {- // WebSocket not available — polling fallback is already running- }+ } catch {+ // WebSocket not available — polling fallback is already running+ }+ })();}, [caseId, closeWs]);const startInvestigation = useCallback(async () => {diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 2f2d6bc72..b4881484a 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -5115,10 +5115,46 @@ export const savedViewsApi = {// ─── Realtime / WebSocket helpers ────────────────────────────────────────────+export interface RealtimeTicket {+ token: string;+ expires_in: number;+ tenant_id: string;+}+export const realtimeApi = {- /** Returns a ready-to-open WebSocket URL for the given channel. */- channelUrl(channel: 'alerts' | 'cases' | 'agents' | 'insights' | 'all') {- return `${wsOrigin()}/ws/${channel}?tenant_id=${encodeURIComponent(TENANT_ID)}`;+ /**+ * Mint a short-lived (≤60s), audience-scoped HS256 ticket for the realtime+ * WS/SSE edge (Issue #239). This authenticated call uses the caller's session+ * Bearer token (attached automatically by `request`); the API derives the+ * tenant server-side, so the browser never chooses its own tenant. The+ * returned `token` is appended as `?token=` to the WS/SSE URL immediately+ * before connecting and re-fetched on every (re)connect since it expires fast.+ */+ ticket: () =>+ request<RealtimeTicket>('/api/v1/realtime/ticket', { method: 'POST' }),++ /**+ * Returns a ready-to-open WebSocket URL for the given channel, with a freshly+ * minted ticket attached as `?token=`. Async because it must authenticate+ * (mint a ticket) first — the realtime service rejects tokenless upgrades.+ * The tenant is derived from the verified ticket claim server-side, so we no+ * longer pass (untrusted) `tenant_id` in the query string.+ */+ async channelUrl(+ channel: 'alerts' | 'cases' | 'agents' | 'insights' | 'all',+ ): Promise<string> {+ const { token } = await realtimeApi.ticket();+ return `${wsOrigin()}/ws/${channel}?token=${encodeURIComponent(token)}`;+ },++ /**+ * Returns a ready-to-open SSE URL with a freshly minted ticket attached as+ * `?token=`. Mirrors `channelUrl` for the EventSource transport.+ */+ async sseUrl(): Promise<string> {+ const { token } = await realtimeApi.ticket();+ const base = REALTIME_BASE || '';+ return `${base}/sse?token=${encodeURIComponent(token)}`;},/**diff --git a/apps/web/src/lib/realtime.ts b/apps/web/src/lib/realtime.tsindex f4880d113..44c167154 100644--- a/apps/web/src/lib/realtime.ts+++ b/apps/web/src/lib/realtime.ts@@ -60,11 +60,31 @@ export function useRealtimeChannel<T = unknown>(if (!enabled || typeof window === 'undefined') return;cancelRef.current = false;- function connect() {+ async function connect() {if (cancelRef.current) return;- const target = url ?? realtimeApi.channelUrl(channel);setStatus('connecting');+ // Mint a fresh short-lived ticket and attach it as `?token=` immediately+ // before opening the socket (Issue #239). On reconnect this re-mints, so+ // an expired ticket never blocks recovery. A test-supplied `url` override+ // bypasses ticketing.+ let target: string;+ try {+ target = url ?? (await realtimeApi.channelUrl(channel));+ } catch {+ // Could not authenticate (e.g. signed-out, or realtime ticketing is+ // not configured server-side → 503). Surface as error and retry with+ // backoff rather than opening an unauthenticated socket.+ if (cancelRef.current) return;+ setStatus('error');+ const attempt = reconnectRef.current + 1;+ reconnectRef.current = attempt;+ const delay = Math.min(1000 * 2 ** Math.min(attempt, 6), maxBackoffMs);+ window.setTimeout(connect, delay);+ return;+ }+ if (cancelRef.current) return;+const ws = new WebSocket(target);wsRef.current = ws;diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex e55f92f99..90bb4d9fd 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -12685,6 +12685,29 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/realtime/ticket:+ post:+ tags:+ - realtime+ summary: Mint Realtime Ticket+ description: 'Mint a short-lived ticket for the realtime WS/SSE edge.+++ Requires a valid session (``get_current_user`` 401s otherwise). The ticket''s++ tenant is bound server-side from the authenticated user — the client cannot++ request a tenant.'+ operationId: mint_realtime_ticket_api_v1_realtime_ticket_post+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RealtimeTicket'+ security:+ - HTTPBearer: []/auth/saml/login:get:tags:@@ -21961,6 +21984,27 @@ components:required:- scoretitle: RatingIn+ RealtimeTicket:+ properties:+ token:+ type: string+ title: Token+ description: Signed HS256 ticket for the WS/SSE edge.+ expires_in:+ type: integer+ title: Expires In+ description: Ticket lifetime in seconds.+ tenant_id:+ type: string+ title: Tenant Id+ description: Tenant the ticket is scoped to.+ type: object+ required:+ - token+ - expires_in+ - tenant_id+ title: RealtimeTicket+ description: Response body for ``POST /realtime/ticket``.RecommendedAction:properties:priority:diff --git a/infra/terraform/azure/container_apps.tf b/infra/terraform/azure/container_apps.tfindex 688129495..a5ccbedb1 100644--- a/infra/terraform/azure/container_apps.tf+++ b/infra/terraform/azure/container_apps.tf@@ -64,6 +64,14 @@ resource "azurerm_container_app" "api" {identity = azurerm_user_assigned_identity.api.idkey_vault_secret_id = azurerm_key_vault_secret.credential_key.id}+ # Shared HS256 secret the API uses to mint realtime WS/SSE tickets (Issue+ # #239). The Node realtime workload (an always-on Container App / AKS in the+ # follow-up plan) reads the same Key Vault entry to verify them.+ secret {+ name = "realtime-jwt-secret"+ identity = azurerm_user_assigned_identity.api.id+ key_vault_secret_id = azurerm_key_vault_secret.realtime_jwt_secret.id+ }secret {name = "redis-auth"identity = azurerm_user_assigned_identity.api.id@@ -158,6 +166,10 @@ resource "azurerm_container_app" "api" {name = "AISOC_CREDENTIAL_KEY"secret_name = "credential-key"}+ env {+ name = "AISOC_REALTIME_JWT_SECRET"+ secret_name = "realtime-jwt-secret"+ }env {name = "REDIS_PASSWORD"secret_name = "redis-auth"diff --git a/infra/terraform/azure/outputs.tf b/infra/terraform/azure/outputs.tfindex 3bfea7978..a7f3c46a3 100644--- a/infra/terraform/azure/outputs.tf+++ b/infra/terraform/azure/outputs.tf@@ -88,3 +88,8 @@ output "key_vault_uri" {description = "Vault URI for ad-hoc `az keyvault secret show` after apply."value = azurerm_key_vault.main.vault_uri}++output "realtime_jwt_secret_name" {+ description = "Key Vault secret name for the shared realtime WS/SSE ticket secret (Issue #239). Wire this into the realtime workload (always-on Container App / AKS follow-up) as AISOC_REALTIME_JWT_SECRET so it verifies the same tickets the API mints."+ value = azurerm_key_vault_secret.realtime_jwt_secret.name+}diff --git a/infra/terraform/azure/secrets.tf b/infra/terraform/azure/secrets.tfindex 372d4df40..ab7729778 100644--- a/infra/terraform/azure/secrets.tf+++ b/infra/terraform/azure/secrets.tf@@ -30,6 +30,15 @@ resource "random_password" "credential_key" {min_numeric = 1}+resource "random_password" "realtime_jwt_secret" {+ # Shared HS256 secret for short-lived realtime WS/SSE tickets (Issue #239).+ # The API mints tickets at POST /api/v1/realtime/ticket; the Node realtime+ # service verifies them. Kept separate from secret_key so the realtime edge+ # rotates independently and a leaked ticket can't forge a full API session.+ length = 64+ special = false+}+# ─── Key Vault ───────────────────────────────────────────────────────────────## RBAC-authorization mode (no access policies). The deploying principal gets@@ -101,6 +110,15 @@ resource "azurerm_key_vault_secret" "credential_key" {depends_on = [azurerm_role_assignment.deployer_secrets_officer]}+resource "azurerm_key_vault_secret" "realtime_jwt_secret" {+ name = "realtime-jwt-secret"+ value = random_password.realtime_jwt_secret.result+ key_vault_id = azurerm_key_vault.main.id+ tags = var.tags++ depends_on = [azurerm_role_assignment.deployer_secrets_officer]+}+resource "azurerm_key_vault_secret" "redis_auth" {name = "redis-auth"value = azurerm_redis_cache.main.primary_access_keydiff --git a/infra/terraform/environments/managed/outputs.tf b/infra/terraform/environments/managed/outputs.tfindex 695d8ac7a..fe4502b0d 100644--- a/infra/terraform/environments/managed/outputs.tf+++ b/infra/terraform/environments/managed/outputs.tf@@ -109,10 +109,16 @@ output "bootstrap_checklist" {3. Set the Slack sales-channel webhook used by /v1/waitlist/signup:fly secrets set AISOC_WAITLIST_SLACK_WEBHOOK=<your webhook> -a ${fly_app.control_plane.name}- 4. Deploy the AiSOC images:+ 4. Set the shared realtime WS/SSE ticket secret (Issue #239). The API+ mints short-TTL tickets and the realtime process group verifies them,+ so both must read the SAME value. Generate one 32-byte secret and set+ it once — Fly fans it out to every process group in the app:+ fly secrets set AISOC_REALTIME_JWT_SECRET=$(python -c 'import secrets; print(secrets.token_hex(32))') -a ${fly_app.control_plane.name}++ 5. Deploy the AiSOC images:fly deploy --app ${fly_app.control_plane.name}- 5. Verify the public URL responds:+ 6. Verify the public URL responds:curl -sSf https://${var.app_hostname}/healthThe Redis URL is exposed as a `sensitive` output — surface it withdiff --git a/infra/terraform/gcp/cloud_run.tf b/infra/terraform/gcp/cloud_run.tfindex 9f4bff50f..99e408d67 100644--- a/infra/terraform/gcp/cloud_run.tf+++ b/infra/terraform/gcp/cloud_run.tf@@ -141,6 +141,20 @@ resource "google_cloud_run_v2_service" "api" {}}}+ # Shared HS256 secret the API uses to mint realtime WS/SSE tickets+ # (Issue #239). The Node realtime service reads the same secret value to+ # verify them. The realtime workload itself isn't on Cloud Run (see the+ # header note), so it consumes this from the same Secret Manager entry+ # when deployed on its managed instance group / GKE follow-up.+ env {+ name = "AISOC_REALTIME_JWT_SECRET"+ value_source {+ secret_key_ref {+ secret = google_secret_manager_secret.realtime_jwt_secret.secret_id+ version = "latest"+ }+ }+ }env {name = "REDIS_PASSWORD"value_source {diff --git a/infra/terraform/gcp/iam.tf b/infra/terraform/gcp/iam.tfindex d55024620..c62ea36b4 100644--- a/infra/terraform/gcp/iam.tf+++ b/infra/terraform/gcp/iam.tf@@ -78,6 +78,7 @@ locals {google_secret_manager_secret.postgres_password.id,google_secret_manager_secret.secret_key.id,google_secret_manager_secret.credential_key.id,+ google_secret_manager_secret.realtime_jwt_secret.id,google_secret_manager_secret.redis_auth.id,],google_secret_manager_secret.openai_api_key[*].id,diff --git a/infra/terraform/gcp/outputs.tf b/infra/terraform/gcp/outputs.tfindex df8ef6434..6fea1b663 100644--- a/infra/terraform/gcp/outputs.tf+++ b/infra/terraform/gcp/outputs.tf@@ -107,6 +107,11 @@ output "secret_redis_auth_id" {value = google_secret_manager_secret.redis_auth.secret_id}+output "secret_realtime_jwt_secret_id" {+ description = "Secret Manager ID for the shared realtime WS/SSE ticket secret (Issue #239). Wire this into the realtime workload (managed instance group / GKE) as AISOC_REALTIME_JWT_SECRET so it verifies the same tickets the API mints."+ value = google_secret_manager_secret.realtime_jwt_secret.secret_id+}+output "secret_openai_api_key_id" {description = "Secret Manager ID for the OpenAI API key (null when not provisioned)."value = nonsensitive(diff --git a/infra/terraform/gcp/secrets.tf b/infra/terraform/gcp/secrets.tfindex 27de84eee..556b0cb5c 100644--- a/infra/terraform/gcp/secrets.tf+++ b/infra/terraform/gcp/secrets.tf@@ -29,6 +29,16 @@ resource "random_password" "credential_key" {min_numeric = 1}+resource "random_password" "realtime_jwt_secret" {+ # Shared HS256 secret for short-lived realtime WS/SSE tickets (Issue #239).+ # The API mints tickets at POST /api/v1/realtime/ticket; the Node realtime+ # service verifies them on every upgrade. Kept separate from secret_key so the+ # realtime edge rotates independently and a leaked ticket can't forge a full+ # API session.+ length = 64+ special = false+}+# ─── Secret Manager secrets ──────────────────────────────────────────────────resource "google_secret_manager_secret" "postgres_password" {@@ -79,6 +89,22 @@ resource "google_secret_manager_secret_version" "credential_key" {secret_data = base64encode(random_password.credential_key.result)}+resource "google_secret_manager_secret" "realtime_jwt_secret" {+ secret_id = "${var.name_prefix}-realtime-jwt-secret"+ labels = var.labels++ replication {+ auto {}+ }++ depends_on = [google_project_service.enabled]+}++resource "google_secret_manager_secret_version" "realtime_jwt_secret" {+ secret = google_secret_manager_secret.realtime_jwt_secret.id+ secret_data = random_password.realtime_jwt_secret.result+}+resource "google_secret_manager_secret" "redis_auth" {secret_id = "${var.name_prefix}-redis-auth"labels = var.labelsdiff --git a/services/api/app/api/v1/endpoints/realtime.py b/services/api/app/api/v1/endpoints/realtime.pynew file mode 100644index 000000000..df5a12e15--- /dev/null+++ b/services/api/app/api/v1/endpoints/realtime.py@@ -0,0 +1,77 @@+"""Short-lived ticket minting for the realtime WS/SSE edge — Issue #239.++The Node realtime service (``services/realtime``) fans out case/graph events+over WebSocket and SSE. Browsers cannot attach an ``Authorization`` header to a+WS upgrade, so instead of letting the realtime edge accept *any* connection+(the broken-access-control bug this endpoint closes), the flow is:++ 1. The authenticated SPA calls ``POST /api/v1/realtime/ticket`` with its+ normal session bearer token.+ 2. This endpoint mints a short-TTL (≤60s), audience-scoped HS256 ticket+ signed with the **shared realtime secret** (``AISOC_REALTIME_JWT_SECRET``+ or the dev fallback) — deliberately *not* ``SECRET_KEY``.+ 3. The SPA appends the ticket as ``?token=`` on the WS/SSE URL.+ 4. The realtime service verifies signature + ``aud`` + ``exp`` and derives the+ subscription ``tenant_id`` from the verified claim, so a browser can never+ subscribe to another tenant.++Fail-closed: outside a development-class environment, if the shared secret is+unset or set to a known insecure placeholder, ``realtime_ticket_secret`` returns+``None`` and we 503 rather than minting a ticket nobody can verify.+"""++from __future__ import annotations++from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException, status+from pydantic import BaseModel, Field++from app.api.v1.deps import CurrentUser, get_current_user+from app.core.config import realtime_ticket_secret, settings+from app.core.security import create_realtime_ticket++router = APIRouter(prefix="/realtime", tags=["realtime"])++# Hard ceiling on ticket lifetime regardless of configuration, so a+# misconfigured ``AISOC_REALTIME_TICKET_TTL_SECONDS`` can never mint a+# long-lived bearer that survives session revocation for minutes.+_MAX_TICKET_TTL_SECONDS = 60+++class RealtimeTicket(BaseModel):+ """Response body for ``POST /realtime/ticket``."""++ token: str = Field(..., description="Signed HS256 ticket for the WS/SSE edge.")+ expires_in: int = Field(..., description="Ticket lifetime in seconds.")+ tenant_id: str = Field(..., description="Tenant the ticket is scoped to.")++[email protected]("/ticket", response_model=RealtimeTicket)+async def mint_realtime_ticket(+ current_user: Annotated[CurrentUser, Depends(get_current_user)],+) -> RealtimeTicket:+ """Mint a short-lived ticket for the realtime WS/SSE edge.++ Requires a valid session (``get_current_user`` 401s otherwise). The ticket's+ tenant is bound server-side from the authenticated user — the client cannot+ request a tenant.+ """+ secret = realtime_ticket_secret(settings)+ if secret is None:+ # Production with the shared secret unset/insecure: fail closed rather+ # than mint a ticket the realtime verifier will reject anyway.+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail=("Realtime ticket signing is not configured. Set AISOC_REALTIME_JWT_SECRET " "to enable WS/SSE connections."),+ )++ ttl = max(1, min(settings.AISOC_REALTIME_TICKET_TTL_SECONDS, _MAX_TICKET_TTL_SECONDS))+ tenant_id = str(current_user.tenant_id)+ token = create_realtime_ticket(+ secret=secret,+ tenant_id=tenant_id,+ user_id=str(current_user.user_id),+ ttl_seconds=ttl,+ )+ return RealtimeTicket(token=token, expires_in=ttl, tenant_id=tenant_id)diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.pyindex 9921bbb37..e3c30ec1a 100644--- a/services/api/app/api/v1/router.py+++ b/services/api/app/api/v1/router.py@@ -59,6 +59,7 @@ from app.api.v1.endpoints import (posture,push,rbac,+ realtime,remediation,reports,rule_tuning,@@ -285,3 +286,11 @@ api_router.include_router(tenant_provision.router)# broadcaster (AISOC_INGEST_GRAPH_WS_URL). Backs the RealtimeGraph# Cytoscape view; gates on graph:read.api_router.include_router(graph_ws.router)++# Short-lived realtime WS/SSE ticket minting — Issue #239.+# POST /realtime/ticket authenticates the browser's session token and mints a+# short-TTL (≤60s), audience-scoped HS256 ticket signed with the shared+# AISOC_REALTIME_JWT_SECRET. The Node realtime service verifies it on every WS+# upgrade and SSE request, deriving the tenant from the verified claim so the+# fan-out edge is no longer unauthenticated.+api_router.include_router(realtime.router)diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 27930e33f..6be142355 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -26,6 +26,15 @@ INSECURE_SECRET_KEY_DEFAULTS: frozenset[str] = frozenset(})+# Deterministic fallback secret for realtime WS/SSE tickets in development.+# The API ticket endpoint and the Node realtime verifier BOTH fall back to+# this literal when ``AISOC_REALTIME_JWT_SECRET`` is unset *and* the+# environment is development-class, so local docker-compose works without any+# secret plumbing. It is intentionally well-known and is treated as insecure+# outside development (see ``realtime_ticket_secret``). The exact same literal+# is hardcoded in ``services/realtime/src/index.ts`` — keep the two in sync.+DEV_REALTIME_TICKET_SECRET: Final[str] = "aisoc-dev-realtime-ticket-secret-not-for-production"+# ------------------------------------------------------------------# Canonical "dev mode" detection (H-8 + P2-A3).#@@ -344,6 +353,26 @@ class Settings(BaseSettings):# tests by passing ``JWT_SECRET=""`` instead of mutating the environment.JWT_SECRET: str = ""+ # Shared HS256 secret governing short-lived WebSocket/SSE *tickets*. The+ # API mints tickets at ``POST /api/v1/realtime/ticket`` (see+ # ``app/api/v1/endpoints/realtime.py``) and the Node realtime service+ # (``services/realtime``) verifies them on every WS upgrade and SSE+ # request. Both sides MUST read the same value. This is intentionally a+ # *different* secret from ``SECRET_KEY`` (which signs first-party API+ # access tokens) and ``REALTIME_INTERNAL_TOKEN`` (service-to-service+ # fan-out auth), so the realtime edge can be rotated independently and a+ # leaked ticket secret never forges a full API session.+ #+ # When empty in a development-class environment, both services fall back+ # to ``DEV_REALTIME_TICKET_SECRET`` so local docker-compose "just works".+ # Outside development the ticket endpoint fails closed (503) until a real+ # secret is wired, and the realtime service rejects every connection.+ AISOC_REALTIME_JWT_SECRET: str = ""+ # Time-to-live, in seconds, for minted realtime tickets. Kept short so a+ # leaked ticket is only briefly useful; the frontend re-mints on every+ # (re)connect. Clamped to a sane ceiling by the ticket endpoint.+ AISOC_REALTIME_TICKET_TTL_SECONDS: int = 60+# Relying party identity for WebAuthn / Passkey ceremonies. RP_ID must# match the eTLD+1 of the PWA origin (no scheme, no port). RP_NAME is# what the OS prompt shows the user.@@ -601,6 +630,32 @@ def get_settings() -> Settings:return Settings()+def realtime_ticket_secret(s: Settings | None = None) -> str | None:+ """Resolve the effective HS256 secret used to sign realtime WS/SSE tickets.++ Returns the secret to sign with, or ``None`` when the deployment is not+ configured to mint tickets (i.e. the ticket endpoint should fail closed+ with 503).++ Resolution rules — kept byte-for-byte in sync with the Node verifier in+ ``services/realtime/src/index.ts``:++ * If ``AISOC_REALTIME_JWT_SECRET`` is set to a non-empty, non-insecure+ value, use it (any environment).+ * Otherwise, in a development-class environment, fall back to the shared+ ``DEV_REALTIME_TICKET_SECRET`` so local stacks work with zero config.+ * Otherwise (production with the secret unset or set to a known insecure+ placeholder), return ``None`` — the caller must fail closed.+ """+ s = s or settings+ configured = (s.AISOC_REALTIME_JWT_SECRET or "").strip()+ if configured and configured not in INSECURE_SECRET_KEY_DEFAULTS:+ return configured+ if is_dev_env(s.ENVIRONMENT):+ return DEV_REALTIME_TICKET_SECRET+ return None++def warn_if_insecure_defaults(s: Settings | None = None) -> list[str]:"""Emit a structured warning for each insecure default still in place.@@ -651,6 +706,17 @@ def warn_if_insecure_defaults(s: Settings | None = None) -> list[str]:if not is_dev_env(s.ENVIRONMENT) and not s.REALTIME_INTERNAL_TOKEN:msgs.append("REALTIME_INTERNAL_TOKEN is empty in a non-development environment — agent → realtime events are unauthenticated.")+ # Realtime WS/SSE ticket secret. When unset (or set to a well-known+ # placeholder) outside development the ticket endpoint fails closed (503)+ # and the realtime service rejects every browser connection, so surface it+ # loudly at boot rather than letting operators discover it via 503s.+ if not is_dev_env(s.ENVIRONMENT) and realtime_ticket_secret(s) is None:+ msgs.append(+ "AISOC_REALTIME_JWT_SECRET is empty or set to a known insecure placeholder — "+ "realtime WS/SSE ticket issuance will fail closed (503) and browser realtime "+ "connections will be rejected until you wire a real secret."+ )+# Air-gap sanity check: if an operator flipped on AISOC_AIRGAPPED but# the LLM is still pointed at a public endpoint (api.openai.com, etc.)# surface that as an insecure-default rather than silently 503-ingdiff --git a/services/api/app/core/security.py b/services/api/app/core/security.pyindex b5b4da4f2..2bf56df34 100644--- a/services/api/app/core/security.py+++ b/services/api/app/core/security.py@@ -172,6 +172,41 @@ def decode_token(token: str) -> dict[str, Any]:return jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])+# Audience claim required on every realtime WS/SSE ticket. The Node realtime+# verifier (``services/realtime/src/index.ts``) checks for this exact value, so+# a leaked first-party API access token (aud unset) cannot be replayed against+# the realtime edge and vice-versa.+REALTIME_TICKET_AUDIENCE = "aisoc-realtime"+++def create_realtime_ticket(+ *,+ secret: str,+ tenant_id: str,+ user_id: str,+ ttl_seconds: int,+) -> str:+ """Mint a short-lived HS256 ticket for the realtime WS/SSE edge.++ Signed with the *shared realtime secret* (``AISOC_REALTIME_JWT_SECRET`` or+ the dev fallback), NOT ``SECRET_KEY``. Carries an ``aud`` claim so it is only+ valid at the realtime boundary, and an ``exp`` clamped by the caller. The+ realtime service derives the subscription tenant from ``tenant_id`` here —+ the browser never gets to choose its own tenant.+ """+ now = datetime.now(UTC)+ expire = now + timedelta(seconds=ttl_seconds)+ payload = {+ "sub": user_id,+ "tenant_id": tenant_id,+ "aud": REALTIME_TICKET_AUDIENCE,+ "iat": now,+ "exp": expire,+ "type": "realtime_ticket",+ }+ return jwt.encode(payload, secret, algorithm="HS256")++def generate_api_key() -> tuple[str, str, str]:"""Generate a new scoped API key.diff --git a/services/api/tests/api/v1/endpoints/test_realtime_ticket.py b/services/api/tests/api/v1/endpoints/test_realtime_ticket.pynew file mode 100644index 000000000..4cd074320--- /dev/null+++ b/services/api/tests/api/v1/endpoints/test_realtime_ticket.py@@ -0,0 +1,204 @@+"""Regression tests for the realtime WS/SSE ticket flow — Issue #239.++Issue #239 closed a broken-access-control bug: ``services/realtime`` upgraded+WebSocket connections and served ``/sse`` to *any* caller. The fix mints a+short-TTL, audience-scoped HS256 ticket from ``POST /api/v1/realtime/ticket``+(signed with the shared ``AISOC_REALTIME_JWT_SECRET``, deliberately NOT+``SECRET_KEY``) which the Node edge verifies before accepting a connection.++These tests pin the API half of that contract so it cannot silently regress:++* ``realtime_ticket_secret`` resolution — configured / dev fallback / prod+ fail-closed / insecure placeholder.+* ``warn_if_insecure_defaults`` surfaces the missing secret in prod.+* ``mint_realtime_ticket`` — mints claims the Node verifier expects (aud, type,+ tenant_id, sub, exp), clamps TTL to the 60s ceiling, binds the tenant from the+ authenticated user (never the client), and fails closed with 503 when the+ shared secret is unconfigured in prod.++The Node-side signature/aud/exp verification is pinned separately in+``services/realtime/src/auth.test.ts``. The claim shape here must stay in sync+with ``RealtimeClaims`` / ``verifyRealtimeTicket`` there.++AiSOC — open-source AI Security Operations Center (MIT License)+"""++from __future__ import annotations++import uuid++import pytest+from app.api.v1.deps import CurrentUser+from app.api.v1.endpoints import realtime as realtime_ep+from app.core.config import DEV_REALTIME_TICKET_SECRET, Settings, realtime_ticket_secret, warn_if_insecure_defaults+from app.core.security import REALTIME_TICKET_AUDIENCE+from fastapi import HTTPException+from jose import jwt++# A real 64-char secret used across the "happy path" tests — anything outside+# INSECURE_SECRET_KEY_DEFAULTS and non-empty resolves as configured.+_REAL_SECRET = "r" * 64+++def _settings(**overrides) -> Settings:+ """Construct Settings without reading the host .env (deterministic)."""+ base: dict = {+ "ENVIRONMENT": "production",+ "AISOC_REALTIME_JWT_SECRET": _REAL_SECRET,+ }+ base.update(overrides)+ return Settings(_env_file=None, **base)+++def _user(tenant_id: uuid.UUID | None = None) -> CurrentUser:+ return CurrentUser(+ user_id=uuid.uuid4(),+ tenant_id=tenant_id or uuid.uuid4(),+ role="admin",+ email="[email protected]",+ )+++# ─── realtime_ticket_secret resolution ──────────────────────────────────────+++def test_secret_uses_configured_value_in_any_env():+ s = _settings(ENVIRONMENT="production", AISOC_REALTIME_JWT_SECRET=_REAL_SECRET)+ assert realtime_ticket_secret(s) == _REAL_SECRET+++def test_secret_falls_back_to_dev_default_in_development():+ s = _settings(ENVIRONMENT="development", AISOC_REALTIME_JWT_SECRET="")+ assert realtime_ticket_secret(s) == DEV_REALTIME_TICKET_SECRET+++def test_secret_is_none_in_prod_when_unset():+ """Production with the shared secret unset must fail closed (None)."""+ s = _settings(ENVIRONMENT="production", AISOC_REALTIME_JWT_SECRET="")+ assert realtime_ticket_secret(s) is None+++def test_secret_is_none_in_prod_when_set_to_insecure_placeholder():+ """A well-known placeholder is treated as 'unset' — fail closed."""+ s = _settings(+ ENVIRONMENT="production",+ # SECRET_KEY placeholder is in INSECURE_SECRET_KEY_DEFAULTS.+ AISOC_REALTIME_JWT_SECRET="change-me-in-production-at-least-32-chars",+ )+ assert realtime_ticket_secret(s) is None+++def test_missing_secret_in_prod_warns():+ s = _settings(ENVIRONMENT="production", AISOC_REALTIME_JWT_SECRET="")+ msgs = warn_if_insecure_defaults(s)+ assert any("AISOC_REALTIME_JWT_SECRET" in m for m in msgs)+++def test_configured_secret_in_prod_does_not_warn():+ s = _settings(ENVIRONMENT="production", AISOC_REALTIME_JWT_SECRET=_REAL_SECRET)+ msgs = warn_if_insecure_defaults(s)+ assert not any("AISOC_REALTIME_JWT_SECRET" in m for m in msgs)+++def test_missing_secret_in_dev_does_not_warn():+ """Dev has a built-in fallback, so no nag there."""+ s = _settings(ENVIRONMENT="development", AISOC_REALTIME_JWT_SECRET="")+ msgs = warn_if_insecure_defaults(s)+ assert not any("AISOC_REALTIME_JWT_SECRET" in m for m in msgs)+++# ─── mint_realtime_ticket endpoint ───────────────────────────────────────────+++def configured(monkeypatch):+ """Point the endpoint module at a settings object with a real secret."""+ s = _settings(ENVIRONMENT="production", AISOC_REALTIME_JWT_SECRET=_REAL_SECRET)+ monkeypatch.setattr(realtime_ep, "settings", s)+ return s+++async def test_mint_returns_verifiable_ticket(configured):+ """The minted token must decode under the shared secret with the exact+ claims the Node verifier checks (aud, type, tenant_id, sub)."""+ tenant = uuid.uuid4()+ user = _user(tenant)++ ticket = await realtime_ep.mint_realtime_ticket(user)++ assert ticket.tenant_id == str(tenant)+ assert ticket.expires_in == configured.AISOC_REALTIME_TICKET_TTL_SECONDS++ claims = jwt.decode(+ ticket.token,+ _REAL_SECRET,+ algorithms=["HS256"],+ audience=REALTIME_TICKET_AUDIENCE,+ )+ assert claims["aud"] == REALTIME_TICKET_AUDIENCE+ assert claims["type"] == "realtime_ticket"+ assert claims["tenant_id"] == str(tenant)+ assert claims["sub"] == str(user.user_id)+ assert claims["exp"] > claims["iat"]+++async def test_mint_binds_tenant_from_user_not_client(configured):+ """Tenant is taken from the authenticated user — there is no client input+ that could smuggle a different tenant into the ticket."""+ tenant = uuid.uuid4()+ ticket = await realtime_ep.mint_realtime_ticket(_user(tenant))+ assert ticket.tenant_id == str(tenant)+++async def test_mint_rejects_foreign_audience(configured):+ """A ticket scoped to the realtime edge must not validate for any other+ audience — guards against a stolen ticket being replayed at the API."""+ ticket = await realtime_ep.mint_realtime_ticket(_user())+ with pytest.raises(jwt.JWTError):+ jwt.decode(+ ticket.token,+ _REAL_SECRET,+ algorithms=["HS256"],+ audience="some-other-service",+ )+++async def test_mint_clamps_ttl_to_60s_ceiling(monkeypatch):+ """A misconfigured long TTL can never mint a multi-minute bearer."""+ s = _settings(+ ENVIRONMENT="production",+ AISOC_REALTIME_JWT_SECRET=_REAL_SECRET,+ AISOC_REALTIME_TICKET_TTL_SECONDS=600,+ )+ monkeypatch.setattr(realtime_ep, "settings", s)+ ticket = await realtime_ep.mint_realtime_ticket(_user())+ assert ticket.expires_in == 60+++async def test_mint_fails_closed_with_503_when_secret_unconfigured(monkeypatch):+ """Production with the shared secret unset → 503, not a ticket nobody can+ verify. This is the fail-closed half of the #239 fix."""+ s = _settings(ENVIRONMENT="production", AISOC_REALTIME_JWT_SECRET="")+ monkeypatch.setattr(realtime_ep, "settings", s)++ with pytest.raises(HTTPException) as exc:+ await realtime_ep.mint_realtime_ticket(_user())++ assert exc.value.status_code == 503+ assert "AISOC_REALTIME_JWT_SECRET" in exc.value.detail+++def test_endpoint_requires_authentication():+ """The route must depend on get_current_user so an unauthenticated caller+ is 401'd before any ticket is minted (the WS/SSE 401 contract starts here).+ """+ from app.api.v1.deps import get_current_user++ route = next(r for r in realtime_ep.router.routes if getattr(r, "path", None) == "/realtime/ticket")+ dep_calls = [d.call for d in route.dependant.dependencies]+ assert get_current_user in dep_callsdiff --git a/services/api/tests/test_security_defaults.py b/services/api/tests/test_security_defaults.pyindex 83155abc4..ffbe3bb6f 100644--- a/services/api/tests/test_security_defaults.py+++ b/services/api/tests/test_security_defaults.py@@ -39,6 +39,11 @@ def _make_settings(**overrides) -> Settings:# Bearer token the agents service uses to push events into realtime.# Empty in prod means the channel is unauthenticated, which warns."REALTIME_INTERNAL_TOKEN": "c" * 64,+ # Shared HS256 secret the API uses to mint WS/SSE tickets and the+ # realtime service uses to verify them (issue #239). Empty/placeholder+ # values fail closed (503) in prod, so the "clean prod" baseline must+ # set a real value.+ "AISOC_REALTIME_JWT_SECRET": "d" * 64,}base.update(overrides)# ``_env_file=None`` skips .env discovery so test runs are deterministic@@ -142,6 +147,20 @@ def test_empty_realtime_token_in_dev_does_not_warn():assert not any("REALTIME_INTERNAL_TOKEN" in m for m in msgs)+def test_empty_realtime_jwt_secret_in_prod_warns():+ """WS/SSE ticket signing must use a real shared secret in prod (#239)."""+ s = _make_settings(AISOC_REALTIME_JWT_SECRET="")+ msgs = warn_if_insecure_defaults(s)+ assert any("AISOC_REALTIME_JWT_SECRET" in m for m in msgs)+++def test_empty_realtime_jwt_secret_in_dev_does_not_warn():+ """Dev falls back to a hardcoded ticket secret, so silence is intentional."""+ s = _make_settings(ENVIRONMENT="development", AISOC_REALTIME_JWT_SECRET="")+ msgs = warn_if_insecure_defaults(s)+ assert not any("AISOC_REALTIME_JWT_SECRET" in m for m in msgs)++# ─── /metrics auth gate ────────────────────────────────────────────────────diff --git a/services/realtime/package.json b/services/realtime/package.jsonindex 8d8438a60..d2da7157e 100644--- a/services/realtime/package.json+++ b/services/realtime/package.json@@ -6,7 +6,8 @@"scripts": {"dev": "tsx watch src/index.ts","build": "tsc",- "start": "node dist/index.js"+ "start": "node dist/index.js",+ "test": "tsx --test test/**/*.test.ts"},"dependencies": {"cors": "^2.8.5",diff --git a/services/realtime/src/auth.ts b/services/realtime/src/auth.tsnew file mode 100644index 000000000..c8839d9ba--- /dev/null+++ b/services/realtime/src/auth.ts@@ -0,0 +1,127 @@+/**+ * Realtime WS/SSE ticket verification — Issue #239.+ *+ * The browser cannot attach an Authorization header to a WebSocket upgrade, so+ * the SPA first calls `POST /api/v1/realtime/ticket` on the API, which mints a+ * short-TTL (≤60s), audience-scoped HS256 ticket signed with the shared+ * `AISOC_REALTIME_JWT_SECRET`. The browser then appends the ticket as+ * `?token=...` on the WS/SSE URL. This module verifies that ticket here at the+ * realtime edge: signature (HS256), `aud`, and `exp`. The subscription tenant+ * is derived from the verified `tenant_id` claim — never from a client-supplied+ * query parameter — so a caller can never subscribe to another tenant.+ *+ * We verify manually with Node's `crypto` rather than pulling in a JWT library+ * to keep the realtime service's dependency surface (and supply chain) minimal.+ * The signing side lives in `services/api/app/core/security.py`+ * (`create_realtime_ticket`) and must stay in sync with the claims checked here.+ */+import crypto from 'crypto';++// Must equal `REALTIME_TICKET_AUDIENCE` in services/api/app/core/security.py.+export const REALTIME_TICKET_AUDIENCE = 'aisoc-realtime';++// Must equal `DEV_REALTIME_TICKET_SECRET` in services/api/app/core/config.py.+// Shared dev fallback so local docker-compose works with zero secret plumbing.+const DEV_REALTIME_TICKET_SECRET = 'aisoc-dev-realtime-ticket-secret-not-for-production';++// Mirror INSECURE_SECRET_KEY_DEFAULTS in services/api/app/core/config.py so a+// placeholder secret is treated as "unset" on this side too.+const INSECURE_SECRET_DEFAULTS = new Set<string>([+ 'change-me-in-production-at-least-32-chars',+ 'dev_secret_key_change_in_production',+ 'changeme',+ 'secret',+]);++function isProductionEnv(): boolean {+ const env = (process.env.AISOC_ENV || process.env.ENVIRONMENT || process.env.APP_ENV || '')+ .trim()+ .toLowerCase();+ return env === 'production' || env === 'prod';+}++/**+ * Resolve the effective HS256 secret used to verify realtime tickets.+ *+ * Returns the secret, or `null` when the service is not configured to verify+ * tickets (production with the shared secret unset/insecure) — in which case the+ * caller MUST reject every connection (fail closed). Kept byte-for-byte in sync+ * with `realtime_ticket_secret` in services/api/app/core/config.py.+ */+export function resolveTicketSecret(): string | null {+ const configured = (process.env.AISOC_REALTIME_JWT_SECRET || '').trim();+ if (configured && !INSECURE_SECRET_DEFAULTS.has(configured)) {+ return configured;+ }+ if (!isProductionEnv()) {+ return DEV_REALTIME_TICKET_SECRET;+ }+ return null;+}++function base64UrlDecode(input: string): Buffer {+ // JWT uses base64url; Node's 'base64url' decoder tolerates missing padding.+ return Buffer.from(input, 'base64url');+}++export interface RealtimeClaims {+ sub: string;+ tenant_id: string;+ aud: string;+ exp: number;+ iat?: number;+ type?: string;+}++/**+ * Verify an HS256 realtime ticket. Returns the decoded claims on success, or+ * `null` if the token is malformed, has a bad signature, wrong audience, wrong+ * type, or is expired.+ */+export function verifyRealtimeTicket(token: string, secret: string): RealtimeClaims | null {+ if (!token) return null;+ const parts = token.split('.');+ if (parts.length !== 3) return null;+ const [headerB64, payloadB64, sigB64] = parts;++ // Verify header advertises HS256 — reject "alg: none" and asymmetric algs so+ // an attacker can't downgrade the verification.+ let header: { alg?: string; typ?: string };+ try {+ header = JSON.parse(base64UrlDecode(headerB64).toString('utf8'));+ } catch {+ return null;+ }+ if (header.alg !== 'HS256') return null;++ // Recompute and constant-time compare the signature over `header.payload`.+ const expected = crypto+ .createHmac('sha256', secret)+ .update(`${headerB64}.${payloadB64}`)+ .digest();+ let provided: Buffer;+ try {+ provided = base64UrlDecode(sigB64);+ } catch {+ return null;+ }+ if (expected.length !== provided.length) return null;+ if (!crypto.timingSafeEqual(expected, provided)) return null;++ let claims: RealtimeClaims;+ try {+ claims = JSON.parse(base64UrlDecode(payloadB64).toString('utf8'));+ } catch {+ return null;+ }++ if (claims.aud !== REALTIME_TICKET_AUDIENCE) return null;+ if (claims.type && claims.type !== 'realtime_ticket') return null;+ if (typeof claims.exp !== 'number') return null;+ // 30s clock-skew leeway, matching common JWT verifier defaults.+ const now = Math.floor(Date.now() / 1000);+ if (claims.exp + 30 < now) return null;+ if (!claims.tenant_id) return null;++ return claims;+}diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.tsindex 36aa7d0fa..50def956c 100644--- a/services/realtime/src/index.ts+++ b/services/realtime/src/index.ts@@ -8,6 +8,7 @@ import pino from 'pino';import rateLimit from 'express-rate-limit';import { PushManager } from './push';+import { resolveTicketSecret, verifyRealtimeTicket } from './auth';const log = pino({ level: process.env.LOG_LEVEL || 'info' });@@ -84,6 +85,37 @@ log.info('CORS configured',);+// --- Realtime ticket auth (Issue #239) -------------------------------------+// Resolve the shared HS256 secret used to verify the short-lived tickets the+// API mints at POST /api/v1/realtime/ticket. `null` means we are NOT configured+// to verify (production with AISOC_REALTIME_JWT_SECRET unset/insecure) — in that+// case every WS upgrade and SSE request is rejected (fail closed) rather than+// silently accepting unauthenticated subscribers (the bug Issue #239 closes).+const REALTIME_TICKET_SECRET = resolveTicketSecret();+if (REALTIME_TICKET_SECRET === null) {+ log.error(+ 'AISOC_REALTIME_JWT_SECRET is unset or insecure in a production environment — ' ++ 'realtime WS/SSE connections will be rejected until a real secret is wired.',+ );+} else if (+ REALTIME_TICKET_SECRET === 'aisoc-dev-realtime-ticket-secret-not-for-production'+) {+ log.warn('Using the shared development realtime ticket secret — do NOT use in production.');+}++/**+ * Verify the `?token=` ticket on a realtime request URL. Returns the verified+ * tenant_id, or `null` if the request must be rejected. Centralises the+ * fail-closed decision for both the WS upgrade and the SSE handler.+ */+function authenticateRealtime(url: URL): string | null {+ if (REALTIME_TICKET_SECRET === null) return null;+ const token = url.searchParams.get('token') || '';+ const claims = verifyRealtimeTicket(token, REALTIME_TICKET_SECRET);+ if (!claims) return null;+ return claims.tenant_id;+}+const pushManager = new PushManager({redis: PUSH_REDIS,logger: log,@@ -164,8 +196,20 @@ server.on('upgrade', (req, socket, head) => {socket.destroy();return;}+ // Authenticate the connection from the short-lived ticket BEFORE completing+ // the upgrade. Reject (401 + close) when the ticket is missing/invalid or the+ // service is not configured to verify — never accept an anonymous subscriber.+ const verifiedTenant = authenticateRealtime(url);+ if (verifiedTenant === null) {+ socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');+ socket.destroy();+ return;+ }wss.handleUpgrade(req, socket, head, (ws) => {(ws as any)._aisocChannel = requested;+ // Tenant is derived from the verified ticket claim, NOT the URL query, so a+ // client can never subscribe to another tenant's fan-out.+ (ws as any)._aisocTenant = verifiedTenant;wss.emit('connection', ws, req);});});@@ -198,8 +242,9 @@ wss.on('connection', (ws, req) => {ws.close(1008, 'Rate limit exceeded');return;}- const url = new URL(req.url || '/', `http://localhost`);- const tenantId = url.searchParams.get('tenant_id') || 'default';+ // Tenant comes from the verified ticket claim stashed during the upgrade+ // (see server.on('upgrade')), never from a client-supplied query parameter.+ const tenantId = (ws as any)._aisocTenant || 'default';const channel: Channel = (ws as any)._aisocChannel ?? 'all';if (!clients.has(tenantId)) {@@ -314,7 +359,15 @@ const internalPushRateLimit = rateLimit({// --- SSE endpoint ---app.get('/sse', sseRateLimit, (req, res) => {- const tenantId = (req.query.tenant_id as string) || 'default';+ // Authenticate from the short-lived ticket and derive the tenant from the+ // verified claim. Reject (401) when the ticket is missing/invalid or the+ // service is not configured to verify — SSE is no longer an open stream.+ const reqUrl = new URL(req.originalUrl, 'http://localhost');+ const tenantId = authenticateRealtime(reqUrl);+ if (tenantId === null) {+ res.status(401).json({ error: 'unauthorized' });+ return;+ }res.setHeader('Content-Type', 'text/event-stream');res.setHeader('Cache-Control', 'no-cache');@@ -322,10 +375,11 @@ app.get('/sse', sseRateLimit, (req, res) => {// CORS headers for SSE are emitted by the `cors()` middleware on lines// ~118–143 above, which the `cors` npm package implements safely (CodeQL// recognises `cors({ origin: <function> })` as a sanitiser). SSE auth is- // done via the `tenant_id` query parameter, not via a session cookie,- // so we deliberately do not enable `Access-Control-Allow-Credentials`- // on this endpoint — that eliminates the entire "CORS misconfiguration- // for credentials transfer" attack surface that CodeQL warns about.+ // done via the short-lived `?token=` ticket verified above (Issue #239),+ // not via a session cookie, so we deliberately do not enable+ // `Access-Control-Allow-Credentials` on this endpoint — that eliminates+ // the entire "CORS misconfiguration for credentials transfer" attack+ // surface that CodeQL warns about.res.flushHeaders();const heartbeat = setInterval(() => {diff --git a/services/realtime/test/auth.test.ts b/services/realtime/test/auth.test.tsnew file mode 100644index 000000000..383b32982--- /dev/null+++ b/services/realtime/test/auth.test.ts@@ -0,0 +1,167 @@+/**+ * Unit tests for the realtime WS/SSE ticket verifier — Issue #239.+ *+ * These run on Node's built-in test runner via `tsx --test` (no extra deps).+ * The HMAC signing helper here mirrors `create_realtime_ticket` in+ * services/api/app/core/security.py so the test proves the two sides agree on+ * the exact wire format (HS256 over `base64url(header).base64url(payload)`).+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';++import {+ REALTIME_TICKET_AUDIENCE,+ resolveTicketSecret,+ verifyRealtimeTicket,+ type RealtimeClaims,+} from '../src/auth';++const SECRET = 'a'.repeat(64);++function b64url(buf: Buffer | string): string {+ return Buffer.from(buf).toString('base64url');+}++/** Mint an HS256 ticket the same way the Python API does. */+function mintTicket(+ claims: Record<string, unknown>,+ opts: { secret?: string; alg?: string } = {},+): string {+ const secret = opts.secret ?? SECRET;+ const header = b64url(JSON.stringify({ alg: opts.alg ?? 'HS256', typ: 'JWT' }));+ const payload = b64url(JSON.stringify(claims));+ const sig = crypto+ .createHmac('sha256', secret)+ .update(`${header}.${payload}`)+ .digest('base64url');+ return `${header}.${payload}.${sig}`;+}++function validClaims(overrides: Record<string, unknown> = {}): Record<string, unknown> {+ const now = Math.floor(Date.now() / 1000);+ return {+ sub: 'user-123',+ tenant_id: 'tenant-abc',+ aud: REALTIME_TICKET_AUDIENCE,+ iat: now,+ exp: now + 60,+ type: 'realtime_ticket',+ ...overrides,+ };+}++test('accepts a well-formed ticket and returns claims with the verified tenant', () => {+ const claims = verifyRealtimeTicket(mintTicket(validClaims()), SECRET) as RealtimeClaims;+ assert.ok(claims, 'expected claims');+ assert.equal(claims.tenant_id, 'tenant-abc');+ assert.equal(claims.sub, 'user-123');+ assert.equal(claims.aud, REALTIME_TICKET_AUDIENCE);+});++test('rejects an empty / malformed token', () => {+ assert.equal(verifyRealtimeTicket('', SECRET), null);+ assert.equal(verifyRealtimeTicket('not-a-jwt', SECRET), null);+ assert.equal(verifyRealtimeTicket('a.b', SECRET), null);+});++test('rejects a tampered signature', () => {+ const token = mintTicket(validClaims());+ const tampered = `${token.slice(0, -2)}xx`;+ assert.equal(verifyRealtimeTicket(tampered, SECRET), null);+});++test('rejects a token signed with a different secret', () => {+ const token = mintTicket(validClaims(), { secret: 'b'.repeat(64) });+ assert.equal(verifyRealtimeTicket(token, SECRET), null);+});++test('rejects alg:none (algorithm downgrade)', () => {+ const header = b64url(JSON.stringify({ alg: 'none', typ: 'JWT' }));+ const payload = b64url(JSON.stringify(validClaims()));+ // Unsigned token — the classic "alg: none" forgery.+ assert.equal(verifyRealtimeTicket(`${header}.${payload}.`, SECRET), null);+});++test('rejects a foreign audience', () => {+ const token = mintTicket(validClaims({ aud: 'some-other-service' }));+ assert.equal(verifyRealtimeTicket(token, SECRET), null);+});++test('rejects a wrong token type', () => {+ const token = mintTicket(validClaims({ type: 'access' }));+ assert.equal(verifyRealtimeTicket(token, SECRET), null);+});++test('rejects an expired ticket (beyond clock-skew leeway)', () => {+ const now = Math.floor(Date.now() / 1000);+ const token = mintTicket(validClaims({ iat: now - 120, exp: now - 60 }));+ assert.equal(verifyRealtimeTicket(token, SECRET), null);+});++test('accepts a ticket within the 30s clock-skew leeway', () => {+ const now = Math.floor(Date.now() / 1000);+ // Expired 10s ago — still inside the 30s leeway, so accepted.+ const token = mintTicket(validClaims({ exp: now - 10 }));+ assert.ok(verifyRealtimeTicket(token, SECRET));+});++test('rejects a ticket missing tenant_id', () => {+ const claims = validClaims();+ delete (claims as Record<string, unknown>).tenant_id;+ assert.equal(verifyRealtimeTicket(mintTicket(claims), SECRET), null);+});++test('rejects a non-numeric exp', () => {+ const token = mintTicket(validClaims({ exp: 'soon' }));+ assert.equal(verifyRealtimeTicket(token, SECRET), null);+});++test('resolveTicketSecret falls back to the dev secret outside production', () => {+ const prev = { ...process.env };+ try {+ delete process.env.AISOC_REALTIME_JWT_SECRET;+ process.env.ENVIRONMENT = 'development';+ delete process.env.AISOC_ENV;+ delete process.env.APP_ENV;+ assert.equal(+ resolveTicketSecret(),+ 'aisoc-dev-realtime-ticket-secret-not-for-production',+ );+ } finally {+ process.env = prev;+ }+});++test('resolveTicketSecret fails closed (null) in production when unset', () => {+ const prev = { ...process.env };+ try {+ delete process.env.AISOC_REALTIME_JWT_SECRET;+ process.env.ENVIRONMENT = 'production';+ assert.equal(resolveTicketSecret(), null);+ } finally {+ process.env = prev;+ }+});++test('resolveTicketSecret rejects a known insecure placeholder in production', () => {+ const prev = { ...process.env };+ try {+ process.env.AISOC_REALTIME_JWT_SECRET = 'changeme';+ process.env.ENVIRONMENT = 'production';+ assert.equal(resolveTicketSecret(), null);+ } finally {+ process.env = prev;+ }+});++test('resolveTicketSecret returns a real configured secret in production', () => {+ const prev = { ...process.env };+ try {+ process.env.AISOC_REALTIME_JWT_SECRET = SECRET;+ process.env.ENVIRONMENT = 'production';+ assert.equal(resolveTicketSecret(), SECRET);+ } finally {+ process.env = prev;+ }+});