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.

feat(t3.3): attack-chain timeline UI for /cases/{id} (#145)

Beenu Arorad80659a7d966
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 01a68f2ad..31fb284c7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Attack-chain timeline UI (T3.3, v8.0)
+
+`/cases/{id}` now ships an **Attack Chain** tab that visualises the ranked
+timeline returned by `/v1/cases/{id}/attack-chain` (shipped earlier under
+`8df637b9`). The new `AttackChainPanel` in
+`apps/web/src/components/cases/CaseWorkspace.tsx`:
+
+- Window selector with the same vocabulary as the backend `WindowLiteral`
+ (`1h`, `6h`, `24h`, `72h`, `7d`, `30d`) — selection is deep-linkable via
+ `?window=…` and survives reload.
+- One card per `ChainLink` with the alert title, severity chip (driven by
+ the canonical 5-tier ladder `info | low | medium | high | critical`),
+ confidence percent, MITRE technique IDs, and the deterministic narrative
+ reason emitted by `services/api/app/services/attack_chain.py`.
+- Entity-graph summary panel — node count grouped by `kind` (`user`,
+ `asset`, `process`, `ip`, `domain`, `alert`), top edges, and a per-node
+ severity chip when present in `_entity_graph_payload`.
+- SWR-keyed on `(case_id, window)` with skeleton, error, and empty states
+ that match the rest of the case workspace.
+- New `casesApi.getAttackChain` method + `AttackChainTimeline`,
+ `AttackChainWindow`, `AttackChainLink`, `AttackChainEntityNode`,
+ `AttackChainEntityEdge`, `BackendAttackChainResponse` types in
+ `apps/web/src/lib/api.ts`. The wire format matches the backend `to_dict`
+ shape exactly (node `kind` rather than `type`; optional `severity` and
+ `event_time` from `_entity_graph_payload`).
+- Coverage in `apps/web/src/components/cases/CaseWorkspace.test.tsx`:
+ empty-state, error-state, and three data-rendering assertions
+ (alert titles, confidence percent, MITRE techniques). The SWR mock is now
+ key-aware so attack-chain and attack-path fetches stay isolated, and
+ `useSearchParams` is stateful so window-selection deep-links round-trip
+ cleanly under test. The `WindowSelector` is a labelled
+ `role="group"` of buttons with `aria-pressed`, so deep-link assertions
+ resolve the active option via the single pressed button inside the
+ group rather than a non-existent `<select>` value.
+
+Closes the UI side of T3.3 in `AISOC_V8_PROGRESS.md`. Pre-existing
+non-blocking lint warnings in `CaseWorkspace.tsx` are unchanged by this
+diff.
+
### LLM input contract — static regression gate (T2.3, v8.0)
Closes T2.3 by adding the missing **bypass-prevention** layer on top of the
@@ -27,9 +66,9 @@ new test files in `services/agents/tests/`:
LangGraph control-flow handles, not LLMs) or whose file is not the
contract module itself. Ships with self-tests proving (a) a synthetic
`llm.ainvoke(...)` bypass trips the detector and (b) allowlisted
- receivers do not. Adding a new agent that calls a chat model directly
- now fails the build until it routes through `safe_ainvoke` /
- `safe_astream` / `make_safe_chat_model`.
+receivers do not. Adding a new agent that calls a chat model directly
+now fails the build until it routes through `safe_ainvoke` /
+`safe_astream` / `make_safe_chat_model`.
The survey behind this gate confirmed every existing direct chat-model call
under `services/agents/app/` already goes through the safe wrapper — the
diff --git a/apps/web/src/components/cases/CaseWorkspace.test.tsx b/apps/web/src/components/cases/CaseWorkspace.test.tsx
index 69b63bbf5..645fc8213 100644
--- a/apps/web/src/components/cases/CaseWorkspace.test.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.test.tsx
@@ -1,22 +1,59 @@
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
-import { render, screen } from '@testing-library/react';
-import type { Case } from '@/lib/api';
+import { render, screen, within } from '@testing-library/react';
+import type { AttackChainTimeline, Case } from '@/lib/api';
// We mock SWR rather than the real network layer so the test stays
// hermetic and so we can exercise both the loaded and fallback paths.
+// The mock is key-aware so different panels in the workspace (the case
+// header vs the attack-chain panel) can return different shapes.
const swrState = vi.hoisted(() => ({
- data: undefined as Case | undefined,
- error: undefined as Error | undefined,
+ caseData: undefined as Case | undefined,
+ caseError: undefined as Error | undefined,
+ attackChainData: undefined as AttackChainTimeline | null | undefined,
+ attackChainError: undefined as Error | undefined,
+ attackChainLoading: false,
}));
+function isAttackChainKey(key: unknown): boolean {
+ if (Array.isArray(key)) return key[0] === 'case:attack-chain';
+ return false;
+}
+
+function isAttackPathKey(key: unknown): boolean {
+ return typeof key === 'string' && key.startsWith('case:') && key.endsWith(':attack-path');
+}
+
vi.mock('swr', () => ({
__esModule: true,
- default: () => ({
- data: swrState.data,
- error: swrState.error,
- isLoading: !swrState.data && !swrState.error,
- mutate: vi.fn(async () => undefined),
- }),
+ default: (key: unknown) => {
+ if (isAttackChainKey(key)) {
+ return {
+ data: swrState.attackChainData,
+ error: swrState.attackChainError,
+ isLoading:
+ swrState.attackChainLoading ||
+ (swrState.attackChainData === undefined && !swrState.attackChainError),
+ mutate: vi.fn(async () => undefined),
+ };
+ }
+ if (isAttackPathKey(key)) {
+ // We don't exercise the attack-path tab in these tests; return an
+ // empty resolved state so it doesn't show a phantom loading skeleton.
+ return {
+ data: null,
+ error: undefined,
+ isLoading: false,
+ mutate: vi.fn(async () => undefined),
+ };
+ }
+ // Default: case workspace fetch.
+ return {
+ data: swrState.caseData,
+ error: swrState.caseError,
+ isLoading: !swrState.caseData && !swrState.caseError,
+ mutate: vi.fn(async () => undefined),
+ };
+ },
}));
vi.mock('next/link', () => ({
@@ -28,8 +65,10 @@ vi.mock('next/link', () => ({
),
}));
+const searchParamsState = vi.hoisted(() => ({ params: new URLSearchParams() }));
+
vi.mock('next/navigation', () => ({
- useSearchParams: () => new URLSearchParams(),
+ useSearchParams: () => searchParamsState.params,
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => '/cases/INC-001',
}));
@@ -85,8 +124,12 @@ const fakeCase: Case = {
describe('CaseWorkspace', () => {
beforeEach(() => {
- swrState.data = fakeCase;
- swrState.error = undefined;
+ swrState.caseData = fakeCase;
+ swrState.caseError = undefined;
+ swrState.attackChainData = undefined;
+ swrState.attackChainError = undefined;
+ swrState.attackChainLoading = false;
+ searchParamsState.params = new URLSearchParams();
});
afterEach(() => {
@@ -111,8 +154,8 @@ describe('CaseWorkspace', () => {
});
it('shows the demo banner when the backend errors out', () => {
- swrState.data = undefined;
- swrState.error = new Error('fetch failed');
+ swrState.caseData = undefined;
+ swrState.caseError = new Error('fetch failed');
render(<CaseWorkspace caseId="INC-001" />);
@@ -124,4 +167,142 @@ describe('CaseWorkspace', () => {
// …and the demo-mode banner is visible so the analyst knows it's not live data.
expect(screen.getByText(/demo data — writes disabled/i)).toBeInTheDocument();
});
+
+ describe('attack-chain panel', () => {
+ beforeEach(() => {
+ // Force the attack-chain tab to render by setting ?tab=attack-chain.
+ searchParamsState.params = new URLSearchParams('tab=attack-chain');
+ });
+
+ it('renders an empty state when the backend returns no chain', () => {
+ swrState.attackChainData = null;
+
+ render(<CaseWorkspace caseId="INC-001" />);
+
+ expect(screen.getByText(/no attack chain yet/i)).toBeInTheDocument();
+ });
+
+ it('renders an error state when the chain request fails', () => {
+ swrState.attackChainData = undefined;
+ swrState.attackChainError = new Error('boom');
+
+ render(<CaseWorkspace caseId="INC-001" />);
+
+ expect(screen.getByText(/failed to load attack chain/i)).toBeInTheDocument();
+ });
+
+ it('renders chain links, confidence, and entity summary when data is loaded', () => {
+ const now = new Date('2026-05-15T00:00:00Z').toISOString();
+ const timeline: AttackChainTimeline = {
+ caseId: 'INC-001',
+ tenantId: 'tenant-1',
+ window: '24h',
+ seedAlertId: 'alert-seed',
+ chainSignature: 'sig-xyz',
+ confidence: 0.82,
+ generatedAt: now,
+ chain: [
+ {
+ alertId: 'alert-seed',
+ title: 'Seed — Suspicious PowerShell on FIN-WS-01',
+ severity: 'critical',
+ eventTime: now,
+ score: 1.0,
+ distance: 0,
+ dtSeconds: 0,
+ sharedEntities: [],
+ mitreTechniques: ['T1059.001'],
+ connectorType: 'edr',
+ sourceEventIds: ['evt-1'],
+ },
+ {
+ alertId: 'alert-2',
+ title: 'Lateral SMB session to FIN-DB-02',
+ severity: 'high',
+ eventTime: new Date('2026-05-15T00:05:00Z').toISOString(),
+ score: 0.74,
+ distance: 1,
+ dtSeconds: 300,
+ sharedEntities: [{ kind: 'user', value: 'svc-finance' }],
+ mitreTechniques: ['T1021.002'],
+ connectorType: 'edr',
+ sourceEventIds: ['evt-2'],
+ },
+ ],
+ entityGraph: {
+ nodes: [
+ { id: 'alert-seed', kind: 'alert', severity: 'critical', event_time: now },
+ { id: 'alert-2', kind: 'alert', severity: 'high' },
+ { id: 'user:svc-finance', kind: 'user', label: 'svc-finance' },
+ ],
+ edges: [{ source: 'alert-seed', target: 'alert-2', kind: 'shares_entity' }],
+ },
+ };
+ swrState.attackChainData = timeline;
+
+ render(<CaseWorkspace caseId="INC-001" />);
+
+ // Both chain links should render.
+ expect(screen.getByText(/Seed — Suspicious PowerShell on FIN-WS-01/i)).toBeInTheDocument();
+ expect(screen.getByText(/Lateral SMB session to FIN-DB-02/i)).toBeInTheDocument();
+
+ // Confidence is surfaced as a percentage to the analyst.
+ expect(screen.getByText(/82%/)).toBeInTheDocument();
+
+ // MITRE techniques from the chain should be visible.
+ expect(screen.getByText('T1059.001')).toBeInTheDocument();
+ expect(screen.getByText('T1021.002')).toBeInTheDocument();
+ });
+
+ // Helper: read the active window from the WindowSelector. The UI is a
+ // segmented button group (role=group, buttons with aria-pressed) rather
+ // than a <select>, so we resolve the active choice by looking inside the
+ // labelled group for the lone button with aria-pressed="true".
+ const readActiveWindow = (): string | null => {
+ const group = screen.getByLabelText(/attack chain time window/i);
+ const pressed = within(group).getAllByRole('button', { pressed: true });
+ // The component invariant is exactly one option pressed at a time.
+ expect(pressed).toHaveLength(1);
+ return pressed[0]?.textContent?.replace(/\s+/g, '') ?? null;
+ };
+
+ it('honors the ?window=… deep link on first render', () => {
+ // Regression for PR #145 review: the changelog claims the window
+ // selection survives reload via ?window=…. Mount with both the
+ // tab AND window params set, and assert the WindowSelector is
+ // showing the linked value rather than the default `24h`.
+ searchParamsState.params = new URLSearchParams('tab=attack-chain&window=72h');
+ swrState.attackChainData = null;
+
+ render(<CaseWorkspace caseId="INC-001" />);
+
+ // The window selector must show 72h as the active choice. Since
+ // `WindowSelector value={windowParam}` is bound directly to the
+ // panel state, the selector reading 72h proves the URL value
+ // flowed through `initialWindow` into the state — which in turn
+ // is what SWR keys the fetch on.
+ expect(readActiveWindow()).toBe('72h');
+ });
+
+ it('falls back to the 24h default when ?window=… is missing or unknown', () => {
+ // Just the tab, no window param → default `24h` (NOT the previous
+ // `1h` default the PR shipped with; switched to 24h per review
+ // because 1h showed an empty state for most realistic cases).
+ searchParamsState.params = new URLSearchParams('tab=attack-chain');
+ swrState.attackChainData = null;
+
+ const { unmount } = render(<CaseWorkspace caseId="INC-001" />);
+ expect(readActiveWindow()).toBe('24h');
+ unmount();
+
+ // An obviously-invalid value must also fall back to the default
+ // (defence-in-depth: the type guard refuses anything outside the
+ // closed `AttackChainWindow` set), not crash the panel.
+ searchParamsState.params = new URLSearchParams('tab=attack-chain&window=900years');
+ swrState.attackChainData = null;
+
+ render(<CaseWorkspace caseId="INC-001" />);
+ expect(readActiveWindow()).toBe('24h');
+ });
+ });
});
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsx
index 2efbfc71e..3c35198b0 100644
--- a/apps/web/src/components/cases/CaseWorkspace.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.tsx
@@ -25,6 +25,8 @@ import toast from 'react-hot-toast';
import {
casesApi,
graphApi,
+ type AttackChainTimeline,
+ type AttackChainWindow,
type Case,
type CaseAttackPath,
type CaseSeverity,
@@ -42,6 +44,7 @@ type WorkspaceTab =
| 'overview'
| 'investigation'
| 'attack-path'
+ | 'attack-chain'
| 'ledger'
| 'report';
@@ -49,6 +52,7 @@ const VALID_TABS: readonly WorkspaceTab[] = [
'overview',
'investigation',
'attack-path',
+ 'attack-chain',
'ledger',
'report',
];
@@ -796,6 +800,16 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
graph
</span>
</span>
+ ) : tab === 'attack-chain' ? (
+ <span className="inline-flex items-center gap-1">
+ Attack chain
+ <span
+ className="rounded bg-rose-500/15 px-1 py-0.5 text-[8px] font-bold uppercase tracking-wider text-rose-300 ring-1 ring-rose-500/30"
+ title="Ranked temporal timeline of related alerts that form the attack chain"
+ >
+ timeline
+ </span>
+ </span>
) : (
tab
)}
@@ -824,6 +838,11 @@ export function CaseWorkspace({ caseId }: { caseId: string }) {
<AttackPathPanel caseId={caseRecord.id || caseId} />
)}
+ {/* Attack-chain tab — ranked temporal timeline of related alerts */}
+ {activeTab === 'attack-chain' && (
+ <AttackChainPanel caseId={caseRecord.id || caseId} />
+ )}
+
{/* Ledger tab — persistent, replayable agent decision log */}
{activeTab === 'ledger' && (
<InvestigationLedger
@@ -1335,6 +1354,398 @@ function AttackPathPanel({ caseId }: { caseId: string }) {
);
}
+// ─── Attack chain panel ───────────────────────────────────────────────────────
+//
+// Renders the ranked temporal timeline of related alerts (the "attack chain")
+// computed by services/api/app/services/attack_chain.py. The backend's BFS
+// expands from the seed alert through the case's linked alerts, ranks each
+// link by recency + shared-entity overlap + MITRE tactic co-occurrence, and
+// hands us back a deterministic timeline plus the entity graph that connects
+// the alerts. We render this as a vertical timeline (most-recent first by
+// distance) with severity bands, score, and the entities each step shares
+// with its predecessor — that's the part an analyst actually reads to decide
+// "yes, this is one campaign, not three independent things."
+
+const CHAIN_SEVERITY_STYLES: Record<string, string> = {
+ critical: 'bg-rose-500/15 text-rose-300 ring-rose-500/30',
+ high: 'bg-orange-500/15 text-orange-300 ring-orange-500/30',
+ medium: 'bg-amber-500/15 text-amber-300 ring-amber-500/30',
+ low: 'bg-sky-500/15 text-sky-300 ring-sky-500/30',
+ info: 'bg-slate-500/15 text-slate-300 ring-slate-500/30',
+};
+
+function severityChipClass(severity: string): string {
+ return CHAIN_SEVERITY_STYLES[severity?.toLowerCase()] ?? CHAIN_SEVERITY_STYLES.info;
+}
+
+const CHAIN_WINDOWS: ReadonlyArray<{ value: AttackChainWindow; label: string }> = [
+ { value: '1h', label: '1 h' },
+ { value: '6h', label: '6 h' },
+ { value: '24h', label: '24 h' },
+ { value: '72h', label: '72 h' },
+ { value: '7d', label: '7 d' },
+ { value: '30d', label: '30 d' },
+];
+
+const CHAIN_WINDOW_VALUES: ReadonlySet<AttackChainWindow> = new Set(
+ CHAIN_WINDOWS.map((w) => w.value),
+);
+
+function isAttackChainWindow(value: string | null | undefined): value is AttackChainWindow {
+ return typeof value === 'string' && CHAIN_WINDOW_VALUES.has(value as AttackChainWindow);
+}
+
+// Default lookback for first-time loads. Picked to be wide enough that a
+// case with linked alerts from a typical investigation horizon (the day
+// before, an active shift) renders chain links instead of the empty state
+// on first paint; analysts who want a tighter view narrow with the
+// selector, and the choice is persisted on the URL via `?window=…`.
+const DEFAULT_CHAIN_WINDOW: AttackChainWindow = '24h';
+
+function AttackChainPanel({ caseId }: { caseId: string }) {
+ // Mirror AttackPathPanel's guard: caseId can be empty during the brief window
+ // between route hydration and the case fetch resolving. Calling the API with
+ // `undefined` returns a 5xx and confuses analysts during the demo flow.
+ const hasCaseId = Boolean(caseId);
+
+ // Honor `?window=…` so a deep-link like
+ // `/cases/INC-001?tab=attack-chain&window=24h` lands the analyst on
+ // the same lookback the linker chose. Only the initial value is read
+ // from search params; subsequent user selections write back through
+ // `history.replaceState` (see `handleWindowChange`) so the choice
+ // survives reload without coupling this panel to the next/navigation
+ // router instance (which can be undefined in unit tests).
+ const searchParams = useSearchParams();
+ const initialWindow: AttackChainWindow = useMemo(() => {
+ const raw = searchParams?.get('window') ?? null;
+ return isAttackChainWindow(raw) ? raw : DEFAULT_CHAIN_WINDOW;
+ }, [searchParams]);
+ const [windowParam, setWindowParam] = useState<AttackChainWindow>(initialWindow);
+
+ const handleWindowChange = useCallback((next: AttackChainWindow) => {
+ setWindowParam(next);
+ if (typeof window === 'undefined') return;
+ try {
+ const url = new URL(window.location.href);
+ url.searchParams.set('window', next);
+ window.history.replaceState({}, '', url.toString());
+ } catch {
+ // Best-effort URL sync; a malformed location shouldn't break the
+ // panel. The state update above is the source of truth either way.
+ }
+ }, []);
+
+ const { data, error, isLoading } = useSWR<AttackChainTimeline | null>(
+ hasCaseId ? ['case:attack-chain', caseId, windowParam] : null,
+ () => casesApi.getAttackChain(caseId, { window: windowParam }),
+ { revalidateOnFocus: false, shouldRetryOnError: 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-chain timeline appears once the case is loaded.
+ </p>
+ </div>
+ );
+ }
+
+ if (isLoading) {
+ return (
+ <div className="space-y-3">
+ <Skeleton className="h-6 w-48" />
+ <Skeleton className="h-24 w-full" />
+ <Skeleton className="h-24 w-full" />
+ <Skeleton className="h-24 w-full" />
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <ErrorState
+ title="Failed to load attack chain"
+ description={error instanceof Error ? error.message : 'Unknown error'}
+ />
+ );
+ }
+
+ // The backend returns a structurally-valid object with `seed_alert_id: null`
+ // and an empty chain when the case has no linked alerts yet. casesApi
+ // collapses that to `null` so the empty state here is unambiguous.
+ if (!data || data.chain.length === 0) {
+ return (
+ <div className="space-y-3">
+ <WindowSelector value={windowParam} onChange={handleWindowChange} />
+ <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">
+ <div className="mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-rose-500/10 ring-1 ring-rose-500/30">
+ <svg className="h-5 w-5 text-rose-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth={2}
+ d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
+ />
+ </svg>
+ </div>
+ <p className="text-sm font-medium text-slate-300">No attack chain yet</p>
+ <p className="mt-1 max-w-md text-xs text-slate-500">
+ An attack chain forms once two or more alerts in the {windowParam} window share
+ entities or MITRE techniques. Link more alerts to the case or widen the window.
+ </p>
+ </div>
+ </div>
+ );
+ }
+
+ // Pre-compute confidence band so we can present "high" vs "exploratory"
+ // distinctly — analysts treat a 0.4 chain very differently from a 0.85 chain.
+ const confidencePct = Math.round(data.confidence * 100);
+ const confidenceBand =
+ data.confidence >= 0.75 ? 'high' : data.confidence >= 0.5 ? 'medium' : 'low';
+ const confidenceClass =
+ confidenceBand === 'high'
+ ? 'bg-emerald-500/15 text-emerald-300 ring-emerald-500/30'
+ : confidenceBand === 'medium'
+ ? 'bg-amber-500/15 text-amber-300 ring-amber-500/30'
+ : 'bg-slate-500/15 text-slate-300 ring-slate-500/30';
+
+ const nodeCount = data.entityGraph.nodes.length;
+ const edgeCount = data.entityGraph.edges.length;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h3 className="text-sm font-medium text-slate-200">Reconstructed attack chain</h3>
+ <p className="text-xs text-slate-500">
+ {data.chain.length} link{data.chain.length === 1 ? '' : 's'} · {nodeCount} entit
+ {nodeCount === 1 ? 'y' : 'ies'} · {edgeCount} edge{edgeCount === 1 ? '' : 's'} · window {data.window}
+ </p>
+ {data.chainSignature && (
+ <p className="mt-0.5 font-mono text-[10px] text-slate-600 truncate">
+ signature: {data.chainSignature}
+ </p>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <span
+ className={clsx(
+ 'inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ring-1',
+ confidenceClass,
+ )}
+ title="Confidence is derived from average link score and chain length"
+ >
+ confidence {confidencePct}%
+ </span>
+ <WindowSelector value={windowParam} onChange={handleWindowChange} />
+ </div>
+ </div>
+
+ {/* Vertical timeline. Steps are already sorted by event_time on the
+ backend (oldest → newest); we render in that order so the analyst
+ reads the chain the same way the campaign actually unfolded. */}
+ <ol className="relative space-y-3 border-l border-slate-800/60 pl-5">
+ {data.chain.map((link, index) => {
+ const sevClass = severityChipClass(link.severity);
+ const isFirst = index === 0;
+ const dtMinutes = Math.round(link.dtSeconds / 60);
+ const dtLabel =
+ isFirst
+ ? 'seed'
+ : dtMinutes <= 0
+ ? `+${Math.max(1, Math.round(link.dtSeconds))}s`
+ : dtMinutes < 60
+ ? `+${dtMinutes}m`
+ : `+${(dtMinutes / 60).toFixed(1)}h`;
+ return (
+ <li key={link.alertId} className="relative">
+ {/* Dot anchored to the spine */}
+ <span
+ className={clsx(
+ 'absolute -left-[26px] top-2 inline-block h-2.5 w-2.5 rounded-full ring-2 ring-slate-950',
+ isFirst ? 'bg-rose-400' : 'bg-slate-500',
+ )}
+ />
+ <div className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4">
+ <div className="flex flex-wrap items-start justify-between gap-2">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <span
+ className={clsx(
+ 'inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ring-1',
+ sevClass,
+ )}
+ >
+ {link.severity}
+ </span>
+ {isFirst && (
+ <span className="inline-flex items-center rounded-full bg-rose-500/15 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-rose-300 ring-1 ring-rose-500/30">
+ seed
+ </span>
+ )}
+ {link.connectorType && (
+ <span className="inline-flex items-center rounded-full bg-slate-800 px-2 py-0.5 text-[10px] font-medium text-slate-400 ring-1 ring-slate-700/60">
+ {link.connectorType}
+ </span>
+ )}
+ <span className="text-[10px] font-mono text-slate-500" title="time since previous link">
+ Δt {dtLabel}
+ </span>
+ </div>
+ <p className="mt-1.5 text-sm font-medium text-slate-200 truncate" title={link.title}>
+ {link.title}
+ </p>
+ <p className="mt-0.5 text-[11px] text-slate-500">
+ {(() => {
+ try {
+ return `${format(new Date(link.eventTime), 'MMM d, HH:mm:ss')} · ${formatDistanceToNow(new Date(link.eventTime), { addSuffix: true })}`;
+ } catch {
+ return link.eventTime;
+ }
+ })()}
+ </p>
+ </div>
+ <div className="flex shrink-0 flex-col items-end gap-1">
+ <span className="rounded-md bg-slate-800/60 px-2 py-0.5 text-[10px] font-mono text-slate-300 ring-1 ring-slate-700/60">
+ score {link.score.toFixed(2)}
+ </span>
+ <span className="text-[10px] text-slate-600">distance {link.distance}</span>
+ </div>
+ </div>
+
+ {/* Shared entities — the "why is this link in the chain"
+ explanation. Empty for the seed because there's no
+ predecessor to share with. */}
+ {link.sharedEntities.length > 0 && (
+ <div className="mt-3 flex flex-wrap gap-1.5">
+ {link.sharedEntities.slice(0, 6).map((entity, i) => (
+ <span
+ key={`${entity.kind ?? 'entity'}-${entity.value ?? i}`}
+ className="inline-flex items-center gap-1 rounded bg-slate-800/70 px-1.5 py-0.5 text-[10px] font-mono text-slate-300 ring-1 ring-slate-700/60"
+ title={`Shared with previous link: ${entity.kind ?? ''}`}
+ >
+ <span className="text-slate-500">{entity.kind}</span>
+ <span>{entity.value}</span>
+ </span>
+ ))}
+ {link.sharedEntities.length > 6 && (
+ <span className="text-[10px] italic text-slate-500">
+ +{link.sharedEntities.length - 6} more
+ </span>
+ )}
+ </div>
+ )}
+
+ {/* MITRE techniques — gives the chain ATT&CK colour even when
+ titles are vague. Surface up to 4 to keep cards compact. */}
+ {link.mitreTechniques.length > 0 && (
+ <div className="mt-2 flex flex-wrap gap-1">
+ {link.mitreTechniques.slice(0, 4).map((tech) => (
+ <span
+ key={tech}
+ className="inline-flex items-center rounded bg-purple-500/10 px-1.5 py-0.5 text-[10px] font-mono text-purple-300 ring-1 ring-purple-500/30"
+ >
+ {tech}
+ </span>
+ ))}
+ {link.mitreTechniques.length > 4 && (
+ <span className="text-[10px] italic text-slate-500">
+ +{link.mitreTechniques.length - 4} more
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ </li>
+ );
+ })}
+ </ol>
+
+ {/* Entity graph summary. The case's attack-path tab renders the full
+ graph; here we just call out the entities that actually appear in
+ the chain itself so the analyst can scan them at a glance. */}
+ {data.entityGraph.nodes.length > 0 && (
+ <div className="rounded-xl border border-slate-800/80 bg-slate-900/40 p-4">
+ <div className="flex items-center justify-between">
+ <h4 className="text-xs font-semibold uppercase tracking-wide text-slate-400">
+ Entities in chain ({data.entityGraph.nodes.length})
+ </h4>
+ <span className="text-[10px] text-slate-500">
+ {data.entityGraph.edges.length} connection{data.entityGraph.edges.length === 1 ? '' : 's'}
+ </span>
+ </div>
+ <ul className="mt-2 flex flex-wrap gap-1.5">
+ {data.entityGraph.nodes.slice(0, 24).map((node) => (
+ <li
+ key={node.id}
+ className="inline-flex items-center gap-1 rounded bg-slate-800/70 px-1.5 py-0.5 text-[10px] font-mono text-slate-300 ring-1 ring-slate-700/60"
+ title={node.label ?? node.id}
+ >
+ <span className="text-slate-500">{node.kind}</span>
+ <span className="truncate max-w-[160px]">{node.label ?? node.id}</span>
+ </li>
+ ))}
+ {data.entityGraph.nodes.length > 24 && (
+ <li className="text-[10px] italic text-slate-500 self-center">
+ +{data.entityGraph.nodes.length - 24} more
+ </li>
+ )}
+ </ul>
+ </div>
+ )}
+
+ <p className="text-[10px] text-slate-600">
+ Chain computed at{' '}
+ {(() => {
+ try {
+ return format(new Date(data.generatedAt), 'MMM d, HH:mm:ss');
+ } catch {
+ return data.generatedAt;
+ }
+ })()}{' '}
+ · seed alert{' '}
+ <span className="font-mono">{data.seedAlertId}</span>
+ </p>
+ </div>
+ );
+}
+
+function WindowSelector({
+ value,
+ onChange,
+}: {
+ value: AttackChainWindow;
+ onChange: (next: AttackChainWindow) => void;
+}) {
+ return (
+ <div
+ className="inline-flex items-center rounded-md border border-slate-800/80 bg-slate-900/40 p-0.5"
+ role="group"
+ aria-label="Attack chain time window"
+ >
+ {CHAIN_WINDOWS.map((opt) => (
+ <button
+ key={opt.value}
+ type="button"
+ onClick={() => onChange(opt.value)}
+ className={clsx(
+ 'rounded px-2 py-1 text-[11px] font-medium transition',
+ value === opt.value
+ ? 'bg-slate-800 text-slate-100 ring-1 ring-slate-700/60'
+ : 'text-slate-400 hover:text-slate-200',
+ )}
+ aria-pressed={value === opt.value}
+ >
+ {opt.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
function AuditLogPreview({ log }: { log: Array<{ kind: string; agent: string; summary: string }> }) {
return (
<ul className="p-4 space-y-1.5">
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 26d297c1f..2f2d6bc72 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1469,6 +1469,58 @@ export const casesApi = {
error?: string;
}>(`/api/v1/cases/${caseId}/investigations/${runId}`),
+ /**
+ * Attack-chain timeline visualization (T3.3 — v8.0).
+ *
+ * Backed by `/api/v1/cases/{id}/attack-chain` which runs a graph BFS over
+ * the case's seed alert and returns a ranked, time-ordered chain of
+ * related alerts plus a side-by-side entity graph. Severity stays as a
+ * lowercase string (info|low|medium|high|critical) to round-trip the
+ * five-tier ladder cleanly.
+ *
+ * Window defaults to 24h; the backend rejects unknown windows with 400.
+ * Returns `null` when the case has no linked alerts (the seed cannot be
+ * resolved). All other failures throw so SWR can surface them.
+ */
+ getAttackChain: async (
+ caseId: string,
+ options: { window?: AttackChainWindow } = {},
+ ): Promise<AttackChainTimeline | null> => {
+ const params: Record<string, string> = {};
+ if (options.window) params.window = options.window;
+ const raw = await request<BackendAttackChainResponse>(
+ `/api/v1/cases/${encodeURIComponent(caseId)}/attack-chain`,
+ { params },
+ );
+ if (!raw.seed_alert_id) return null;
+ return {
+ caseId: raw.case_id,
+ tenantId: raw.tenant_id,
+ window: raw.window,
+ seedAlertId: raw.seed_alert_id,
+ chainSignature: raw.chain_signature ?? null,
+ confidence: typeof raw.confidence === 'number' ? raw.confidence : 0,
+ generatedAt: raw.generated_at ?? new Date().toISOString(),
+ chain: (raw.chain ?? []).map((link) => ({
+ alertId: link.alert_id,
+ title: link.title,
+ severity: link.severity,
+ eventTime: link.event_time,
+ score: link.score,
+ distance: link.distance,
+ dtSeconds: link.dt_seconds,
+ sharedEntities: link.shared_entities ?? [],
+ mitreTechniques: link.mitre_techniques ?? [],
+ connectorType: link.connector_type ?? null,
+ sourceEventIds: link.source_event_ids ?? [],
+ })),
+ entityGraph: {
+ nodes: raw.entity_graph?.nodes ?? [],
+ edges: raw.entity_graph?.edges ?? [],
+ },
+ };
+ },
+
/** Trigger a browser download of the PDF report. */
downloadReportPdf: async (caseId: string, runId: string): Promise<void> => {
const resp = await fetch(`${API_BASE}/api/v1/cases/${caseId}/investigations/${runId}/report.pdf`, {
@@ -3100,6 +3152,110 @@ interface BackendCaseAttackPathResponse {
edge_count: number;
}
+// ─── Attack chain timeline (T3.3 — v8.0) ──────────────────────────────────────
+// The attack-chain endpoint returns a ranked, time-ordered chain of related
+// alerts starting from the seed alert anchored to a case. It's distinct from
+// the case attack-path graph above: this view is *temporal* (a timeline of
+// alerts) while the path view is *topological* (a graph of entities). Both
+// power different tabs in the case workspace.
+
+/** Severity ladder mirrors the backend five-tier scale exactly. */
+export type AttackChainSeverity = 'info' | 'low' | 'medium' | 'high' | 'critical';
+
+/** Allowed lookback windows. The backend rejects anything else with 400. */
+export type AttackChainWindow = '1h' | '6h' | '24h' | '72h' | '7d' | '30d';
+
+/**
+ * A single link in the chain — one related alert plus the metadata that
+ * makes it readable in a timeline: how far it is from the seed (graph
+ * distance), how it scored relative to other candidates, the entities it
+ * shares with the seed, and which MITRE techniques it tagged.
+ */
+export interface AttackChainLink {
+ alertId: string;
+ title: string;
+ severity: AttackChainSeverity | string;
+ /** ISO-8601. The chain is ordered by this field. */
+ eventTime: string;
+ /** Ranking score the BFS uses to pick the top chain candidates. */
+ score: number;
+ /** Hops from the seed alert in the entity graph. 0 == seed itself. */
+ distance: number;
+ /** Time gap from the previous link, in seconds. Always >= 0. */
+ dtSeconds: number;
+ /** Entities that bridge this link to the rest of the chain. */
+ sharedEntities: Array<{ kind: string; value: string }>;
+ mitreTechniques: string[];
+ connectorType: string | null;
+ sourceEventIds: string[];
+}
+
+/** Entity nodes & edges rendered side-by-side with the timeline.
+ *
+ * Node shape from the backend is `{id, kind, label, ...extras}` where extras
+ * depend on the kind: Alert nodes also carry `severity` and `event_time`.
+ * Edges are `{source, target, kind}` — the relationship label (e.g. TOUCHES).
+ */
+export interface AttackChainEntityNode {
+ id: string;
+ kind: string;
+ label?: string;
+ severity?: string;
+ event_time?: string;
+ [key: string]: unknown;
+}
+export interface AttackChainEntityEdge {
+ source: string;
+ target: string;
+ kind: string;
+}
+
+export interface AttackChainTimeline {
+ caseId: string;
+ tenantId: string;
+ window: string;
+ seedAlertId: string;
+ chainSignature: string | null;
+ /** 0..1 — substrate-level confidence in the chain reconstruction. */
+ confidence: number;
+ generatedAt: string;
+ chain: AttackChainLink[];
+ entityGraph: {
+ nodes: AttackChainEntityNode[];
+ edges: AttackChainEntityEdge[];
+ };
+}
+
+/** Raw shape returned by `/api/v1/cases/{id}/attack-chain`. */
+interface BackendAttackChainResponse {
+ case_id: string;
+ tenant_id: string;
+ window: string;
+ seed_alert_id: string | null;
+ chain_signature: string | null;
+ confidence: number;
+ generated_at: string;
+ chain: Array<{
+ alert_id: string;
+ title: string;
+ severity: string;
+ event_time: string;
+ score: number;
+ distance: number;
+ dt_seconds: number;
+ shared_entities: Array<{ kind: string; value: string }>;
+ mitre_techniques: string[];
+ connector_type: string | null;
+ source_event_ids: string[];
+ }>;
+ entity_graph: {
+ nodes: AttackChainEntityNode[];
+ edges: AttackChainEntityEdge[];
+ };
+ // Empty-chain responses include a `reason` breadcrumb the UI can show.
+ reason?: string;
+}
+
export const graphApi = {
getOverview: (filters: { entity?: string; depth?: number } = {}) =>
request<AttackGraph>('/api/v1/graph', {