Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

fix: address all remaining GitHub Code Scanning alerts

Beenu Arora585565da6ca7
diff --git a/packages/aisoc-cli/src/aisoc_cli/main.py b/packages/aisoc-cli/src/aisoc_cli/main.py
index c774f08cc..0753282ea 100644
--- a/packages/aisoc-cli/src/aisoc_cli/main.py
+++ b/packages/aisoc-cli/src/aisoc_cli/main.py
@@ -25,7 +25,6 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import (
from jsonschema import ValidationError, validate
from rich.console import Console
from rich.panel import Panel
-from rich.syntax import Syntax
from rich.table import Table
console = Console()
diff --git a/plugins/okta-connector/plugin.py b/plugins/okta-connector/plugin.py
index 50b655f61..b2eddc16f 100644
--- a/plugins/okta-connector/plugin.py
+++ b/plugins/okta-connector/plugin.py
@@ -68,6 +68,7 @@ class Plugin:
action = payload.get("action", "get_user")
user_id = payload.get("user_id", "")
+ result: dict = {"error": f"Unknown action: {action}"}
async with self._client(context) as client:
match action:
case "get_user":
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index 275894134..760f75fc0 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -351,10 +351,16 @@ async def investigate_case(
return InvestigateResponse(**data)
-def _validate_run_id(run_id: str) -> None:
- """Raise 422 if run_id is not a UUID to prevent partial-SSRF via path injection."""
- if not _RUN_ID_RE.match(run_id):
- raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Invalid run_id format")
+def _validate_run_id(run_id: str) -> str:
+ """Raise 422 if run_id is not a UUID; return canonicalized UUID string to break taint flow."""
+ try:
+ # Round-trip through uuid.UUID to produce a safe, canonical string
+ return str(uuid.UUID(run_id))
+ except (ValueError, AttributeError) as exc:
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
+ detail="Invalid run_id format",
+ ) from exc
@router.get("/{case_id}/investigations/{run_id}")
@@ -364,10 +370,10 @@ async def get_case_investigation(
current_user: Annotated[AuthUser, Depends(require_permission("cases:read"))],
) -> dict[str, Any]:
"""Proxy: poll investigation run status from the agents service."""
- _validate_run_id(run_id)
+ safe_run_id = _validate_run_id(run_id)
try:
async with httpx.AsyncClient(timeout=10.0) as client:
- resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}")
+ resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{safe_run_id}")
resp.raise_for_status()
return resp.json()
except httpx.HTTPStatusError as exc:
@@ -385,10 +391,10 @@ async def get_case_report_md(
"""Proxy: download Markdown incident report from the agents service."""
from fastapi.responses import PlainTextResponse
- _validate_run_id(run_id)
+ safe_run_id = _validate_run_id(run_id)
try:
async with httpx.AsyncClient(timeout=30.0) as client:
- resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}/report.md")
+ resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{safe_run_id}/report.md")
resp.raise_for_status()
return PlainTextResponse(content=resp.text)
except httpx.HTTPStatusError as exc:
@@ -406,10 +412,10 @@ async def get_case_report_html(
"""Proxy: download HTML incident report from the agents service."""
from fastapi.responses import HTMLResponse
- _validate_run_id(run_id)
+ safe_run_id = _validate_run_id(run_id)
try:
async with httpx.AsyncClient(timeout=30.0) as client:
- resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}/report.html")
+ resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{safe_run_id}/report.html")
resp.raise_for_status()
return HTMLResponse(content=resp.text)
except httpx.HTTPStatusError as exc:
@@ -427,15 +433,15 @@ async def get_case_report_pdf(
"""Proxy: download PDF incident report (rendered by weasyprint in agents service)."""
from fastapi.responses import Response as FastAPIResponse
- _validate_run_id(run_id)
+ safe_run_id = _validate_run_id(run_id)
try:
async with httpx.AsyncClient(timeout=60.0) as client:
- resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{run_id}/report.pdf")
+ resp = await client.get(f"{_AGENTS_URL}/api/v1/investigations/{safe_run_id}/report.pdf")
resp.raise_for_status()
return FastAPIResponse(
content=resp.content,
media_type="application/pdf",
- headers={"Content-Disposition": f'attachment; filename="aisoc-report-{run_id}.pdf"'},
+ headers={"Content-Disposition": f'attachment; filename="aisoc-report-{safe_run_id}.pdf"'},
)
except httpx.HTTPStatusError as exc:
raise HTTPException(status_code=exc.response.status_code, detail="Upstream service error") from exc
diff --git a/services/api/app/api/v1/endpoints/connectors.py b/services/api/app/api/v1/endpoints/connectors.py
index ed5be33ea..5b7b16b5c 100644
--- a/services/api/app/api/v1/endpoints/connectors.py
+++ b/services/api/app/api/v1/endpoints/connectors.py
@@ -223,7 +223,11 @@ async def _proxy_test_connection(
async with httpx.AsyncClient(timeout=_CATALOG_TIMEOUT) as client:
resp = await client.post(url, json=payload)
except httpx.HTTPError as exc:
- logger.warning("connectors_service.test.unreachable url=%s err=%s", url, exc)
+ logger.warning(
+ "connectors_service.test.unreachable url=%s err=%s",
+ url,
+ str(exc).replace("\n", " ").replace("\r", " "),
+ )
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="connectors service is unavailable; cannot test connection",
diff --git a/services/api/app/api/v1/endpoints/playbooks.py b/services/api/app/api/v1/endpoints/playbooks.py
index b9493b479..9f825ee41 100644
--- a/services/api/app/api/v1/endpoints/playbooks.py
+++ b/services/api/app/api/v1/endpoints/playbooks.py
@@ -24,12 +24,20 @@ router = APIRouter(prefix="/playbooks", tags=["playbooks"])
_SAFE_ID_RE = re.compile(r"^[0-9a-zA-Z_\-]{1,128}$")
-def _validate_path_id(value: str, name: str = "id") -> None:
+def _validate_path_id(value: str, name: str = "id") -> str:
+ """Validate that *value* is a safe ID and return it to break the taint flow.
+
+ Raising HTTPException here prevents any tainted data from reaching _proxy.
+ Returning the validated string (rather than void) lets callers use the
+ return value in path construction, which CodeQL recognises as untainted.
+ """
if not _SAFE_ID_RE.match(value):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Invalid {name} format",
)
+ # Return a new string built from the match to break the taint chain.
+ return _SAFE_ID_RE.match(value).group(0) # type: ignore[union-attr]
async def _proxy(method: str, path: str, **kwargs) -> Any:
@@ -70,31 +78,31 @@ async def list_runs(limit: int = 50):
@router.get("/runs/{run_id}", summary="Get a playbook run")
async def get_run(run_id: str):
- _validate_path_id(run_id, "run_id")
- return await _proxy("GET", f"/runs/{run_id}")
+ safe_run_id = _validate_path_id(run_id, "run_id")
+ return await _proxy("GET", f"/runs/{safe_run_id}")
@router.get("/{playbook_id}", summary="Get a playbook")
async def get_playbook(playbook_id: str):
- _validate_path_id(playbook_id, "playbook_id")
- return await _proxy("GET", f"/{playbook_id}")
+ safe_id = _validate_path_id(playbook_id, "playbook_id")
+ return await _proxy("GET", f"/{safe_id}")
@router.put("/{playbook_id}", summary="Update a playbook")
async def update_playbook(playbook_id: str, request: Request):
- _validate_path_id(playbook_id, "playbook_id")
+ safe_id = _validate_path_id(playbook_id, "playbook_id")
body = await request.json()
- return await _proxy("PUT", f"/{playbook_id}", json=body)
+ return await _proxy("PUT", f"/{safe_id}", json=body)
@router.delete("/{playbook_id}", summary="Delete a playbook", status_code=204, response_model=None)
async def delete_playbook(playbook_id: str):
- _validate_path_id(playbook_id, "playbook_id")
- await _proxy("DELETE", f"/{playbook_id}")
+ safe_id = _validate_path_id(playbook_id, "playbook_id")
+ await _proxy("DELETE", f"/{safe_id}")
@router.post("/{playbook_id}/run", summary="Execute a playbook", status_code=202)
async def run_playbook(playbook_id: str, request: Request):
- _validate_path_id(playbook_id, "playbook_id")
+ safe_id = _validate_path_id(playbook_id, "playbook_id")
body = await request.json()
- return await _proxy("POST", f"/{playbook_id}/run", json=body)
+ return await _proxy("POST", f"/{safe_id}/run", json=body)
diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.py
index 01b834de1..828153e7b 100644
--- a/services/api/app/auth/oidc.py
+++ b/services/api/app/auth/oidc.py
@@ -28,7 +28,7 @@ import re
import secrets
from datetime import UTC, datetime, timedelta
from typing import Any
-from urllib.parse import urlencode
+from urllib.parse import urlencode, urlparse
import httpx
import jwt as _jwt
@@ -282,10 +282,15 @@ async def oidc_logout(request: Request, post_logout_redirect_uri: str = "/") ->
try:
provider = await _discover(issuer)
end_session = provider.get("end_session_endpoint")
- if end_session:
- params = urlencode({"post_logout_redirect_uri": safe_uri})
- response = RedirectResponse(url=f"{end_session}?{params}", status_code=302)
- response.delete_cookie("aisoc_token")
+ if end_session and isinstance(end_session, str):
+ # Validate end_session_endpoint is a safe HTTPS URL to prevent open redirect
+ _parsed = urlparse(end_session)
+ if _parsed.scheme == "https" and _parsed.netloc:
+ params = urlencode({"post_logout_redirect_uri": safe_uri})
+ response = RedirectResponse(url=f"{end_session}?{params}", status_code=302)
+ response.delete_cookie("aisoc_token")
+ else:
+ logger.warning("OIDC end_session_endpoint is not a valid HTTPS URL, skipping: %s", end_session)
except Exception as exc: # noqa: BLE001
logger.debug("OIDC end_session discovery failed, falling back to local logout: %s", exc)
diff --git a/services/api/app/services/plugin_manager.py b/services/api/app/services/plugin_manager.py
index 94ff91ebc..36a2e62af 100644
--- a/services/api/app/services/plugin_manager.py
+++ b/services/api/app/services/plugin_manager.py
@@ -242,8 +242,8 @@ def _read_signature(plugin_dir: Path) -> bytes | None:
decoded = bytes.fromhex(text.decode("ascii"))
if len(decoded) == 64: # Ed25519 signatures are exactly 64 bytes
return decoded
- except (UnicodeDecodeError, ValueError):
- pass # not a hex-encoded Ed25519 signature; fall through to raw bytes
+ except (UnicodeDecodeError, ValueError):
+ pass # not a hex-encoded Ed25519 signature; fall through to raw bytes
# Otherwise treat the file as raw signature bytes.
if len(raw) == 64:
diff --git a/services/purple-team/app/services/drift.py b/services/purple-team/app/services/drift.py
index bbed2c15a..d11d13a93 100644
--- a/services/purple-team/app/services/drift.py
+++ b/services/purple-team/app/services/drift.py
@@ -22,7 +22,6 @@ runs happened.
from __future__ import annotations
-import logging
import uuid
from datetime import UTC, datetime
from typing import Any
@@ -33,8 +32,6 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.models.purple_team import AtomicTest, DetectionDriftSnapshot, TestExecution
from app.services.coverage import build_coverage_matrix
-LOG = logging.getLogger(__name__)
-
async def compute_coverage_for_tenant(
session: AsyncSession,
@@ -141,7 +138,7 @@ from app.services.drift_diff import compute_drift # noqa: E402
__all__ = [
"compute_drift",
- "get_latest_snapshots",
+ "latest_two_snapshots",
"list_snapshots",
- "take_snapshot",
+ "capture_snapshot",
]
diff --git a/services/realtime/src/index.ts b/services/realtime/src/index.ts
index 8c38bf374..94f1bd301 100644
--- a/services/realtime/src/index.ts
+++ b/services/realtime/src/index.ts
@@ -137,21 +137,30 @@ function broadcastToTenant(tenantId: string, message: { type: string } & Record<
}
}
+// Generic IP-based rate limiter factory.
+function makeRateLimiter(limit: number, windowMs: number) {
+ const counts = new Map<string, { count: number; resetAt: number }>();
+ return function rateLimitExceeded(ip: string): boolean {
+ const now = Date.now();
+ let entry = counts.get(ip);
+ if (!entry || now > entry.resetAt) {
+ entry = { count: 0, resetAt: now + windowMs };
+ counts.set(ip, entry);
+ }
+ entry.count += 1;
+ return entry.count > limit;
+ };
+}
+
// Simple IP-based rate limiter for SSE: max 20 connections per IP per minute.
-const sseConnectCounts = new Map<string, { count: number; resetAt: number }>();
const SSE_RATE_LIMIT = 20;
const SSE_RATE_WINDOW_MS = 60_000;
+const sseRateLimitExceeded = makeRateLimiter(SSE_RATE_LIMIT, SSE_RATE_WINDOW_MS);
-function sseRateLimitExceeded(ip: string): boolean {
- const now = Date.now();
- let entry = sseConnectCounts.get(ip);
- if (!entry || now > entry.resetAt) {
- entry = { count: 0, resetAt: now + SSE_RATE_WINDOW_MS };
- sseConnectCounts.set(ip, entry);
- }
- entry.count += 1;
- return entry.count > SSE_RATE_LIMIT;
-}
+// Rate limiter for the internal agent-event endpoint: max 200 req/s per IP.
+// This endpoint is internal-only (token-gated) but we still rate-limit to
+// protect against misconfigured or runaway callers.
+const internalEventRateLimitExceeded = makeRateLimiter(200, 60_000);
// --- SSE endpoint ---
app.get('/sse', (req, res) => {
@@ -291,6 +300,14 @@ app.post('/internal/push', async (req, res) => {
app.post('/internal/agent-event', (req, res) => {
if (!requireInternal(req, res)) return;
+ const ip = (req.headers['x-forwarded-for'] as string | undefined)?.split(',')[0]?.trim()
+ || req.socket.remoteAddress
+ || 'unknown';
+ if (internalEventRateLimitExceeded(ip)) {
+ res.status(429).json({ error: 'Rate limit exceeded' });
+ return;
+ }
+
const { tenant_id, run_id, kind, agent, summary, data } = req.body as {
tenant_id?: string;
run_id: string;