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(api): audit the verified principal, not an unverified JWT (GHSA-w4r8-969c-67p2) (#1182)
Beenu Arora8f2224299124
diff --git a/.github/workflows/audit-forgery-live.yml b/.github/workflows/audit-forgery-live.ymlnew file mode 100644index 000000000..5cbbef445--- /dev/null+++ b/.github/workflows/audit-forgery-live.yml@@ -0,0 +1,152 @@+# Audit-chain forgery is refused — through the real app and real Postgres.+#+# GHSA-w4r8-969c-67p2 (CWE-347). AuditMiddleware used to decode the+# Authorization Bearer token with verify_signature=False and write the claims+# into the tenant's tamper-evident audit hash chain, for every mutating+# request, before and regardless of authentication. An unauthenticated caller+# who sent a structurally valid JWT signed with any key forged audit entries+# attributed to any user into any known tenant.+#+# The offline test (services/api/tests/test_audit_middleware_no_forgery.py)+# runs in the general Python job and intercepts the DB write, so it proves the+# decision. This job proves the end-to-end property: a forged request leaves+# the real audit_log / audit_chain_head tables untouched while a legitimately+# authenticated request still lands a chained row.+#+# No `paths:` filter — a security regression guard must grade every pull+# request, not only ones that touch a named path.+name: Audit forgery (live)++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++concurrency:+ group: audit-forgery-live-${{ github.ref }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ audit-forgery-live:+ name: A forged token cannot enter the audit chain+ runs-on: ubuntu-latest+ timeout-minutes: 20++ services:+ postgres:+ image: postgres:16-alpine+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_only+ POSTGRES_DB: aisoc+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20++ env:+ # The runtime role, not the owner. POSTGRES_USER (aisoc) is a superuser+ # and ignores every RLS policy even under FORCE ROW LEVEL SECURITY, so+ # the app connects as the NOSUPERUSER runtime role aisoc_app and the+ # owner is used only to run migrations.+ AUDIT_DSN: postgresql+asyncpg://aisoc_app:aisoc_app_ci_only@localhost:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ # Not a bypass environment — an uncredentialed request must resolve to no+ # principal, or the "no identity, no audit row" claim passes for the+ # wrong reason.+ ENVIRONMENT: production+ SECRET_KEY: ci-audit-forgery-signing-secret-at-least-32-chars+ OTEL_SDK_DISABLED: "true"++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6+ with:+ python-version: "3.11"++ # The service's own lockfile, not a hand-curated pip list: a suite that+ # drives the real service pulls in the real service's whole import chain.+ - name: Install api from its lockfile+ working-directory: services/api+ run: |+ set -euo pipefail+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: Apply every migration, in order+ run: |+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: Give the runtime role its password+ run: |+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "ALTER ROLE aisoc_app WITH PASSWORD 'aisoc_app_ci_only';"+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -c \+ "GRANT USAGE ON SCHEMA public TO aisoc_app;"++ - name: A forged token cannot enter the chain; a verified one is audited+ working-directory: services/api+ env:+ ISOLATION_AUDIT_DSN: ${{ env.AUDIT_DSN }}+ DATABASE_URL: ${{ env.AUDIT_DSN }}+ run: python -m pytest ../../tests/isolation/test_audit_forgery_live.py -v --tb=short++ # The negative control.+ #+ # Reintroduce the vulnerability — trust the unverified Authorization+ # header again — and the forgery assertion must go red. Without this, a+ # middleware that simply stopped writing would pass the suite above while+ # silently also stopping all legitimate auditing.+ - name: The gate fails when the middleware trusts an unverified token+ working-directory: services/api+ env:+ ISOLATION_AUDIT_DSN: ${{ env.AUDIT_DSN }}+ DATABASE_URL: ${{ env.AUDIT_DSN }}+ run: |+ cp app/middleware/audit_middleware.py /tmp/audit_mw.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/middleware/audit_middleware.py")+ s = p.read_text()+ needle = ' principal = getattr(request.state, "aisoc_authenticated_principal", None)\n'+ if needle not in s:+ print("negative control could not find the request.state read to subvert; "+ "the middleware has been reshaped and this control no longer proves anything")+ sys.exit(1)+ vuln = (+ " import jwt as _jwt # NEGATIVE CONTROL: trust the unverified header again\n"+ " import types as _types\n"+ ' _auth = request.headers.get("authorization", "")\n'+ " principal = None\n"+ ' if _auth.startswith("Bearer "):\n'+ " try:\n"+ ' _c = _jwt.decode(_auth.split(" ", 1)[1], options={"verify_signature": False})\n'+ " principal = _types.SimpleNamespace(\n"+ " user_id=None,\n"+ ' tenant_id=uuid.UUID(_c["tenant_id"]) if _c.get("tenant_id") else None,\n'+ " email=_c.get(\"email\"),\n"+ " )\n"+ " except Exception:\n"+ " principal = None\n"+ )+ p.write_text(s.replace(needle, vuln, 1))+ PY+ if python -m pytest ../../tests/isolation/test_audit_forgery_live.py::TestForgeryIsRefused::test_a_forged_bearer_jwt_writes_no_audit_row -q >/dev/null 2>&1; then+ cp /tmp/audit_mw.bak app/middleware/audit_middleware.py+ echo "FAIL: the suite passed with the middleware trusting a forged token."+ exit 1+ fi+ cp /tmp/audit_mw.bak app/middleware/audit_middleware.py+ echo "OK: reintroducing the unverified-token path makes the suite fail, as it must."diff --git a/.security/allowlist.yml b/.security/allowlist.ymlindex 01a4618de..345ef4f06 100644--- a/.security/allowlist.yml+++ b/.security/allowlist.yml@@ -182,8 +182,17 @@ ceilings:# to where it stood before the unused-logger removal lowered it,# which is a different thing from raising a ceiling to make a scan# pass — the error count stays at the reduced 39.- total: 104- error: 39+ #+ # 104 -> 103 and 39 -> 38, another real reduction rather than the ±1+ # the note above warns about. The GHSA-w4r8-969c-67p2 fix removed the+ # `jwt.decode(token, options={"verify_signature": False})` call in+ # services/api/app/middleware/audit_middleware.py, which the rule set+ # flags as an `error` (a JWT decoded with signature verification+ # disabled). That is exactly one `error` finding, and both the error+ # and total counts dropped by exactly one on this branch, so the delta+ # is the removed call and not the scanner. Lowering locks it in.+ total: 103+ error: 38measured_with: "1.86.0"checkov:failed: 219diff --git a/services/api/app/api/v1/deps.py b/services/api/app/api/v1/deps.pyindex bc8cf7819..06294e898 100644--- a/services/api/app/api/v1/deps.py+++ b/services/api/app/api/v1/deps.py@@ -400,6 +400,27 @@ async def _resolve_api_key(raw_key: str, db: AsyncSession) -> CurrentUser:)+def _record_authenticated_principal(request: Request, principal: CurrentUser) -> CurrentUser:+ """Record the **verified** principal for the audit middleware, and return it.++ :class:`~app.middleware.audit_middleware.AuditMiddleware` runs outside this+ dependency and used to decode the Authorization header with+ ``verify_signature=False`` to label its rows, which let an unauthenticated+ caller forge entries in the tamper-evident audit chain+ (GHSA-w4r8-969c-67p2). It now reads the actor from this stashed principal+ instead, so only a credential that actually verified is audited, as the+ identity it verified to.++ ``request.state`` is backed by the ASGI ``scope["state"]`` dict — the same+ dict for every ``Request`` built from this scope — which is the channel+ ``app.services.audit`` already uses to signal the middleware across the+ ``BaseHTTPMiddleware`` task boundary. A request that fails authentication+ raises before reaching here, so nothing is recorded for it.+ """+ request.state.aisoc_authenticated_principal = principal+ return principal++async def get_current_user(request: Request,credentials: Annotated[HTTPAuthorizationCredentials | None, Security(bearer_scheme)],@@ -421,14 +442,21 @@ async def get_current_user(In development mode an unauthenticated request resolves to a deterministicdemo user (see ``app.api.v1.dev_auth``). Production requires a bearer token.++ Every principal this returns is first recorded on ``request.state`` via+ :func:`_record_authenticated_principal` so the audit middleware audits the+ verified identity rather than an unverified token (GHSA-w4r8-969c-67p2)."""if credentials is None:if is_dev_mode():- return CurrentUser(- user_id=DEMO_USER_ID,- tenant_id=DEMO_TENANT_ID,- role=DEMO_USER_ROLE,- email=DEMO_USER_EMAIL,+ return _record_authenticated_principal(+ request,+ CurrentUser(+ user_id=DEMO_USER_ID,+ tenant_id=DEMO_TENANT_ID,+ role=DEMO_USER_ROLE,+ email=DEMO_USER_EMAIL,+ ),)raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,@@ -440,7 +468,7 @@ async def get_current_user(# --- API key path ---if token.startswith(_API_KEY_PREFIX):- return await _resolve_api_key(token, db)+ return _record_authenticated_principal(request, await _resolve_api_key(token, db))# --- trusted peer service acting for one declared tenant ---#@@ -455,10 +483,10 @@ async def get_current_user(declared_tenant = request.headers.get(SERVICE_TENANT_HEADER)service_principal = await _resolve_service_principal(token, declared_tenant, db)if service_principal is not None:- return service_principal+ return _record_authenticated_principal(request, service_principal)# --- JWT path ---- return await resolve_jwt_principal(token, db)+ return _record_authenticated_principal(request, await resolve_jwt_principal(token, db))async def resolve_jwt_principal(token: str, db: AsyncSession) -> CurrentUser:diff --git a/services/api/app/middleware/audit_middleware.py b/services/api/app/middleware/audit_middleware.pyindex 217138755..4d110d76d 100644--- a/services/api/app/middleware/audit_middleware.py+++ b/services/api/app/middleware/audit_middleware.py@@ -87,22 +87,37 @@ def _label_for_path(method: str, path: str) -> tuple[str, str]:return f"{method.lower()}:{path}", "unknown"-def _extract_jwt_claims(request: Request) -> tuple[uuid.UUID | None, uuid.UUID | None, str | None]:- """Return (user_id, tenant_id, email) from the Bearer JWT without re-validating."""- auth = request.headers.get("authorization", "")- if not auth.startswith("Bearer "):- return None, None, None- token = auth.split(" ", 1)[1]- try:- import jwt # noqa: PLC0415-- payload = jwt.decode(token, options={"verify_signature": False})- user_id = uuid.UUID(payload["sub"]) if payload.get("sub") else None- tenant_id = uuid.UUID(payload["tenant_id"]) if payload.get("tenant_id") else None- email = payload.get("email")- return user_id, tenant_id, email- except Exception:+def _authenticated_actor(+ request: Request,+) -> tuple[uuid.UUID | None, uuid.UUID | None, str | None]:+ """Return (user_id, tenant_id, email) from the *verified* principal.++ The identity is read from the principal that ``get_current_user`` resolved+ and recorded on ``request.state`` — the one place in the API where a+ credential is actually verified. It is **not** re-derived from the+ Authorization header here.++ The previous implementation decoded the Bearer JWT with+ ``jwt.decode(options={"verify_signature": False})`` and trusted its+ ``sub`` / ``tenant_id`` / ``email`` claims. That ran for every mutating+ request, before and regardless of authentication, so an unauthenticated+ caller who sent a structurally valid JWT signed with any key forged those+ claims straight into the tenant's tamper-evident audit chain+ (GHSA-w4r8-969c-67p2, CWE-347: improper verification of a cryptographic+ signature). A request that fails authentication now records nothing,+ because nothing verified an identity for it. A side effect is that the+ API-key and service-token paths — which never produced a JWT and so were+ never audited here before — are now audited as the principal they+ resolved to.+ """+ principal = getattr(request.state, "aisoc_authenticated_principal", None)+ if principal is None:return None, None, None+ return (+ getattr(principal, "user_id", None),+ getattr(principal, "tenant_id", None),+ getattr(principal, "email", None),+ )def _truncate(value: str | None, limit: int) -> str | None:@@ -137,9 +152,9 @@ class AuditMiddleware(BaseHTTPMiddleware):if response.status_code >= 500:return response- user_id, tenant_id, email = _extract_jwt_claims(request)+ user_id, tenant_id, email = _authenticated_actor(request)if tenant_id is None:- return response # unauthenticated+ return response # nothing authenticated this request — audit nothing# One audit writer per request.#diff --git a/services/api/tests/test_audit_middleware_no_forgery.py b/services/api/tests/test_audit_middleware_no_forgery.pynew file mode 100644index 000000000..f842b4775--- /dev/null+++ b/services/api/tests/test_audit_middleware_no_forgery.py@@ -0,0 +1,171 @@+"""The audit middleware must derive its actor from a verified principal only.++GHSA-w4r8-969c-67p2 (CWE-347). ``AuditMiddleware`` used to decode the+Authorization Bearer token with ``jwt.decode(options={"verify_signature":+False})`` and write the extracted ``sub`` / ``tenant_id`` / ``email`` into the+tenant's tamper-evident audit hash chain — for every mutating request,+*before and regardless of authentication*. An unauthenticated caller who sent+a structurally valid JWT signed with any key therefore forged audit entries+attributed to any user, into any tenant whose id they knew (the Default tenant+exists in every deployment).++These tests mount the **real** ``AuditMiddleware`` through a real Starlette app+and ``TestClient``, so the ``BaseHTTPMiddleware`` task boundary and the+``request.state`` propagation are the real ones — a hand-built call of+``dispatch`` would fake exactly the behaviour under test. The database write is+intercepted at ``AsyncSessionLocal`` / ``_append_to_chain`` so the assertion is+about *which identity the middleware decides to write*, not about a row; the+live suite (``tests/isolation/test_audit_forgery_live.py``) proves the same+property end to end against real Postgres.++The identity now comes from ``request.state.aisoc_authenticated_principal``,+set by ``get_current_user`` only after a credential verifies. A request that+sends a forged token but never authenticates leaves no principal there, so the+middleware writes nothing.+"""++from __future__ import annotations++import types++import jwt+import pytest+from app.middleware import audit_middleware+from app.middleware.audit_middleware import AuditMiddleware+from fastapi import FastAPI, Request+from starlette.testclient import TestClient++# A forged token: a structurally valid JWT whose claims an attacker chose,+# signed with a key the attacker owns. The server signs with its own+# SECRET_KEY, so this signature is invalid by construction — exactly the PoC+# token from the advisory.+FORGED_TOKEN = jwt.encode(+ {+ "sub": "66666666-6666-6666-6666-666666666666",+ "tenant_id": "00000000-0000-0000-0000-000000000001",+ "email": "[email protected]",+ "exp": 9999999999,+ },+ "attacker-owned-key-not-the-server-key",+ algorithm="HS256",+)+++class _FakeSession:+ """Stands in for ``AsyncSessionLocal()`` — records the row the middleware+ tries to write without needing a database.++ The security decision happens *before* the write (which identity, or+ none), so intercepting here observes it faithfully. ``_append_to_chain`` is+ separately patched to a no-op because it would otherwise issue SQL.+ """++ def __init__(self, sink: list) -> None:+ self._sink = sink++ async def __aenter__(self) -> _FakeSession:+ return self++ async def __aexit__(self, *_exc: object) -> bool:+ return False++ def add(self, event: object) -> None:+ self._sink.append(event)++ async def commit(self) -> None:+ return None+++def written(monkeypatch: pytest.MonkeyPatch) -> list:+ """Intercept the middleware's DB write; yield the list of written rows."""+ sink: list = []+ monkeypatch.setattr(audit_middleware, "AsyncSessionLocal", lambda: _FakeSession(sink))++ async def _noop_chain(_db: object, _event: object) -> None:+ return None++ monkeypatch.setattr(audit_middleware, "_append_to_chain", _noop_chain)+ return sink+++def _app(*, stash_principal: object | None = None) -> FastAPI:+ """A minimal app behind the real ``AuditMiddleware``.++ ``stash_principal`` simulates ``get_current_user`` recording a *verified*+ principal on ``request.state`` — the only identity source the middleware+ is now allowed to trust.+ """+ app = FastAPI()++ @app.post("/mutate")+ async def mutate(request: Request): # noqa: ANN202+ if stash_principal is not None:+ request.state.aisoc_authenticated_principal = stash_principal+ return {"ok": True}++ app.add_middleware(AuditMiddleware)+ return app+++class TestForgedTokensAreNeverAudited:+ def test_a_forged_bearer_jwt_writes_no_audit_row(self, written: list) -> None:+ """The advisory's attack. A forged token on a mutating request, with no+ principal ever verified, must produce no audit write.++ On the vulnerable tree the middleware decoded this header and wrote a+ row attributed to ``[email protected]``; this assertion fails+ there, which is the point.+ """+ with TestClient(_app()) as client:+ resp = client.post("/mutate", headers={"Authorization": f"Bearer {FORGED_TOKEN}"})+ assert resp.status_code == 200+ assert written == [], (+ "the middleware wrote an audit row from an unverified Bearer token — "+ "forged claims can enter the tamper-evident chain (GHSA-w4r8-969c-67p2)"+ )++ def test_an_unauthenticated_request_writes_no_audit_row(self, written: list) -> None:+ """Control: no Authorization header, no principal, no write."""+ with TestClient(_app()) as client:+ resp = client.post("/mutate")+ assert resp.status_code == 200+ assert written == []+++class TestVerifiedPrincipalsAreStillAudited:+ def test_a_verified_principal_is_audited(self, written: list) -> None:+ """The other direction, which matters just as much.++ Reading the actor from ``request.state`` must not silently stop the+ middleware auditing authenticated routes that do not call+ ``emit_audit`` themselves — which is most of them. A request whose+ ``get_current_user`` resolved a principal is audited as that principal.+ """+ principal = types.SimpleNamespace(+ user_id="11111111-1111-1111-1111-111111111111",+ tenant_id="22222222-2222-2222-2222-222222222222",+ email="[email protected]",+ )+ with TestClient(_app(stash_principal=principal)) as client:+ resp = client.post("/mutate", headers={"Authorization": f"Bearer {FORGED_TOKEN}"})+ assert resp.status_code == 200+ assert len(written) == 1, "the middleware stopped auditing a verified, authenticated request"+ row = written[0]+ # The identity is the verified principal, never the forged header.+ assert str(row.tenant_id) == principal.tenant_id+ assert row.actor_email == principal.email+ assert row.actor_email != "[email protected]"++ def test_the_header_claims_never_override_the_principal(self, written: list) -> None:+ """Belt and braces: even with a forged header present, the written+ identity is the one ``request.state`` carries."""+ principal = types.SimpleNamespace(+ user_id="33333333-3333-3333-3333-333333333333",+ tenant_id="44444444-4444-4444-4444-444444444444",+ email="[email protected]",+ )+ with TestClient(_app(stash_principal=principal)) as client:+ client.post("/mutate", headers={"Authorization": f"Bearer {FORGED_TOKEN}"})+ assert len(written) == 1+ assert written[0].actor_email == "[email protected]"diff --git a/tests/isolation/test_audit_forgery_live.py b/tests/isolation/test_audit_forgery_live.pynew file mode 100644index 000000000..fd8e48a31--- /dev/null+++ b/tests/isolation/test_audit_forgery_live.py@@ -0,0 +1,171 @@+"""Audit-chain forgery is refused — through the real app and real Postgres.++GHSA-w4r8-969c-67p2 (CWE-347). The regression guard that proves an+unauthenticated caller cannot forge entries into a tenant's tamper-evident+audit hash chain.++Why the offline suite is not enough+-----------------------------------+`services/api/tests/test_audit_middleware_no_forgery.py` mounts the real+middleware but intercepts the database write, so it proves *which identity the+middleware decides to write*. It cannot prove that a forged request leaves the+real ``audit_log`` and ``audit_chain_head`` tables untouched, or that a+legitimate request actually lands a chained row. This suite drives+``app.main:create_application`` against real Postgres with every migration+applied, so the middleware stack, the hash-chain appender and the auth+dependencies are the ones a deployment runs.++Production posture, deliberately+--------------------------------+``ENVIRONMENT`` is **not** a bypass value here. Under ``development`` an+uncredentialed request resolves to a demo admin principal, which would be+stashed and audited — and the forged and unauthenticated controls would write+rows for the wrong reason. The whole claim is "no identity, no audit row", so+the environment must be one where no identity is synthesized.++The negative controls+---------------------+``test_a_forged_bearer_jwt_writes_no_audit_row`` and+``test_an_unauthenticated_request_writes_no_audit_row`` are what stop the+positive assertion passing for the wrong reason: a middleware that simply+stopped writing would satisfy "the forged row is absent", so+``test_a_verified_principal_is_still_audited`` proves the legitimate row is+present.+"""++from __future__ import annotations++import os+import uuid++import pytest+import pytest_asyncio++# The migration-created Default tenant — present in every deployment, which is+# what makes the victim tenant id trivially known (per the advisory).+DEFAULT_TENANT = "00000000-0000-0000-0000-000000000001"+FORGED_EMAIL = "[email protected]"++pytestmark = [+ pytest.mark.asyncio(loop_scope="module"),+ pytest.mark.skipif(+ not os.environ.get("ISOLATION_AUDIT_DSN", "").strip(),+ reason="ISOLATION_AUDIT_DSN is not set; this suite needs live infrastructure",+ ),+]+++def _dsn() -> str:+ value = os.environ.get("ISOLATION_AUDIT_DSN", "").strip()+ if not value:+ pytest.skip("ISOLATION_AUDIT_DSN is not set; this suite needs a live Postgres")+ return value+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def app_client():+ """The real application, in production posture, against real Postgres."""+ pytest.importorskip("httpx")+ os.environ["DATABASE_URL"] = _dsn()+ # Not a bypass environment — no demo principal is synthesized for an+ # uncredentialed request, so "no identity -> no audit row" is a real test.+ os.environ["ENVIRONMENT"] = "production"+ # A real, non-placeholder signing secret so the server verifies tokens+ # against a key the attacker does not have.+ os.environ.setdefault("SECRET_KEY", "ci-audit-forgery-signing-secret-at-least-32-chars")++ import httpx+ from app.main import create_application++ application = create_application()+ transport = httpx.ASGITransport(app=application)+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:+ yield client+++@pytest_asyncio.fixture(scope="module", loop_scope="module")+async def db():+ pytest.importorskip("asyncpg")+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++ engine = create_async_engine(_dsn(), future=True)+ maker = async_sessionmaker(engine, expire_on_commit=False)+ async with maker() as session:+ yield session+ await engine.dispose()+++async def _count_by_email(session, email: str) -> int: # noqa: ANN001+ import sqlalchemy++ result = await session.execute(+ sqlalchemy.text("SELECT count(*) FROM audit_log WHERE actor_email = :e"),+ {"e": email},+ )+ return int(result.scalar_one())+++def _forged_token() -> str:+ """The advisory's PoC token: attacker-chosen claims, signed with a key the+ attacker owns, so the signature is invalid against the server's secret."""+ import jwt++ return jwt.encode(+ {"tenant_id": DEFAULT_TENANT, "email": FORGED_EMAIL, "exp": 9999999999},+ "attacker-owned-key-not-the-server-key",+ algorithm="HS256",+ )+++class TestForgeryIsRefused:+ async def test_a_forged_bearer_jwt_writes_no_audit_row(self, app_client, db) -> None: # noqa: ANN001+ """A mutating request with a forged token fails auth and must leave the+ Default tenant's audit chain untouched."""+ before = await _count_by_email(db, FORGED_EMAIL)+ resp = await app_client.post("/api/v1/cases", headers={"Authorization": f"Bearer {_forged_token()}"}, json={})+ # The route rejects the invalid credential; the point is what the+ # middleware does *after* that.+ assert resp.status_code in (401, 403), resp.status_code+ after = await _count_by_email(db, FORGED_EMAIL)+ assert after == before, (+ f"a forged token added {after - before} audit row(s) attributed to {FORGED_EMAIL} "+ "— unauthenticated audit-chain forgery (GHSA-w4r8-969c-67p2)"+ )++ async def test_an_unauthenticated_request_writes_no_audit_row(self, app_client, db) -> None: # noqa: ANN001+ """Control: no Authorization header at all, no audit row."""+ marker = f"noauth-{uuid.uuid4().hex[:8]}@victim.test"+ before = await _count_by_email(db, marker)+ resp = await app_client.post("/api/v1/cases", json={})+ assert resp.status_code in (401, 403)+ assert await _count_by_email(db, marker) == before+++class TestLegitimateRequestsAreStillAudited:+ async def test_a_verified_principal_is_still_audited(self, app_client, db) -> None: # noqa: ANN001+ """The positive half. A real, active user authenticates with a server-+ signed token; the middleware must audit that request as that user, even+ when the route itself returns a non-2xx (auth succeeded, authorization+ did not)."""+ import sqlalchemy+ from app.core.security import create_access_token++ user_id = uuid.uuid4()+ email = f"real-{user_id.hex[:8]}@victim.test"+ await db.execute(+ sqlalchemy.text(+ "INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active) "+ "VALUES (:i, CAST(:t AS uuid), :e, :u, 'x', 'analyst', true)"+ ),+ {"i": user_id, "t": DEFAULT_TENANT, "e": email, "u": f"u{user_id.hex[:8]}"},+ )+ await db.commit()++ token = create_access_token({"sub": str(user_id), "tenant_id": DEFAULT_TENANT})+ before = await _count_by_email(db, email)+ resp = await app_client.post("/api/v1/cases", headers={"Authorization": f"Bearer {token}"}, json={})+ assert resp.status_code < 500, resp.status_code+ assert await _count_by_email(db, email) == before + 1, (+ "a legitimately authenticated mutating request was not audited — the middleware "+ "must still be the writer for routes that do not call emit_audit themselves"+ )