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(api,web): attack-chain 404, reopen endpoint, investigate auto-advances status

Alexandru Mateescu9f3164dcad3e
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsx
index b893b358b..6a80f3115 100644
--- a/apps/web/src/components/cases/CaseWorkspace.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.tsx
@@ -573,8 +573,19 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
setStatusUpdating(true);
void mutate({ ...caseRecord, status }, { revalidate: false });
try {
- await casesApi.update(caseRecord.id, { status });
- toast.success(`Status set to ${STATUS_LABEL[status]}`);
+ // Backwards moves are refused by the forward-only PATCH ladder (422);
+ // route them through the explicit reopen endpoint instead.
+ const LADDER = ['new', 'triaged', 'investigating', 'contained', 'resolved', 'closed'] as const;
+ if (LADDER.indexOf(status as (typeof LADDER)[number]) < LADDER.indexOf(previous as (typeof LADDER)[number])) {
+ await casesApi.reopen(caseRecord.id, {
+ reason: `Reopened to ${STATUS_LABEL[status]} from analyst console`,
+ status: status === 'new' || status === 'triaged' ? status : 'investigating',
+ });
+ toast.success(`Case reopened — ${STATUS_LABEL[status]}`);
+ } else {
+ await casesApi.update(caseRecord.id, { status });
+ toast.success(`Status set to ${STATUS_LABEL[status]}`);
+ }
} catch (e: unknown) {
// The optimistic mutation has to come back off. Leaving it applied
// showed a status the database does not have, on the one screen an
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index f623c0e26..4ce23b1da 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1880,6 +1880,19 @@ export function normalizeCasesResponse(raw: unknown, filters: CaseFilters = {}):
}
export const casesApi = {
+ /** Explicit reopen — the sanctioned backwards status move (PATCH is
+ * forward-only and answers 422 on backwards transitions). */
+ async reopen(
+ caseId: string,
+ opts: { reason: string; status?: 'new' | 'triaged' | 'investigating' },
+ ): Promise<Case> {
+ const raw = await request<unknown>(`/api/v1/cases/${encodeURIComponent(caseId)}/reopen`, {
+ method: 'POST',
+ body: JSON.stringify(opts),
+ });
+ return normalizeCase(raw);
+ },
+
list: async (filters: CaseFilters = {}) => {
// The status filter is passed through unchanged. It used to be rewritten
// through a five-state UI vocabulary, which could not express `contained`
diff --git a/services/api/app/api/v1/endpoints/attack_chain.py b/services/api/app/api/v1/endpoints/attack_chain.py
index 3bb57317c..453a6807f 100644
--- a/services/api/app/api/v1/endpoints/attack_chain.py
+++ b/services/api/app/api/v1/endpoints/attack_chain.py
@@ -26,7 +26,6 @@ from sqlalchemy import select, text
from app.api.v1.deps import AuthUser, DBSession
from app.models.alert import Alert
-from app.models.case import Case
from app.services.attack_chain import (
AttackChain,
PostgresAttackChainLoader,
@@ -68,7 +67,17 @@ async def get_attack_chain(
# but a future schema change could relax that — fail closed.
raise HTTPException(status_code=400, detail=f"unknown window: {window}")
- case_row = (await db.execute(select(Case).where(Case.id == case_id, Case.tenant_id == user.tenant_id))).scalar_one_or_none()
+ # Read the case via raw SQL against ``aisoc_cases``: the live schema
+ # stores cases there, while the ``Case`` ORM still points at the empty
+ # legacy ``cases`` table — ``select(Case)`` 404'd every real case.
+ case_row = (
+ await db.execute(
+ text(
+ "SELECT id, tenant_id, alert_ids FROM aisoc_cases "
+ "WHERE id = :id AND tenant_id = :tenant_id"
+ ).bindparams(id=case_id, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
if case_row is None:
raise HTTPException(status_code=404, detail="case_not_found")
@@ -77,8 +86,9 @@ async def get_attack_chain(
# on ``alerts.case_id`` if that list is empty so a freshly-linked
# case still resolves.
seed_alert_id: uuid.UUID | None = None
- if case_row.alert_ids:
- candidate_ids = [uuid.UUID(str(a)) if not isinstance(a, uuid.UUID) else a for a in case_row.alert_ids]
+ raw_ids = case_row.alert_ids or []
+ if raw_ids:
+ candidate_ids = [uuid.UUID(str(a)) if not isinstance(a, uuid.UUID) else a for a in raw_ids]
seed_row = (
await db.execute(
select(Alert)
diff --git a/services/api/app/api/v1/endpoints/cases.py b/services/api/app/api/v1/endpoints/cases.py
index df84b31ce..dc9def0ff 100644
--- a/services/api/app/api/v1/endpoints/cases.py
+++ b/services/api/app/api/v1/endpoints/cases.py
@@ -141,6 +141,11 @@ def _status_transition_ok(current: str, target: str) -> bool:
return target in _TRANSITIONS.get(current, set())
+class ReopenCaseRequest(BaseModel):
+ reason: str = Field(..., min_length=3, max_length=500)
+ target_status: Literal["new", "triaged", "investigating"] = "investigating"
+
+
class CreateCaseRequest(BaseModel):
title: str = Field(..., min_length=3)
description: str | None = None
@@ -902,6 +907,67 @@ def case_queue_for(case_row: Any, queues: list[Any]) -> Any:
queues,
)
[email protected]("/{case_id}/reopen", response_model=CaseResponse, summary="Reopen a case")
+async def reopen_case(
+ case_id: str,
+ body: ReopenCaseRequest,
+ db: DBSession,
+ user: Annotated[AuthUser, Depends(require_permission("cases:write"))],
+) -> CaseResponse:
+ """Explicit reopen — the sanctioned backwards status move.
+
+ PATCH /cases/{id} is forward-only by design (see _status_transition_ok);
+ this endpoint is the 'reopen action' its 422 refers to. It resets the
+ future-stage timestamps so the reopened case reads cleanly on the board,
+ and records a timeline event.
+ """
+ import json as _json
+
+ cid = await _resolve_case_id(case_id, db, user.tenant_id)
+ existing = (
+ await db.execute(
+ text("SELECT status FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
+ if not existing:
+ raise HTTPException(status_code=404, detail="Case not found.")
+ if _status_transition_ok(existing.status, body.target_status):
+ raise HTTPException(
+ status_code=422,
+ detail=f"{existing.status} → {body.target_status} is a forward transition; use PATCH /cases/{case_id}.",
+ )
+
+ now = datetime.now(UTC)
+ row = (
+ await db.execute(
+ text(
+ "UPDATE aisoc_cases SET status = :status, reopened_at = :now, "
+ "triaged_at = NULL, resolved_at = NULL, closed_at = NULL, updated_at = :now "
+ "WHERE id = :id AND tenant_id = :tenant_id RETURNING *"
+ ).bindparams(id=cid, tenant_id=user.tenant_id, status=body.target_status, now=now)
+ )
+ ).fetchone()
+ if row is None:
+ raise HTTPException(status_code=404, detail="Case not found.")
+ try:
+ await db.execute(
+ text(
+ "INSERT INTO case_timeline_events (case_id, tenant_id, event_type, actor_type, summary, detail) "
+ "VALUES (:case_id, :tenant_id, 'status_change', 'user', :summary, CAST(:detail AS JSONB))"
+ ).bindparams(
+ case_id=cid,
+ tenant_id=user.tenant_id,
+ summary=f"Case reopened: {existing.status} → {body.target_status}",
+ detail=_json.dumps({"reason": body.reason, "from": existing.status, "to": body.target_status}),
+ )
+ )
+ await db.commit()
+ except Exception as exc:
+ await db.rollback()
+ logger.exception("cases.reopen.timeline_event_failed case=%s", cid)
+ raise HTTPException(status_code=503, detail="Database error") from exc
+ return _row_to_case(row)
+
@router.post("/{case_id}/alerts", response_model=CaseResponse, summary="Link alerts to a case")
async def add_alerts(
@@ -1574,6 +1640,28 @@ async def case_investigate(
except Exception: # noqa: BLE001 - never block launch on enrichment
logger.warning("investigate.launch.raw_alert_enrichment_failed", case_id=str(cid), exc_info=True)
+ # Launching an agent investigation IS an analyst action: advance
+ # new/triaged cases to 'investigating' in the same request so the
+ # board reflects reality without a separate PATCH. Forward-only, same
+ # ladder rule — a contained/resolved case is never pulled backwards
+ # by a re-run.
+ try:
+ st_row = (
+ await db.execute(
+ text("SELECT status FROM aisoc_cases WHERE id = :id AND tenant_id = :tenant_id").bindparams(id=cid, tenant_id=user.tenant_id)
+ )
+ ).fetchone()
+ if st_row and st_row.status != "investigating" and _status_transition_ok(st_row.status, "investigating"):
+ await db.execute(
+ text("UPDATE aisoc_cases SET status = 'investigating', updated_at = :now WHERE id = :id AND tenant_id = :tenant_id").bindparams(
+ id=cid, tenant_id=user.tenant_id, now=datetime.now(UTC)
+ )
+ )
+ await db.commit()
+ except Exception: # noqa: BLE001 — never block the launch on the status bump
+ await db.rollback()
+ logger.warning("investigate.launch.status_advance_failed", case_id=str(cid), exc_info=True)
+
resp = await _agents_proxy(
"POST",
f"/api/v1/cases/{cid}/investigate",