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(mcp): authorize the completion route against its own call, and close two CodeQL findings
Beenu Arora73423a81d57f
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex c959ff9d6..4cb43de9c 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -7079,7 +7079,31 @@ paths:tags:- mcpsummary: Complete Tool Call- description: Record how a call that was allowed turned out.+ description: 'Record how a call that was allowed turned out.+++ Authorized against the call being reported on, not by a blanket++ permission. There is no single permission every MCP caller holds — a key++ minted for ``alerts:read`` is a legitimate caller — so a blanket++ dependency here would either be wider than the call it describes or++ exclude the callers it exists for.+++ Instead this resolves the ``mcp:tool_call`` row the authorize step wrote++ for this id in this tenant, and requires the principal to still hold the++ permission *that call* needed. Two consequences, both wanted: a caller++ cannot write an outcome for a call nobody authorized here, and a key++ whose scopes were narrowed between the call and the report is refused++ rather than quietly accepted.'operationId: complete_tool_call_api_v1_mcp_tool_calls__call_id__complete_postsecurity:- HTTPBearer: []diff --git a/infra/helm/aisoc/Chart.yaml b/infra/helm/aisoc/Chart.yamlindex 8bbb65c60..d2577f0a9 100644--- a/infra/helm/aisoc/Chart.yaml+++ b/infra/helm/aisoc/Chart.yaml@@ -25,7 +25,7 @@ type: application# the chart refuses grants it used to accept (see the v14.0.0 BREAKING# section), and the chart's major is the only coordinate a consumer pulling# `oci://ghcr.io/beenuar/charts/aisoc` sees before they install it.-version: 7.6.0+version: 7.7.0# Used as the image tag wherever a `tag:` in values.yaml is left empty, so# it has to be a tag the registry actually holds — it read "5.2.0", which# exists for no image, so every pod of a default install would have gone todiff --git a/scripts/check_mcp_over_http.py b/scripts/check_mcp_over_http.pyindex db39bec90..64b4b54bf 100644--- a/scripts/check_mcp_over_http.py+++ b/scripts/check_mcp_over_http.py@@ -152,7 +152,12 @@ def _read_only_flags(source: str) -> dict[str, bool]:match = re.search(r"readOnlyHint:\s*(true|false)", block)# An absent annotation is not a claim to be read-only, so the safe# reading -- and the one the MCP client already applies -- is False.- flags[hit.group(1)] = bool(match) and match.group(1) == "true"+ # `match is not None`, not `bool(match)`: the two are equivalent at+ # runtime and only the first narrows the Optional for the type+ # checker, which is why the baseline gate reported a `union-attr`+ # here. Narrowing is the right fix; a `type: ignore` would hide the+ # one thing that makes the next edit safe.+ flags[hit.group(1)] = match is not None and match.group(1) == "true"return flagsdiff --git a/services/api/app/api/v1/endpoints/mcp_access.py b/services/api/app/api/v1/endpoints/mcp_access.pyindex cfac61e08..5a84d6a3f 100644--- a/services/api/app/api/v1/endpoints/mcp_access.py+++ b/services/api/app/api/v1/endpoints/mcp_access.py@@ -59,6 +59,7 @@ from sqlalchemy import selectfrom app.api.v1.deps import AuthUser, require_permissionfrom app.db.rls import TenantDBSession+from app.models.audit import AuditLogfrom app.models.mcp_access import McpToolApproval, McpToolGrantfrom app.services.audit import emit_auditfrom app.services.mcp_access import (@@ -232,12 +233,49 @@ async def complete_tool_call(db: TenantDBSession,current_user: AuthUser,) -> None:- """Record how a call that was allowed turned out."""+ """Record how a call that was allowed turned out.++ Authorized against the call being reported on, not by a blanket+ permission. There is no single permission every MCP caller holds — a key+ minted for ``alerts:read`` is a legitimate caller — so a blanket+ dependency here would either be wider than the call it describes or+ exclude the callers it exists for.++ Instead this resolves the ``mcp:tool_call`` row the authorize step wrote+ for this id in this tenant, and requires the principal to still hold the+ permission *that call* needed. Two consequences, both wanted: a caller+ cannot write an outcome for a call nobody authorized here, and a key+ whose scopes were narrowed between the call and the report is refused+ rather than quietly accepted.+ """if body.outcome not in COMPLETION_OUTCOMES:raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,detail=f"Unknown outcome: {body.outcome}. Expected one of {sorted(COMPLETION_OUTCOMES)}.",)++ decision = (+ await db.execute(+ select(AuditLog)+ .where(+ AuditLog.tenant_id == current_user.tenant_id,+ AuditLog.action == "mcp:tool_call",+ AuditLog.resource_id == str(call_id),+ )+ .limit(1)+ )+ ).scalar_one_or_none()+ if decision is None:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"No authorize decision was recorded for call {call_id} in this tenant.",+ )+ required = str((decision.changes or {}).get("required_permission") or "").strip()+ if required:+ # The principal's own path, which is also what `authorize` used. A+ # second copy of the logic here would be a second authority that can+ # disagree with the first.+ current_user.require_permission(required)await emit_audit(db=db,tenant_id=current_user.tenant_id,diff --git a/services/api/tests/test_mcp_access.py b/services/api/tests/test_mcp_access.pyindex c6fbb3e85..da48e08c4 100644--- a/services/api/tests/test_mcp_access.py+++ b/services/api/tests/test_mcp_access.py@@ -187,6 +187,39 @@ async def test_the_outcome_is_a_second_row_because_audit_rows_are_immutable(clieassert results[0].changes == {"outcome": "success", "latency_ms": 42}+async def test_an_outcome_cannot_be_reported_for_a_call_nobody_authorized(client) -> None:+ """The completion route is authorized against the call it reports on.++ There is no single permission every MCP caller holds, so a blanket+ dependency would be either wider than the call or exclusive of the+ callers it exists for. Resolving the authorize row instead means a+ caller cannot write an outcome for a call that was never decided here.+ """+ res = client.post(+ f"/api/v1/mcp/tool-calls/{uuid.uuid4()}/complete",+ json={"outcome": "success", "latency_ms": 1},+ )+ assert res.status_code == 404+ assert "No authorize decision was recorded" in res.text+++async def test_a_key_narrowed_after_the_call_cannot_report_its_outcome(client) -> None:+ """A scope removed between the call and the report is refused, not ignored."""+ authorized = client.post("/api/v1/mcp/tool-calls/authorize", json={"tool_name": READ_TOOL, "arguments": {}}).json()+ assert authorized["outcome"] == "allow"++ client.state_holder["user"] = _principal( # type: ignore[attr-defined]+ user_id=ANALYST, scopes=["cases:read"], key_prefix="aisoc_analyst"+ )+ res = client.post(+ f"/api/v1/mcp/tool-calls/{authorized['call_id']}/complete",+ json={"outcome": "success", "latency_ms": 1},+ )+ assert res.status_code == 403++@pytest.mark.asyncioasync def test_an_outcome_outside_the_closed_set_is_refused(client) -> None:call_id = uuid.uuid4()diff --git a/services/mcp/src/gate.ts b/services/mcp/src/gate.tsindex a26e5fe50..dc6c76cf4 100644--- a/services/mcp/src/gate.ts+++ b/services/mcp/src/gate.ts@@ -57,6 +57,19 @@ export class GateUnavailableError extends Error {}}+/** The only shape a User-Agent from this module may take. */+const USER_AGENT_RE = /^aisoc-mcp\/[0-9A-Za-z.+-]{1,32}(?: \(\+https:\/\/[A-Za-z0-9./_-]{1,80}\))?$/;++/**+ * A User-Agent that cannot carry anything but a version string.+ *+ * Exported for the test: a guard whose behaviour is only visible inside a+ * network call is one nobody can check.+ */+export function safeUserAgent(candidate: string): string {+ return USER_AGENT_RE.test(candidate) ? candidate : "aisoc-mcp";+}+async function postJson(url: string,bearer: string,@@ -73,7 +86,16 @@ async function postJson(Authorization: bearer.startsWith("Bearer ") ? bearer : `Bearer ${bearer}`,"Content-Type": "application/json",Accept: "application/json",- "User-Agent": userAgent,+ // Constrained rather than passed through. `cfg.userAgent` is built+ // from the version in `package.json`, which `config.ts` reads off+ // disk — so a header built straight from it is file content+ // reaching an outbound request, which CodeQL reports as+ // `js/file-access-to-http` and is right to. A `fullmatch` on the+ // shape this value is allowed to have is the strongest guard+ // available here: anything that is not `aisoc-mcp/<version> (...)`+ // is replaced rather than escaped, because an escaped value that+ // reaches the server and means nothing is worse than a known one.+ "User-Agent": safeUserAgent(userAgent),},body: JSON.stringify(body),signal: controller.signal,diff --git a/services/mcp/src/http.ts b/services/mcp/src/http.tsindex b22c5d16a..232588c34 100644--- a/services/mcp/src/http.ts+++ b/services/mcp/src/http.ts@@ -190,7 +190,18 @@ export async function handleMcpRequest(try {body = req.method === "POST" ? await readJsonBody(req, options.maxBodyBytes) : undefined;} catch (err) {- rpcError(res, 413, String(err instanceof Error ? err.message : err));+ // A fixed sentence, not the thrown message. The only error reachable+ // here is this module's own size refusal or a JSON parse failure, and+ // a parse failure's message quotes the offending input back to whoever+ // sent it — which is both useless to them and an information-exposure+ // finding (`js/stack-trace-exposure`). The bound is the actionable+ // fact, so the bound is what is returned; the detail goes to stderr.+ log.info(`rejected a request body: ${String(err instanceof Error ? err.message : err)}`);+ rpcError(+ res,+ 413,+ `The request body could not be read. It must be JSON and at most ${options.maxBodyBytes} bytes.`,+ );return;}diff --git a/services/mcp/tests/http.test.ts b/services/mcp/tests/http.test.tsindex f341493b8..ae49ada3e 100644--- a/services/mcp/tests/http.test.ts+++ b/services/mcp/tests/http.test.ts@@ -13,6 +13,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { makeLogger, resolveConfig, parseArgs } from "../src/config.js";import { bearerFrom, handleMcpRequest, resolveHttpOptions, HEALTH_PATH, MCP_PATH } from "../src/http.js";+import { safeUserAgent } from "../src/gate.js";interface RecordedCall {path: string;@@ -294,6 +295,26 @@ describe("the HTTP transport", () => {expect(body.result.content[0].text).toContain("unrecognised outcome");});+ it("refuses an oversized body with the bound, not with the thrown message", async () => {+ await mcp.start(api.url);+ const res = await fetch(`${mcp.url}${MCP_PATH}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Accept: "application/json, text/event-stream",+ Authorization: "Bearer aisoc_caller_key",+ },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", pad: "x".repeat(2_000_000) }),+ });+ expect(res.status).toBe(413);+ const body = await res.json();+ // The bound is the actionable fact. A parse failure's message quotes+ // the offending input back at the sender, which is useless to them and+ // is an information-exposure finding.+ expect(body.error.message).toContain("at most 1048576 bytes");+ expect(body.error.message).not.toContain("JSON.parse");+ });+it("serves the MCP endpoint only at /mcp", async () => {await mcp.start(api.url);const res = await fetch(`${mcp.url}/`, {@@ -306,6 +327,23 @@ describe("the HTTP transport", () => {});});+describe("safeUserAgent", () => {+ it("passes the shape this package produces", () => {+ expect(safeUserAgent("aisoc-mcp/0.1.0 (+https://github.com/beenuar/AiSOC)")).toBe(+ "aisoc-mcp/0.1.0 (+https://github.com/beenuar/AiSOC)",+ );+ expect(safeUserAgent("aisoc-mcp/0.1.0")).toBe("aisoc-mcp/0.1.0");+ });++ it("replaces anything else rather than escaping it", () => {+ // The value is built from a version read off disk. An escaped header+ // that reaches the server and means nothing is worse than a known one.+ expect(safeUserAgent("aisoc-mcp/0.1.0\r\nX-Injected: 1")).toBe("aisoc-mcp");+ expect(safeUserAgent("curl/8")).toBe("aisoc-mcp");+ expect(safeUserAgent("")).toBe("aisoc-mcp");+ });+});+describe("resolveHttpOptions", () => {it("binds loopback by default", () => {expect(resolveHttpOptions({} as NodeJS.ProcessEnv).host).toBe("127.0.0.1");