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(main): repair the four gates the merge wave left red (#1214)
Beenu Arora05b12ce74425
diff --git a/apps/web/src/components/settings/RBACView.tsx b/apps/web/src/components/settings/RBACView.tsxindex b3e6c2ecb..0ba2f7d03 100644--- a/apps/web/src/components/settings/RBACView.tsx+++ b/apps/web/src/components/settings/RBACView.tsx@@ -1,7 +1,7 @@'use client';import { useState } from 'react';-import useSWR, { mutate } from 'swr';+import useSWR from 'swr';import { EmptyState, EmptyStateIcons } from '@/components/ui/EmptyState';import { demoFallback } from '@/lib/demoFallback';import { FailureBanner } from '@/components/ui/FailureBanner';diff --git a/docker-compose.prod.yml b/docker-compose.prod.ymlindex e540d262e..9aa56339c 100644--- a/docker-compose.prod.yml+++ b/docker-compose.prod.yml@@ -453,6 +453,10 @@ services:depends_on:preflight-secrets:condition: service_completed_successfully+ # Same treatment as its sibling: the base file publishes a port for+ # local work, and in production only the console and ingest are+ # reachable from the host. `!reset` rather than an empty list, because+ # a plain override appends.ports: !reset []tempo:diff --git a/services/realtime/test/auth.test.ts b/services/realtime/test/auth.test.tsindex b02702983..c96c6a2fa 100644--- a/services/realtime/test/auth.test.ts+++ b/services/realtime/test/auth.test.ts@@ -67,17 +67,32 @@ test('rejects an empty / malformed token', () => {test('rejects a tampered signature', () => {const token = mintTicket(validClaims());- // Flip the last character to a *different* one, rather than overwriting- // the last two with a fixed 'xx'. The fixed form is a no-op whenever the- // signature already ends in 'xx', which base64url does about once in- // 4,096 runs: the test then verifies an untampered token, and the- // assertion fails for a reason that has nothing to do with the verifier.- // Seen in CI. A tamper that is guaranteed to change the bytes cannot- // pass vacuously or fail flakily.- const last = token.slice(-1);- const tampered = `${token.slice(0, -1)}${last === 'A' ? 'B' : 'A'}`;- assert.notEqual(tampered, token);- assert.equal(verifyRealtimeTicket(tampered, SECRET), null);+ // Tamper the FIRST character of the signature, not the last.+ //+ // Two earlier forms were both no-ops, for the same underlying reason:+ // the end of a base64url signature does not carry the bits you would+ // assume. HMAC-SHA256 is 32 bytes, which encodes to 43 characters+ // carrying 258 bits, so the final character's low four bits are padding+ // and decode to nothing.+ //+ // - overwriting the last two characters with a fixed 'xx' left the+ // token unchanged whenever the signature already ended in 'xx',+ // about 1 run in 4,096;+ // - flipping the last character to a different one changed only those+ // padding bits, so the decoded signature was *identical* every time+ // and the test failed deterministically.+ //+ // The first character's six bits are all significant, so this changes+ // the signature bytes for certain. The decode assertion below is what+ // makes that a checked property rather than a claim.+ const [header, payload, signature] = token.split('.');+ const flipped = (signature[0] === 'A' ? 'B' : 'A') + signature.slice(1);+ assert.notEqual(+ Buffer.from(flipped, 'base64url').toString('hex'),+ Buffer.from(signature, 'base64url').toString('hex'),+ 'the tamper must change the decoded signature, not just the text',+ );+ assert.equal(verifyRealtimeTicket(`${header}.${payload}.${flipped}`, SECRET), null);});test('rejects a token signed with a different secret', () => {diff --git a/services/teams-bot/app/notify.py b/services/teams-bot/app/notify.pyindex 2335e9938..f2c50a485 100644--- a/services/teams-bot/app/notify.py+++ b/services/teams-bot/app/notify.py@@ -54,10 +54,19 @@ class ApprovalCardRequest(BaseModel):action: dict[str, Any] = Field(..., description="The action record: id, action_type, target, risk_level, rationale.")case: dict[str, Any] = Field(default_factory=dict, description="Case context rendered into the card.")- webhook_url: str | None = Field(- default=None,- description="Override the configured channel webhook. Useful for per-tenant routing.",- )+ # No `webhook_url`. It used to be accepted here as a per-tenant routing+ # override and posted to directly, which is a full server-side request+ # forgery: anything that can reach this pod chose where an internal+ # service sent an authenticated-looking POST. CodeQL flagged it+ # `py/full-ssrf` at critical.+ #+ # Removed rather than validated. The only production caller+ # (`services/agents/app/investigator/chatops_notify.py`) never set it --+ # only the tests did -- so the field was attack surface with no user,+ # and the destination belongs to the deployment's configuration the way+ # the tenant belongs to the credential. Per-tenant routing, if it is+ # wanted later, is a stored per-tenant setting this service reads, not+ # a string in a request body.requested_by: str = Field(default="",description=(@@ -79,6 +88,9 @@ def _authorized(supplied: str | None) -> bool:expected = os.environ.get("AISOC_INTERNAL_TOKEN", "").strip()if not expected:return False+ # Narrowed with a statement rather than `bool(supplied) and ...`: the+ # call form is identical at runtime, and the type checker cannot carry+ # the truthiness of a `str | None` across `and` into `.strip()`.if not supplied:return Falsereturn hmac.compare_digest(supplied.strip(), expected)@@ -101,7 +113,7 @@ async def post_approval_card(if not _authorized(x_internal_token):raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="internal token required")- webhook_url = (body.webhook_url or os.environ.get("TEAMS_APPROVALS_WEBHOOK_URL", "")).strip()+ webhook_url = os.environ.get("TEAMS_APPROVALS_WEBHOOK_URL", "").strip()if not webhook_url:logger.info("teams_bot.approval_card_skipped", reason="TEAMS_APPROVALS_WEBHOOK_URL is unset", action_id=body.action.get("id"))return {"posted": False, "reason": "no approvals webhook configured"}diff --git a/services/teams-bot/tests/test_notify.py b/services/teams-bot/tests/test_notify.pyindex 9b863092a..f89dc1d94 100644--- a/services/teams-bot/tests/test_notify.py+++ b/services/teams-bot/tests/test_notify.py@@ -22,6 +22,9 @@ def client(monkeypatch: pytest.MonkeyPatch) -> TestClient:monkeypatch.setenv("AISOC_INTERNAL_TOKEN", "tok")monkeypatch.setenv("AISOC_TEAMS_CALLBACK_SECRET", "signing-secret")monkeypatch.setenv("AISOC_WEB_BASE_URL", "https://console.example.com")+ # The destination is deployment configuration, not a request field. It+ # used to arrive in the body, which made this route a full SSRF.+ monkeypatch.setenv("TEAMS_APPROVALS_WEBHOOK_URL", "https://teams.example/hook")return TestClient(app)@@ -84,7 +87,7 @@ def test_an_unsigned_card_is_refused(client: TestClient, monkeypatch: pytest.Monmonkeypatch.setenv("AISOC_TEAMS_CALLBACK_SECRET", "")response = client.post("/internal/approval-card",- json={"action": _ACTION, "webhook_url": "https://teams.example/hook"},+ json={"action": _ACTION},headers={"X-AiSOC-Internal-Token": "tok"},)assert response.json()["posted"] is False@@ -106,7 +109,7 @@ def test_a_posted_card_is_an_adaptive_card_envelope(client: TestClient, monkeypa)response = client.post("/internal/approval-card",- json={"action": _ACTION, "case": {"id": "c-1", "severity": "high"}, "webhook_url": "https://teams.example/hook"},+ json={"action": _ACTION, "case": {"id": "c-1", "severity": "high"}},headers={"X-AiSOC-Internal-Token": "tok"},)assert response.json() == {"posted": True}@@ -124,8 +127,49 @@ def test_a_rejected_post_is_not_reported_as_delivered(client: TestClient, monkey)response = client.post("/internal/approval-card",- json={"action": _ACTION, "webhook_url": "https://teams.example/hook"},+ json={"action": _ACTION},headers={"X-AiSOC-Internal-Token": "tok"},)assert response.json()["posted"] is Falseassert "400" in response.json()["reason"]+++def test_a_caller_cannot_choose_the_destination(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ """The request body must not be able to redirect the post.++ `webhook_url` was accepted here as a per-tenant routing override and+ posted to directly, so anything that could reach this pod chose where an+ internal service sent an authenticated-looking request — CodeQL's+ `py/full-ssrf`, at critical. The field is gone rather than validated,+ because the only production caller never set it.++ Pydantic ignores an unknown field by default, so the attacker-supplied+ URL is simply never read; this asserts the post still goes to the+ configured host, which is the property that matters.+ """+ seen: dict[str, str] = {}++ class _Response:+ status_code = 200++ class _Client:+ async def __aenter__(self) -> _Client:+ return self++ async def __aexit__(self, *_: object) -> None:+ return None++ async def post(self, url: str, **_: object) -> _Response:+ seen["url"] = url+ return _Response()++ monkeypatch.setattr(notify.httpx, "AsyncClient", lambda *a, **k: _Client())++ response = client.post(+ "/internal/approval-card",+ json={"action": _ACTION, "webhook_url": "http://169.254.169.254/latest/meta-data/"},+ headers={"X-AiSOC-Internal-Token": "tok"},+ )++ assert response.json()["posted"] is True+ assert seen["url"] == "https://teams.example/hook"diff --git a/tests/isolation/test_sso_live.py b/tests/isolation/test_sso_live.pyindex 02a021d43..9bc39e059 100644--- a/tests/isolation/test_sso_live.py+++ b/tests/isolation/test_sso_live.py@@ -293,8 +293,16 @@ class _OidcProvider:# splitting even in a fixture, and a provider that lets a# crafted `redirect_uri` inject a header is not modelling# a real one.- target = _header_safe((query.get("redirect_uri") or [""])[0])- state = _header_safe((query.get("state") or [""])[0])+ # Sanitised **inline**, not through `_header_safe`. The+ # helper does exactly this, but CodeQL's taint tracker+ # does not follow a sanitiser across a function+ # boundary and read the echo as+ # `py/http-response-splitting`; it does recognise the+ # inline substitution. The same blindness is why this+ # repository sanitises log values at the call site+ # rather than in a `_log_safe()` helper.+ target = _HEADER_UNSAFE.sub("", (query.get("redirect_uri") or [""])[0])+ state = _HEADER_UNSAFE.sub("", (query.get("state") or [""])[0])self.send_response(302)self.send_header("Location", f"{target}?code={code}&state={state}")self.send_header("Content-Length", "0")