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,web): asyncpg sslmode support + falsy caseId guard for attack-path
Beenu Arora1cea7d1e7296
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsxindex 002327b4e..631cd71b4 100644--- a/apps/web/src/components/cases/CaseWorkspace.tsx+++ b/apps/web/src/components/cases/CaseWorkspace.tsx@@ -768,15 +768,18 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {/>)}- {/* Attack path tab — reconstructed graph for this case */}+ {/* Attack path tab — reconstructed graph for this case.+ We use the URL `caseId` prop rather than `caseRecord.id` because some+ backend variants return the case body without an `id` field; the URL+ is the canonical identifier here. */}{activeTab === 'attack-path' && (- <AttackPathPanel caseId={caseRecord.id} />+ <AttackPathPanel caseId={caseRecord.id || caseId} />)}{/* Ledger tab — persistent, replayable agent decision log */}{activeTab === 'ledger' && (<InvestigationLedger- caseId={caseRecord.id}+ caseId={caseRecord.id || caseId}activeRunId={investigationRunId}onSelectRun={(rid) => setInvestigationRunId(rid)}/>@@ -786,7 +789,7 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {{activeTab === 'report' && (<ReportPanelmarkdown={reportMd}- caseId={caseRecord.id}+ caseId={caseRecord.id || caseId}runId={investigationRunId ?? ''}/>)}@@ -1136,12 +1139,27 @@ function InvestigationPanel({* the agent is wired up but simply has no graph context yet.*/function AttackPathPanel({ caseId }: { caseId: string }) {+ // Guard: when caseId is falsy (router not yet hydrated, fallback path mid-build,+ // backend response without an id field) we render the empty state instead of+ // firing /api/v1/graph/attack-path/undefined which 500s and pollutes the UI.+ const hasCaseId = Boolean(caseId);const { data, error, isLoading } = useSWR<CaseAttackPath | null>(- `case:${caseId}:attack-path`,+ hasCaseId ? `case:${caseId}:attack-path` : null,() => graphApi.getCaseAttackPath(caseId, { maxDepth: 4 }),{ revalidateOnFocus: false },);+ if (!hasCaseId) {+ return (+ <div className="flex flex-col items-center justify-center rounded-xl border border-dashed border-slate-700/60 bg-slate-900/30 py-16 text-center">+ <p className="text-sm font-medium text-slate-300">Loading case context…</p>+ <p className="mt-1 max-w-md text-xs text-slate-500">+ The attack-path graph appears once the case is loaded.+ </p>+ </div>+ );+ }+if (isLoading) {return (<div className="space-y-3">diff --git a/services/api/app/db/database.py b/services/api/app/db/database.pyindex b73842e72..c704e6144 100644--- a/services/api/app/db/database.py+++ b/services/api/app/db/database.py@@ -1,6 +1,8 @@"""Database connection management."""from collections.abc import AsyncGenerator+from typing import Any+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_enginefrom sqlalchemy.orm import DeclarativeBase@@ -8,7 +10,14 @@ from sqlalchemy.orm import DeclarativeBasefrom app.core.config import settings-def _normalize_async_pg_url(url: str) -> str:+# libpq sslmode values -> what asyncpg's `ssl` kwarg expects.+# asyncpg accepts: "disable" | "allow" | "prefer" | "require" | "verify-ca" | "verify-full"+# but NOT under the libpq query-string name `sslmode=`. We pop it from the URL+# and forward it as a connect_arg so asyncpg sees it on the right hand.+_SSLMODE_PASSTHROUGH = {"disable", "allow", "prefer", "require", "verify-ca", "verify-full"}+++def _normalize_async_pg_url(url: str) -> tuple[str, dict[str, Any]]:"""Coerce common Postgres URL forms into the SQLAlchemy 2.x async dialect.Fly.io's ``flyctl postgres attach`` (and Heroku, and most managed@@ -20,27 +29,55 @@ def _normalize_async_pg_url(url: str) -> str:selects the synchronous ``psycopg2`` dialect, which the async enginerejects ("the asyncio extension requires an async driver").- This shim rewrites both forms to ``postgresql+asyncpg://``, which is- what we actually run. It is a no-op for URLs that already specify a- driver (``postgresql+asyncpg``, ``postgresql+psycopg``, etc.), so- operators who want to override the driver via secret can still do so.+ Managed Postgres providers also append ``?sslmode=require`` (libpq+ syntax) which asyncpg's ``connect()`` rejects with+ ``TypeError: connect() got an unexpected keyword argument 'sslmode'``.+ We strip the param and translate it into an explicit ``connect_args``+ payload that asyncpg understands.++ Returns the normalized URL plus a ``connect_args`` dict that callers+ forward to ``create_async_engine``."""if url.startswith("postgres://"):- return "postgresql+asyncpg://" + url[len("postgres://") :]- if url.startswith("postgresql://"):+ url = "postgresql+asyncpg://" + url[len("postgres://") :]+ elif url.startswith("postgresql://"):# No driver specified -> default to asyncpg (the only async driver# we ship with). Anything matching "postgresql+<driver>://" already# has an explicit choice and we leave it alone.- return "postgresql+asyncpg://" + url[len("postgresql://") :]- return url+ url = "postgresql+asyncpg://" + url[len("postgresql://") :]++ # Translate libpq-style query params that asyncpg can't parse.+ parts = urlsplit(url)+ query_pairs = parse_qsl(parts.query, keep_blank_values=True)+ connect_args: dict[str, Any] = {}+ remaining: list[tuple[str, str]] = []+ for key, value in query_pairs:+ if key == "sslmode":+ mode = value.lower().strip()+ if mode in _SSLMODE_PASSTHROUGH:+ # asyncpg understands the libpq mode names via `ssl=`.+ connect_args["ssl"] = mode if mode != "disable" else False+ continue+ if key == "channel_binding":+ # libpq-only; asyncpg negotiates SCRAM channel binding itself.+ continue+ remaining.append((key, value))++ new_url = urlunsplit(+ (parts.scheme, parts.netloc, parts.path, urlencode(remaining), parts.fragment)+ )+ return new_url, connect_args++_normalized_url, _connect_args = _normalize_async_pg_url(str(settings.DATABASE_URL))engine = create_async_engine(- _normalize_async_pg_url(str(settings.DATABASE_URL)),+ _normalized_url,pool_size=settings.DATABASE_POOL_SIZE,max_overflow=settings.DATABASE_MAX_OVERFLOW,echo=settings.DEBUG,future=True,+ connect_args=_connect_args,)AsyncSessionLocal = async_sessionmaker(diff --git a/services/api/tests/test_db_url_normalize.py b/services/api/tests/test_db_url_normalize.pynew file mode 100644index 000000000..eff19fd2f--- /dev/null+++ b/services/api/tests/test_db_url_normalize.py@@ -0,0 +1,56 @@+"""Unit tests for the asyncpg URL normalizer.++The normalizer translates libpq-style ``sslmode=`` query parameters that+asyncpg cannot parse into ``connect_args`` it accepts. Regressing this+silently breaks every database call in production, so we keep the cases+explicit here.+"""++from app.db.database import _normalize_async_pg_url+++def test_postgres_scheme_rewritten_to_asyncpg():+ url, args = _normalize_async_pg_url("postgres://u:p@h:5432/db")+ assert url == "postgresql+asyncpg://u:p@h:5432/db"+ assert args == {}+++def test_postgresql_scheme_rewritten_to_asyncpg():+ url, args = _normalize_async_pg_url("postgresql://u:p@h:5432/db")+ assert url == "postgresql+asyncpg://u:p@h:5432/db"+ assert args == {}+++def test_explicit_driver_left_alone():+ url, args = _normalize_async_pg_url("postgresql+asyncpg://u:p@h/db")+ assert url == "postgresql+asyncpg://u:p@h/db"+ assert args == {}+++def test_sslmode_require_translated_to_ssl_kwarg():+ url, args = _normalize_async_pg_url("postgresql://u:p@h/db?sslmode=require")+ assert url == "postgresql+asyncpg://u:p@h/db"+ assert args == {"ssl": "require"}+++def test_sslmode_disable_translated_to_false():+ url, args = _normalize_async_pg_url("postgres://u:p@h/db?sslmode=disable")+ assert url == "postgresql+asyncpg://u:p@h/db"+ assert args == {"ssl": False}+++def test_other_query_params_preserved():+ url, args = _normalize_async_pg_url(+ "postgresql://u:p@h/db?application_name=aisoc&sslmode=verify-full"+ )+ assert "application_name=aisoc" in url+ assert "sslmode" not in url+ assert args == {"ssl": "verify-full"}+++def test_channel_binding_stripped():+ url, args = _normalize_async_pg_url(+ "postgresql://u:p@h/db?sslmode=require&channel_binding=require"+ )+ assert "channel_binding" not in url+ assert args == {"ssl": "require"}