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(console): six verified counter/scale defects from #1245, plus a version-lockstep gate (#1285)
Beenu Arora142cd6edff36
diff --git a/.github/workflows/governance.yml b/.github/workflows/governance.ymlindex bfc4c759d..3d599a636 100644--- a/.github/workflows/governance.yml+++ b/.github/workflows/governance.yml@@ -27,6 +27,10 @@ on:- "scripts/check_release_policy.py"- "CHANGELOG.md"- "VERSION"+ # The console footer renders this file's version, and the release gate+ # now holds the two in lockstep. Without it here, bumping only the+ # package would not trigger the gate that exists to catch exactly that.+ - "apps/web/package.json"- "apps/docs/docs/operations/release-policy.md"- ".github/workflows/governance.yml"pull_request:@@ -45,6 +49,10 @@ on:- "scripts/check_release_policy.py"- "CHANGELOG.md"- "VERSION"+ # The console footer renders this file's version, and the release gate+ # now holds the two in lockstep. Without it here, bumping only the+ # package would not trigger the gate that exists to catch exactly that.+ - "apps/web/package.json"- "apps/docs/docs/operations/release-policy.md"- ".github/workflows/governance.yml"workflow_dispatch:diff --git a/apps/web/src/components/alerts/AlertCaseSeverity.test.tsx b/apps/web/src/components/alerts/AlertCaseSeverity.test.tsxnew file mode 100644index 000000000..3faf3b9d3--- /dev/null+++ b/apps/web/src/components/alerts/AlertCaseSeverity.test.tsx@@ -0,0 +1,125 @@+/**+ * A case opened from an alert inherits that alert's severity.+ *+ * The defect: `AlertDetailView`'s "Start AI investigation" promotes the alert+ * to a case and calls `casesApi.create({ title, description, alertIds })` with+ * no `severity`. The client only serialises the key when it is present, so the+ * server default applies — `cases.py` declares `severity: CaseSeverity =+ * "medium"`. A critical alert therefore opened a MEDIUM case, and every+ * downstream surface that sorts, pages or escalates on case severity saw the+ * wrong number.+ *+ * The sibling path does it correctly: `CreateCaseModal` seeds its severity+ * select from `alertSeverityToCaseSeverity(alert.severity)`. Two call sites+ * promoting the same alert disagreed about how urgent the result was.+ *+ * Against the pre-change tree, `inherits the alert's severity` fails with+ * `severity: undefined`.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const push = vi.hoisted(() => vi.fn());++vi.mock('next/navigation', () => ({+ useRouter: () => ({ push, replace: vi.fn(), refresh: vi.fn(), back: vi.fn() }),+ usePathname: () => '/alerts/a1',+ useSearchParams: () => new URLSearchParams(),+}));++const createCase = vi.hoisted(() => vi.fn());+const investigate = vi.hoisted(() => vi.fn());+const getAlert = vi.hoisted(() => vi.fn());++vi.mock('@/lib/api', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/api')>();+ return {+ ...actual,+ alertsApi: { ...actual.alertsApi, get: getAlert },+ casesApi: { ...actual.casesApi, create: createCase, investigate },+ };+});++import type { Alert } from '@/lib/api';+import { AlertDetailView } from './AlertDetailView';+import { alertSeverityToCaseSeverity } from './CreateCaseModal';++function alertWith(id: string, severity: Alert['severity']): Alert {+ return {+ id,+ title: 'Ransomware encryption behaviour',+ description: 'desc',+ severity,+ status: 'new',+ source: 'crowdstrike',+ tenantId: 't1',+ riskScore: 90,+ createdAt: '2026-10-01T00:00:00Z',+ updatedAt: '2026-10-01T00:00:00Z',+ } as Alert;+}++beforeEach(() => {+ push.mockReset();+ createCase.mockReset();+ createCase.mockResolvedValue({ id: 'c1', caseNumber: 'CASE-1' });+ investigate.mockReset();+ investigate.mockResolvedValue({});+ getAlert.mockReset();+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++// SWR keys on `['alert', alertId]` and dedupes repeat reads of the same key+// for 2s, so each case needs its own id or the second render replays the+// first one's payload.+async function launchInvestigation(alertId: string, severity: Alert['severity']) {+ getAlert.mockResolvedValue(alertWith(alertId, severity));+ render(<AlertDetailView alertId={alertId} />);++ const button = await screen.findByRole('button', { name: /start ai investigation/i });+ await userEvent.click(button);++ await waitFor(() => expect(createCase).toHaveBeenCalled());+ return createCase.mock.calls[0][0] as { severity?: string };+}++describe('promoting an alert to a case carries the alert severity', () => {+ it("inherits the alert's severity instead of defaulting to medium", async () => {+ const payload = await launchInvestigation('alert-crit', 'critical');++ expect(payload.severity).toBe('critical');+ });++ it('does not simply hardcode the most urgent value', async () => {+ // The negative control for the assertion above: a fix that always sent+ // 'critical' would pass it, and would be a worse defect than the one+ // being fixed.+ const payload = await launchInvestigation('alert-low', 'low');++ expect(payload.severity).toBe('low');+ });++ it('folds the alert-only `info` tier through the shared mapping', async () => {+ // Cases do not model `info`. Sending it raw would be rejected by the+ // server enum, so the one mapping both call sites use folds it to `low`.+ const payload = await launchInvestigation('alert-info', 'info');++ expect(payload.severity).toBe('low');+ });+});++describe('the mapping has exactly one definition', () => {+ it('is the helper the modal already uses', () => {+ expect(alertSeverityToCaseSeverity('critical')).toBe('critical');+ expect(alertSeverityToCaseSeverity('high')).toBe('high');+ expect(alertSeverityToCaseSeverity('medium')).toBe('medium');+ expect(alertSeverityToCaseSeverity('low')).toBe('low');+ expect(alertSeverityToCaseSeverity('info')).toBe('low');+ });+});diff --git a/apps/web/src/components/alerts/AlertDetailView.tsx b/apps/web/src/components/alerts/AlertDetailView.tsxindex e833b49cb..255329d86 100644--- a/apps/web/src/components/alerts/AlertDetailView.tsx+++ b/apps/web/src/components/alerts/AlertDetailView.tsx@@ -20,7 +20,7 @@ import { format } from 'date-fns';import { clsx } from 'clsx';import { ContextualActions } from '@/components/copilot/ContextualActions';import { ExplainDrawer } from '@/components/alerts/ExplainDrawer';-import { CreateCaseModal } from '@/components/alerts/CreateCaseModal';+import { CreateCaseModal, alertSeverityToCaseSeverity } from '@/components/alerts/CreateCaseModal';import { demoFallback } from '@/lib/demoFallback';// ─── Helpers ──────────────────────────────────────────────────────────────────@@ -363,7 +363,15 @@ function LedgerEvidenceChain({ runId }: { runId: string }) {// ─── AI Investigation Panel ───────────────────────────────────────────────────-function AIInvestigation({ alertId, alertTitle }: { alertId: string; alertTitle?: string }) {+function AIInvestigation({+ alertId,+ alertTitle,+ alertSeverity,+}: {+ alertId: string;+ alertTitle?: string;+ alertSeverity?: Alert['severity'];+}) {const router = useRouter();const [isRunning, setIsRunning] = useState(false);const [error, setError] = useState<string | null>(null);@@ -393,6 +401,10 @@ function AIInvestigation({ alertId, alertTitle }: { alertId: string; alertTitle?title: alertTitle ? `Investigation — ${alertTitle}` : `Investigation — alert ${alertId}`,description: alertTitle ? `Opened from alert: ${alertTitle}` : `Opened from alert ${alertId}`,alertIds: [alertId],+ // Omitting this let the server default to `medium`, so a critical+ // alert opened a medium case. The same mapping the promotion modal+ // uses, because cases have no `info` tier.+ severity: alertSeverity ? alertSeverityToCaseSeverity(alertSeverity) : undefined,});// A note about *why*, not a substitute for the evidence. The API// prepends this to what it assembled rather than using it instead.@@ -847,7 +859,11 @@ export function AlertDetailView({ alertId }: { alertId: string }) {score={alert.confidenceScore}/>)}- <span className="text-xs text-gray-500">Risk Score: <span className="text-white font-bold">{alert.riskScore}</span></span>+ {/* Omitted rather than shown as 0 when nothing scored the alert —+ the same honesty the rail's chip already applied. */}+ {typeof alert.riskScore === 'number' && (+ <span className="text-xs text-gray-500">Risk Score: <span className="text-white font-bold">{alert.riskScore}</span></span>+ )}</div><h1 className="text-lg font-semibold text-gray-100">{alert.title}</h1><p className="text-sm text-gray-500 mt-1" suppressHydrationWarning>{alert.source} · {format(new Date(alert.createdAt), 'MMM d, yyyy HH:mm:ss')}</p>@@ -1015,7 +1031,11 @@ export function AlertDetailView({ alertId }: { alertId: string }) {{/* Right column - 1/3 */}<div className="space-y-4"><Section title="AI Investigation">- <AIInvestigation alertId={alertId} alertTitle={alert?.title} />+ <AIInvestigation+ alertId={alertId}+ alertTitle={alert?.title}+ alertSeverity={alert?.severity}+ /></Section><Section title="Verdict & feedback">diff --git a/apps/web/src/components/alerts/AlertsQueryOrder.test.tsx b/apps/web/src/components/alerts/AlertsQueryOrder.test.tsxnew file mode 100644index 000000000..21545de7e--- /dev/null+++ b/apps/web/src/components/alerts/AlertsQueryOrder.test.tsx@@ -0,0 +1,67 @@+/**+ * The alert grid asks for the prioritising order.+ *+ * `GET /api/v1/alerts` orders by `created_at` descending and keeps that as+ * its default, because it has generated SDK clients built against "page one+ * is the newest rows" and changing the order silently would alter what they+ * read without altering the schema.+ *+ * So the console has to opt in, and this is the only thing that proves it+ * does. Without it, the server-side `sort=priority` is a parameter nothing+ * sends — the "exists but nothing calls it" shape — and an analyst watching+ * a low-severity flood still never sees the critical underneath it.+ *+ * Against the pre-change tree this fails: the console sent no `sort` at all.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const swrKeys = vi.hoisted(() => [] as unknown[]);++vi.mock('swr', () => ({+ __esModule: true,+ default: (key: unknown) => {+ swrKeys.push(key);+ return { data: undefined, error: undefined, isLoading: false, mutate: vi.fn() };+ },+}));++vi.mock('@/components/alerts/EntityRiskQueue', () => ({+ EntityRiskQueue: () => <div data-testid="entity-queue" />,+}));++import { AlertsView } from './AlertsView';++/** The filter object the grid hands to `alertsApi.list`. */+function requestedFilters(): Record<string, unknown> | undefined {+ const key = swrKeys.find((k) => Array.isArray(k) && k[0] === 'alerts') as unknown[] | undefined;+ return key?.[1] as Record<string, unknown> | undefined;+}++beforeEach(() => {+ swrKeys.length = 0;+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('the alert grid does not let a flood bury a critical', () => {+ it('requests severity-first ordering', async () => {+ render(<AlertsView />);+ await userEvent.click(await screen.findByRole('tab', { name: /^alerts$/i }));++ expect(requestedFilters()?.sort).toBe('priority');+ });++ it('sends a value the API accepts', async () => {+ // `list_alerts` answers 400 for anything outside this set, so a typo+ // here would 400 the whole grid rather than degrade its ordering.+ render(<AlertsView />);++ expect(['newest', 'priority']).toContain(requestedFilters()?.sort);+ });+});diff --git a/apps/web/src/components/alerts/AlertsTileCounts.test.tsx b/apps/web/src/components/alerts/AlertsTileCounts.test.tsxnew file mode 100644index 000000000..5803c90a8--- /dev/null+++ b/apps/web/src/components/alerts/AlertsTileCounts.test.tsx@@ -0,0 +1,154 @@+/**+ * The Alerts stat strip describes the result set, not the loaded page.+ *+ * The defect: `AlertsView` computed three of its four tiles in the browser+ * from `data?.alerts`, which is one page of 25, and rendered them beside a+ * **Total** read from the server-side `total`. With 522 alerts in the tenant+ * the tiles were arithmetically capped at 25, and clicking "next page"+ * changed them.+ *+ * `GET /api/v1/alerts` now returns `facets` — severity and status counts over+ * the same `WHERE` clause that produces `total` — so all four numbers on the+ * strip describe one set of rows.+ *+ * The last test is the honesty half. A server that sends no facets has told+ * us nothing about the result set, and falling back to the page-derived count+ * would be the original defect wearing a fallback. The strip says so instead.+ * Note what it does *not* do: a facet map that omits `critical` means zero+ * criticals matched, and that renders as a real `0`.+ *+ * Against the pre-change tree, every test here fails.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen, within } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++// `swr` is mocked rather than the fetcher: its cache is module-scoped and+// every test here renders the same `['alerts', filters]` key, so the second+// render in a file is served from the cache inside the 2s dedupe window and+// never calls the fetcher at all.+const swrState = vi.hoisted(() => ({ data: undefined as unknown }));++vi.mock('swr', () => ({+ __esModule: true,+ // Key-aware: the page also mounts `SavedViewsBar`, which calls `useSWR` on+ // its own key and expects an array. Answering every key with the alert+ // payload crashes it.+ default: (key: unknown) => {+ const isAlertList = Array.isArray(key) && key[0] === 'alerts';+ return {+ data: isAlertList ? swrState.data : undefined,+ error: undefined,+ isLoading: false,+ mutate: vi.fn(),+ };+ },+}));++// The RBA entity queue is the default tab and fetches on its own; stub it so+// this file only exercises the alert grid.+vi.mock('@/components/alerts/EntityRiskQueue', () => ({+ EntityRiskQueue: () => <div data-testid="entity-queue" />,+}));++import { AlertsView } from './AlertsView';++/** 25 rows, 3 of them critical — a page that under-represents the queue. */+const PAGE = Array.from({ length: 25 }, (_, i) => ({+ id: `a${i}`,+ title: `Alert ${i}`,+ description: '',+ severity: i < 3 ? 'critical' : 'low',+ status: i < 2 ? 'new' : 'resolved',+ source: 'crowdstrike',+ tenantId: 't1',+ createdAt: '2026-10-01T00:00:00Z',+ updatedAt: '2026-10-01T00:00:00Z',+}));++async function openTheAlertGrid() {+ render(<AlertsView />);+ await userEvent.click(await screen.findByRole('tab', { name: /^alerts$/i }));+}++/** The strip renders `<p>label</p><p>value</p>` per tile inside one group. */+function tile(label: string) {+ const strip = screen.getByRole('group', { name: /alert counts/i });+ const heading = within(strip).getByText(label);+ return within(heading.parentElement as HTMLElement);+}++beforeEach(() => {+ swrState.data = undefined;+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('the stat strip is not capped by the page size', () => {+ beforeEach(() => {+ swrState.data = {+ alerts: PAGE,+ total: 522,+ page: 1,+ pageSize: 25,+ facets: {+ bySeverity: { critical: 118, high: 64, low: 340 },+ byStatus: { new: 200, triaging: 90, resolved: 232 },+ unresolved: 290,+ },+ };+ });++ it('shows the whole-result-set critical count, not the three on this page', async () => {+ await openTheAlertGrid();++ expect(tile('Critical').getByText('118')).toBeInTheDocument();+ expect(tile('Critical').queryByText('3')).toBeNull();+ });++ it('shows the whole-result-set high count', async () => {+ await openTheAlertGrid();++ // Zero highs are on this page at all, so the page-derived count was 0.+ expect(tile('High').getByText('64')).toBeInTheDocument();+ });++ it('counts every unresolved status, not just `new`', async () => {+ await openTheAlertGrid();++ expect(tile('Unresolved').getByText('290')).toBeInTheDocument();+ });+});++describe('an absent facet is distinguished from a zero one', () => {+ it('renders a real zero when the server says zero', async () => {+ swrState.data = {+ alerts: PAGE,+ total: 522,+ page: 1,+ pageSize: 25,+ // No `critical` key — the server counted and found none.+ facets: { bySeverity: { low: 522 }, byStatus: { resolved: 522 }, unresolved: 0 },+ };++ await openTheAlertGrid();++ expect(tile('Critical').getByText('0')).toBeInTheDocument();+ });++ it('does not fall back to the page-derived count when the server sends none', async () => {+ swrState.data = { alerts: PAGE, total: 522, page: 1, pageSize: 25 };++ await openTheAlertGrid();++ // 3 criticals are visible on the page; publishing that as the tenant's+ // critical count is the defect this file exists to stop.+ expect(tile('Critical').queryByText('3')).toBeNull();+ expect(tile('Critical').queryByText('0')).toBeNull();+ expect(tile('Critical').getByText('—')).toBeInTheDocument();+ });+});diff --git a/apps/web/src/components/alerts/AlertsView.tsx b/apps/web/src/components/alerts/AlertsView.tsxindex 969be0026..c5fbf44d1 100644--- a/apps/web/src/components/alerts/AlertsView.tsx+++ b/apps/web/src/components/alerts/AlertsView.tsx@@ -3,7 +3,7 @@import { useState, useCallback } from 'react';import useSWR from 'swr';import Link from 'next/link';-import { alertsApi, type Alert, type AlertFilters, type ConfidenceLabel } from '@/lib/api';+import { alertsApi, type Alert, type AlertFacets, type AlertFilters, type ConfidenceLabel } from '@/lib/api';import { clsx } from 'clsx';import { formatDistanceToNow } from 'date-fns';import { EntityRiskQueue } from './EntityRiskQueue';@@ -91,6 +91,30 @@ const MOCK_ALERTS: Alert[] = Array.from({ length: 25 }, (_, i): Alert => {};});+/**+ * The aggregate the API would return for a set of alerts.+ *+ * Only reachable through `demoFallback`, where `MOCK_ALERTS` is the entire+ * result set rather than a page of one — so this is the same question the+ * server answers, not the page-derived count the stat strip used to show.+ */+function demoFacets(rows: Alert[]): AlertFacets {+ const bySeverity: Record<string, number> = {};+ const byStatus: Record<string, number> = {};+ for (const row of rows) {+ bySeverity[row.severity] = (bySeverity[row.severity] ?? 0) + 1;+ byStatus[row.status] = (byStatus[row.status] ?? 0) + 1;+ }+ // Mirrors `app/services/alert_status.py`: anything not explicitly finished+ // is still someone's problem.+ const RESOLVED = new Set(['resolved', 'closed']);+ return {+ bySeverity,+ byStatus,+ unresolved: rows.filter((r) => !RESOLVED.has(r.status)).length,+ };+}+// Wave 1 — Detection confidence chip rendered inline in the alert grid so an// analyst can spot low-confidence alerts at a glance without clicking through.// Click-through still goes to AlertDetailView for the full evidence chain.@@ -260,7 +284,15 @@ function AlertRow({// ─── Main View ────────────────────────────────────────────────────────────────export function AlertsView() {- const [filters, setFilters] = useState<AlertFilters>({ page: 1, pageSize: 25 });+ // `sort: 'priority'` because the API defaults to reverse-chronological for+ // its SDK clients, and in a console that is the wrong default: a noisy+ // low-severity source emitting faster than an analyst pages pushes a+ // critical off page one and keeps it there.+ const [filters, setFilters] = useState<AlertFilters>({+ page: 1,+ pageSize: 25,+ sort: 'priority',+ });// Default to the entity-centric queue — that's the whole point of Wave 1's// RBA work. Analysts can flip back to the raw alert grid for legacy// workflows or when triaging a specific alert ID.@@ -275,6 +307,11 @@ export function AlertsView() {total: MOCK_ALERTS.length,page: 1,pageSize: 25,+ // In the hosted demo the mock set *is* the whole result set — there+ // is no server behind it — so counting it here is the same aggregate+ // the API computes, not a page-derived figure. `demoFallback` keeps+ // the whole object out of a real deployment.+ facets: demoFacets(MOCK_ALERTS),}),refreshInterval: 30000,}@@ -287,9 +324,11 @@ export function AlertsView() {const alerts = data?.alerts || [];const total = data?.total || 0;- const critCount = alerts.filter((a) => a.severity === 'critical').length;- const highCount = alerts.filter((a) => a.severity === 'high').length;- const newCount = alerts.filter((a) => a.status === 'new').length;+ // These used to be `alerts.filter(...)` over `data.alerts`, which is one+ // page of `pageSize` rows, rendered beside a server-side `total` in the+ // hundreds — so the tiles were capped at 25 and moved when the analyst+ // paged. `facets` is the same aggregate the server computes for `total`.+ const facets = data?.facets;return (<div className="space-y-4">@@ -359,9 +398,7 @@ export function AlertsView() {<AlertsTablealerts={alerts}total={total}- critCount={critCount}- highCount={highCount}- newCount={newCount}+ facets={facets}filters={filters}isLoading={isLoading}error={error}@@ -377,9 +414,7 @@ export function AlertsView() {function AlertsTable({alerts,total,- critCount,- highCount,- newCount,+ facets,filters,isLoading,error,@@ -387,9 +422,7 @@ function AlertsTable({}: {alerts: Alert[];total: number;- critCount: number;- highCount: number;- newCount: number;+ facets?: AlertFacets;filters: AlertFilters;isLoading: boolean;error: unknown;@@ -404,12 +437,16 @@ function AlertsTable({return (<div className="space-y-4">{/* Stats strip (full width) */}- <div className="grid grid-cols-4 gap-3">+ <div className="grid grid-cols-4 gap-3" role="group" aria-label="Alert counts">{[{ label: 'Total', value: total, color: 'text-gray-200' },- { label: 'Critical', value: critCount, color: 'text-red-400' },- { label: 'High', value: highCount, color: 'text-orange-400' },- { label: 'Unresolved', value: newCount, color: 'text-purple-400' },+ // A key the server omitted from the map means it counted and found+ // none, so `?? 0` is a real zero. No facets at all means nobody+ // counted, and the em-dash says so rather than publishing the+ // page-derived figure that was the original defect.+ { label: 'Critical', value: facets ? (facets.bySeverity.critical ?? 0) : '—', color: 'text-red-400' },+ { label: 'High', value: facets ? (facets.bySeverity.high ?? 0) : '—', color: 'text-orange-400' },+ { label: 'Unresolved', value: facets ? facets.unresolved : '—', color: 'text-purple-400' },].map((stat) => (<div key={stat.label} className="bg-gray-900/60 border border-gray-800/60 rounded-xl px-4 py-3"><p className="text-xs text-gray-500">{stat.label}</p>diff --git a/apps/web/src/components/alerts/CreateCaseModal.tsx b/apps/web/src/components/alerts/CreateCaseModal.tsxindex 89f59f834..ae9255f5b 100644--- a/apps/web/src/components/alerts/CreateCaseModal.tsx+++ b/apps/web/src/components/alerts/CreateCaseModal.tsx@@ -14,7 +14,12 @@ import {// Alerts carry an extra `info` severity that cases don't model; fold it into// the lowest case severity so promotion never sends an invalid value.-function alertSeverityToCaseSeverity(severity: Alert['severity']): CaseSeverity {+//+// Exported because `AlertDetailView` promotes an alert too, down a different+// path. It used to send no severity at all, so the server default applied and+// a critical alert opened a medium case; both call sites now resolve the+// severity here so they cannot drift.+export function alertSeverityToCaseSeverity(severity: Alert['severity']): CaseSeverity {return severity === 'info' ? 'low' : severity;}diff --git a/apps/web/src/components/alerts/CreateCaseModalPromotion.test.tsx b/apps/web/src/components/alerts/CreateCaseModalPromotion.test.tsxnew file mode 100644index 000000000..2e91c27b6--- /dev/null+++ b/apps/web/src/components/alerts/CreateCaseModalPromotion.test.tsx@@ -0,0 +1,164 @@+/**+ * The promotion modal's own submit path.+ *+ * `AlertCaseSeverity.test.tsx` proves the *detail view* now sends the alert's+ * severity when it promotes. It reaches that assertion through+ * `AlertDetailView`, so the modal — the other call site of the mapping this+ * change unified, and the one an analyst actually clicks through — never runs+ * in it. A regression in `handleSubmit` would leave that suite green.+ *+ * So this covers the modal end to end: both tabs, the guard that refuses a+ * stub title, and the severity the seeded select actually submits.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const push = vi.hoisted(() => vi.fn());++vi.mock('next/navigation', () => ({+ useRouter: () => ({ push, replace: vi.fn(), refresh: vi.fn(), back: vi.fn() }),+ usePathname: () => '/alerts/a1',+ useSearchParams: () => new URLSearchParams(),+}));++const createCase = vi.hoisted(() => vi.fn());+const linkAlerts = vi.hoisted(() => vi.fn());+const listCases = vi.hoisted(() => vi.fn());+const toastError = vi.hoisted(() => vi.fn());+const toastSuccess = vi.hoisted(() => vi.fn());++vi.mock('react-hot-toast', () => ({+ default: { success: toastSuccess, error: toastError },+}));++vi.mock('@/lib/api', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/lib/api')>();+ return {+ ...actual,+ casesApi: { ...actual.casesApi, create: createCase, linkAlerts, list: listCases },+ };+});++import type { Alert } from '@/lib/api';+import { CreateCaseModal } from './CreateCaseModal';++function alertWith(severity: Alert['severity']): Alert {+ return {+ id: 'alert-1',+ title: 'Credential dumping via LSASS access',+ description: 'desc',+ severity,+ status: 'new',+ source: 'crowdstrike',+ tenantId: 't1',+ createdAt: '2026-10-01T00:00:00Z',+ updatedAt: '2026-10-01T00:00:00Z',+ } as Alert;+}++beforeEach(() => {+ push.mockReset();+ createCase.mockReset();+ createCase.mockResolvedValue({ id: 'c1', caseNumber: 'CASE-1' });+ linkAlerts.mockReset();+ linkAlerts.mockResolvedValue({ id: 'c9', caseNumber: 'CASE-9' });+ listCases.mockReset();+ listCases.mockResolvedValue({ cases: [{ id: 'c9', caseNumber: 'CASE-9', title: 'Existing intrusion' }] });+ toastError.mockReset();+ toastSuccess.mockReset();+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('creating a new case from the modal', () => {+ it("submits the alert's severity, not the server default", async () => {+ render(<CreateCaseModal open onClose={vi.fn()} alert={alertWith('critical')} />);++ await userEvent.click(screen.getByRole('button', { name: /create case/i }));++ await waitFor(() => expect(createCase).toHaveBeenCalled());+ expect(createCase.mock.calls[0][0]).toMatchObject({ severity: 'critical', alertIds: ['alert-1'] });+ });++ it('folds `info` to the lowest tier a case can hold', async () => {+ // Cases have no `info`. Submitting it raw would be refused by the server+ // enum, which is why both call sites resolve through one mapping.+ render(<CreateCaseModal open onClose={vi.fn()} alert={alertWith('info')} />);++ await userEvent.click(screen.getByRole('button', { name: /create case/i }));++ await waitFor(() => expect(createCase).toHaveBeenCalled());+ expect(createCase.mock.calls[0][0]).toMatchObject({ severity: 'low' });+ });++ it('does not hardcode one tier for every alert', async () => {+ // The negative control: a mapping that always answered `critical` would+ // satisfy the first case and be a worse defect than the one it fixed.+ render(<CreateCaseModal open onClose={vi.fn()} alert={alertWith('low')} />);++ await userEvent.click(screen.getByRole('button', { name: /create case/i }));++ await waitFor(() => expect(createCase).toHaveBeenCalled());+ expect(createCase.mock.calls[0][0]).toMatchObject({ severity: 'low' });+ });++ it('refuses a title too short to identify the case later', async () => {+ render(<CreateCaseModal open onClose={vi.fn()} alert={alertWith('high')} />);++ await userEvent.clear(screen.getByLabelText(/title/i));+ await userEvent.type(screen.getByLabelText(/title/i), 'ab');+ await userEvent.click(screen.getByRole('button', { name: /create case/i }));++ expect(createCase).not.toHaveBeenCalled();+ expect(toastError).toHaveBeenCalled();+ });++ it('reports a failed create instead of navigating to a case that does not exist', async () => {+ createCase.mockRejectedValue(new Error('500'));+ render(<CreateCaseModal open onClose={vi.fn()} alert={alertWith('high')} />);++ await userEvent.click(screen.getByRole('button', { name: /create case/i }));++ await waitFor(() => expect(toastError).toHaveBeenCalled());+ expect(push).not.toHaveBeenCalled();+ });+});++describe('attaching the alert to an existing case', () => {+ it('links rather than creating a second case for the same alert', async () => {+ render(<CreateCaseModal open onClose={vi.fn()} alert={alertWith('high')} />);++ await userEvent.click(screen.getByRole('button', { name: /add to existing case/i }));+ await waitFor(() => expect(listCases).toHaveBeenCalled());+ await screen.findByRole('option', { name: /CASE-9/ });+ await userEvent.selectOptions(screen.getByLabelText(/open case/i), 'c9');+ await userEvent.click(screen.getByRole('button', { name: /add to case/i }));++ await waitFor(() => expect(linkAlerts).toHaveBeenCalledWith('c9', ['alert-1']));+ expect(createCase).not.toHaveBeenCalled();+ });++ it('refuses to submit when no case has been picked', async () => {+ render(<CreateCaseModal open onClose={vi.fn()} alert={alertWith('high')} />);++ await userEvent.click(screen.getByRole('button', { name: /add to existing case/i }));+ await userEvent.click(screen.getByRole('button', { name: /add to case/i }));++ expect(linkAlerts).not.toHaveBeenCalled();+ expect(toastError).toHaveBeenCalled();+ });+});++describe('the modal renders nothing while closed', () => {+ it('mounts no dialog, and asks the API for no cases', () => {+ render(<CreateCaseModal open={false} onClose={vi.fn()} alert={alertWith('high')} />);++ expect(screen.queryByRole('dialog')).toBeNull();+ expect(listCases).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/components/alerts/InvestigationRail.tsx b/apps/web/src/components/alerts/InvestigationRail.tsxindex 302eae646..77cbc5709 100644--- a/apps/web/src/components/alerts/InvestigationRail.tsx+++ b/apps/web/src/components/alerts/InvestigationRail.tsx@@ -312,7 +312,10 @@ function RailHeader({<><span>·</span><span className="font-mono text-gray-400">- risk {Math.round(alert.riskScore)}+ {/* `normalizeAlert` already resolves this to a 0-100 integer.+ The rounding here used to be the only thing standing between+ a raw 0.85 and the page, and it printed "risk 1". */}+ risk {alert.riskScore}</span></>)}diff --git a/apps/web/src/components/alerts/RiskScoreAgreement.test.tsx b/apps/web/src/components/alerts/RiskScoreAgreement.test.tsxnew file mode 100644index 000000000..da5d0a397--- /dev/null+++ b/apps/web/src/components/alerts/RiskScoreAgreement.test.tsx@@ -0,0 +1,112 @@+/**+ * Two surfaces showing the same alert must show the same risk number.+ *+ * Reported as "one alert shows two different risk numbers". Both surfaces+ * read `alert.riskScore`, but the field arrived unnormalised — the live API+ * populates it from `ai_score`, a [0,1] float — and the two rendered it+ * differently: `InvestigationRail` wrapped it in `Math.round`, so 0.85 became+ * **1**, while `AlertDetailView` printed the raw **0.85**.+ *+ * This asserts against *one* API payload driven through the real+ * `normalizeAlert` boundary, because that is where the ambiguity lives.+ * Asserting on each component with its own hand-built `Alert` is what let the+ * contradiction survive: each view's fixture used the scale that view assumed.+ *+ * Against the pre-change tree, both agreement tests fail.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen, within } from '@testing-library/react';++const swrState = vi.hoisted(() => ({ data: undefined as unknown, isLoading: false }));++vi.mock('swr', () => ({+ __esModule: true,+ default: () => ({ data: swrState.data, error: undefined, isLoading: swrState.isLoading, mutate: vi.fn() }),+}));++vi.mock('next/navigation', () => ({+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn(), back: vi.fn() }),+ usePathname: () => '/alerts/a1',+ useSearchParams: () => new URLSearchParams(),+}));++import { alertsApi } from '@/lib/api';+import { AlertDetailView } from './AlertDetailView';+import { InvestigationRail } from './InvestigationRail';++/** Exactly what `AlertResponse` serialises for a model-scored alert. */+const API_PAYLOAD = {+ id: 'a1',+ title: 'Credential dumping on WIN-DC01',+ description: 'LSASS memory access from an unsigned binary.',+ severity: 'critical',+ status: 'new',+ source: 'crowdstrike',+ tenant_id: 't1',+ ai_score: 0.85,+ created_at: '2026-10-01T00:00:00Z',+ updated_at: '2026-10-01T00:00:00Z',+};++/**+ * Run the payload through the real boundary rather than hand-building an+ * `Alert`. `normalizeAlert` is module-private on purpose, so reach it the way+ * the console does — through a stubbed `fetch`.+ */+async function loadAlert(payload: Record<string, unknown>) {+ vi.stubGlobal(+ 'fetch',+ vi.fn(+ async () =>+ new Response(JSON.stringify(payload), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ }),+ ),+ );+ try {+ swrState.data = await alertsApi.get('a1');+ } finally {+ vi.unstubAllGlobals();+ }+}++beforeEach(async () => {+ swrState.isLoading = false;+ await loadAlert(API_PAYLOAD);+});++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('the rail and the detail view agree about one alert', () => {+ it('the rail shows the normalised 0-100 score, not a rounded fraction', () => {+ render(<InvestigationRail alertId="a1" onClose={vi.fn()} />);++ const summary = within(screen.getByRole('region', { name: /alert summary/i }));+ expect(summary.getByText(/^risk 85$/)).toBeInTheDocument();+ // `Math.round(0.85)` — the number the rail used to print.+ expect(summary.queryByText(/^risk 1$/)).toBeNull();+ });++ it('the detail view shows the same number', () => {+ render(<AlertDetailView alertId="a1" />);++ expect(screen.getByText('85')).toBeInTheDocument();+ expect(screen.queryByText('0.85')).toBeNull();+ });+});++describe('an unscored alert is not reported as zero risk', () => {+ it('the detail view omits the figure rather than printing 0', async () => {+ const { ai_score: _dropped, ...unscored } = API_PAYLOAD;+ await loadAlert(unscored);++ render(<AlertDetailView alertId="a1" />);++ expect(screen.queryByText(/risk score/i)).toBeNull();+ });+});diff --git a/apps/web/src/components/dashboard/ConnectedSourceCount.test.tsx b/apps/web/src/components/dashboard/ConnectedSourceCount.test.tsxnew file mode 100644index 000000000..59ada3e18--- /dev/null+++ b/apps/web/src/components/dashboard/ConnectedSourceCount.test.tsx@@ -0,0 +1,145 @@+/**+ * The "Connected Sources" tile counts the sources the panel beneath it lists.+ *+ * Two halves of one defect. Server-side, `metrics.sources` was built only+ * from rows of the `connectors` table, so events arriving through `POST+ * /v1/ingest/batch` or a tenant inbox webhook were invisible — a tenant with+ * 522 alerts from three `connector_type` values read **Connected Sources 0**.+ * Client-side, the tile counted `status === 'active'`, a connector *health*+ * value reported by the poller; nothing polls a webhook, so even once the+ * server listed those sources the tile would still have read 0 directly above+ * a panel showing all three.+ *+ * The render test is the one that matters — it asserts the number a user+ * sees. The unit tests pin the predicate's edges, including the two it must+ * *not* count, so "fix the tile" cannot quietly become "count every row".+ *+ * Against the pre-change tree all of these fail.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cleanup, render, screen, within } from '@testing-library/react';+import { TimeWindowProvider } from '@/components/layout/TimeWindowProvider';+import { __setDemoModeForTests } from '@/lib/demoMode';++const swrData = vi.hoisted(() => new Map<string, unknown>());++vi.mock('swr', () => ({+ __esModule: true,+ default: (key: unknown) => {+ const k = typeof key === 'string' ? key : String((key as unknown[])[0]);+ return { data: swrData.get(k), error: undefined, isLoading: false, mutate: vi.fn() };+ },+}));++vi.mock('@/lib/api', () => ({+ __esModule: true,+ authApi: { currentUser: vi.fn(() => null), updateUserPreferences: vi.fn(() => Promise.resolve()) },+ metricsApi: {+ getDashboard: vi.fn(),+ getSOC: vi.fn(),+ getFunnel: vi.fn(),+ getPipelineHealth: vi.fn(),+ },+ investigationsApi: { getCostAggregate: vi.fn() },+}));++vi.mock('next/link', () => ({+ __esModule: true,+ default: ({ children, href }: { children: React.ReactNode; href: string }) => (+ <a href={href}>{children}</a>+ ),+}));++vi.mock('next/navigation', () => ({+ __esModule: true,+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),+ usePathname: () => '/dashboard',+ useSearchParams: () => new URLSearchParams(),+}));++vi.mock('next/dynamic', () => ({+ __esModule: true,+ default: () => function DynamicStub() {+ return null;+ },+}));++vi.mock('@/lib/realtime', () => ({+ __esModule: true,+ useRealtimeChannel: () => ({ status: 'disconnected', lastEvent: null, events: [] }),+}));++import { DashboardView, countConnectedSources } from './DashboardView';++/** What the API now returns for a tenant ingesting over webhooks only. */+const WEBHOOK_ONLY_METRICS = {+ alerts: { total: 522, critical: 12, high: 40, mttr_hours: 0, mttr_sample_count: 0 },+ cases: { open: 0, inProgress: 0, resolvedThisWeek: 0 },+ sources: [+ { name: 'splunk_notable', count: 340, status: 'ingesting' },+ { name: 'aws_eventbridge', count: 150, status: 'ingesting' },+ { name: 'generic_webhook', count: 32, status: 'ingesting' },+ ],+ topMitre: [],+ alertsTrend: [],+};++beforeEach(() => {+ swrData.clear();+ __setDemoModeForTests(false);+});++afterEach(() => {+ cleanup();+ __setDemoModeForTests(null);+});++describe('the dashboard reports sources that are actually delivering', () => {+ it('shows three, not zero, for a tenant ingesting over webhooks', () => {+ swrData.set('dashboard-metrics', WEBHOOK_ONLY_METRICS);++ render(+ <TimeWindowProvider>+ <DashboardView />+ </TimeWindowProvider>,+ );++ // The tile's label and the panel's heading carry the same words — which+ // is exactly why "0" above a list of three reads as a contradiction. The+ // tile is the `<p>`, the panel heading is an `<h3>`.+ const tile = screen+ .getByText('Connected Sources', { selector: 'p' })+ .closest('div') as HTMLElement;++ expect(within(tile).getByText('3')).toBeInTheDocument();+ expect(within(tile).queryByText('0')).toBeNull();+ });+});++describe('a source is connected when it is healthy or delivering', () => {+ it('counts a webhook source that has no connector row and no health', () => {+ expect(countConnectedSources(WEBHOOK_ONLY_METRICS.sources)).toBe(3);+ });++ it('still counts a healthy connector that has delivered nothing yet', () => {+ // Just configured, first poll pending. It is connected.+ expect(countConnectedSources([{ name: 'Prod Okta', count: 0, status: 'active' }])).toBe(1);+ });++ it('does not count a dead connector delivering nothing', () => {+ // The negative control: counting every row would turn the tile into a+ // count of configured integrations, which is a different question.+ expect(countConnectedSources([{ name: 'Broken Splunk', count: 0, status: 'error' }])).toBe(0);+ });++ it('counts a connector that is unhealthy but still delivering', () => {+ // Health says degraded, the events say otherwise. The tile answers "is+ // anything reaching us", so the events win.+ expect(countConnectedSources([{ name: 'Flaky SIEM', count: 91, status: 'error' }])).toBe(1);+ });++ it('counts nothing for a tenant with nothing', () => {+ expect(countConnectedSources([])).toBe(0);+ });+});diff --git a/apps/web/src/components/dashboard/DashboardHonesty.test.tsx b/apps/web/src/components/dashboard/DashboardHonesty.test.tsxindex 12e9aa63d..c3fa7ddd1 100644--- a/apps/web/src/components/dashboard/DashboardHonesty.test.tsx+++ b/apps/web/src/components/dashboard/DashboardHonesty.test.tsx@@ -189,7 +189,9 @@ describe('DashboardView — no fabricated data outside demo mode', () => {// Fabricated ones do not.expectNoFabrication(FABRICATED_SOURCE_NAMES);expect(screen.getByText(/No sources connected/i)).toBeTruthy();- expect(screen.getByText(/No technique coverage yet/i)).toBeTruthy();+ // The panel ranks tactics. It used to say "technique", borrowing the unit+ // the SOC Performance coverage row measures — see MitrePanelWording.+ expect(screen.getByText(/No tactic coverage yet/i)).toBeTruthy();});it('publishes no trend delta it cannot source from the API', () => {diff --git a/apps/web/src/components/dashboard/DashboardView.tsx b/apps/web/src/components/dashboard/DashboardView.tsxindex baf7415b2..38b3b8a54 100644--- a/apps/web/src/components/dashboard/DashboardView.tsx+++ b/apps/web/src/components/dashboard/DashboardView.tsx@@ -454,6 +454,25 @@ function useDashboardLayout() {return { order, dragState: dragState.current, handleDragStart, handleDragOver, handleDrop };}+/**+ * How many of a tenant's sources are actually connected.+ *+ * This counted `status === 'active'` alone. `active` is a connector *health*+ * value the poller writes, and the two cases it gets wrong both show up as a+ * tile reading 0 above a panel listing real sources: a webhook or batch-ingest+ * source has no poller and so no health, and a connector whose last poll+ * errored can still be receiving events.+ *+ * Delivering counts, healthy counts, and a dead integration that has sent+ * nothing does not — otherwise the tile silently becomes a count of+ * configured integrations, which answers a different question.+ */+export function countConnectedSources(+ sources: DashboardMetrics['sources'],+): number {+ return sources.filter((s) => s.status === 'active' || s.count > 0).length;+}+// ─── Main Dashboard ───────────────────────────────────────────────────────────export function DashboardView() {@@ -533,7 +552,7 @@ export function DashboardView() {const sources = metrics?.sources ?? [];const topMitre = metrics?.topMitre ?? [];- const activeSourceCount = sources.filter((s) => s.status === 'active').length;+ const activeSourceCount = countConnectedSources(sources);const periodLabel = TIME_WINDOW_SHORT_LABEL[timeWindow] ?? '';const trendTimeFmt =@@ -712,8 +731,16 @@ export function DashboardView() {error={metricsError}pending={metricsPending}onRetry={retryMetrics}- emptyTitle="No technique coverage yet"- emptyDescription="Tactics rank by alert count once detections start firing."+ // This panel ranks *tactics*, and said "technique" — the unit+ // the SOC Performance coverage row measures. Two panels using+ // each other's vocabulary is why they read as contradicting.+ //+ // The old description also promised tactics would appear "once+ // detections start firing", which is not true: the detection+ // engine writes `mitre_techniques` and never `mitre_tactics`,+ // so a tenant whose rules fire all day still sees this empty.+ emptyTitle="No tactic coverage yet"+ emptyDescription="Ranks ATT&CK tactics by alert count. Alerts tagged only with technique IDs are counted under MITRE coverage in SOC Performance instead."/>)}</div>diff --git a/apps/web/src/components/dashboard/EfficiencyReport.tsx b/apps/web/src/components/dashboard/EfficiencyReport.tsxindex 45f2f0340..d021e7262 100644--- a/apps/web/src/components/dashboard/EfficiencyReport.tsx+++ b/apps/web/src/components/dashboard/EfficiencyReport.tsx@@ -162,7 +162,12 @@ export function EfficiencyReport({/><BarRowlabel="MITRE coverage"- description="Tactic + technique IDs surfaced by your alerts"+ // `_mitre_covered` counts distinct *techniques*, and unions the+ // tenant's alerts with every enabled detection rule. The old+ // text named tactics as well and credited alerts alone, so this+ // figure looked like it should agree with the tactics panel on+ // the overview — a different unit over a different population.+ description="Distinct technique IDs on your alerts or enabled rules"value={data.mitre_coverage.total > 0? data.mitre_coverage.covered / data.mitre_coverage.totaldiff --git a/apps/web/src/components/dashboard/MitrePanelWording.test.tsx b/apps/web/src/components/dashboard/MitrePanelWording.test.tsxnew file mode 100644index 000000000..ba41b4887--- /dev/null+++ b/apps/web/src/components/dashboard/MitrePanelWording.test.tsx@@ -0,0 +1,74 @@+/**+ * The two MITRE panels say which MITRE thing they measure.+ *+ * Reported as "MITRE panels contradict each other": the dashboard showed+ * **No technique coverage yet** beside an efficiency row reading **MITRE+ * coverage 3/201**. They were never measuring the same thing —+ *+ * * *Top MITRE ATT&CK Tactics* ranks **tactics**, from `Alert.mitre_tactics`+ * (`metrics.py::get_dashboard_metrics`);+ * * *MITRE coverage* counts distinct **techniques**, and unions alerts with+ * every enabled detection rule (`metrics.py::_mitre_covered`).+ *+ * — so two different numbers are legitimate. The copy was not: one panel+ * named the other's unit, and the other claimed its figure came from the+ * tenant's alerts when most of it comes from the rule catalogue. A reader had+ * no way to tell a real disagreement from a wording bug.+ *+ * The empty description was separately false. It promised tactics would rank+ * "once detections start firing", and they will not: the detection engine+ * sets `mitre_techniques` and never `mitre_tactics`+ * (`services/fusion/app/services/detection_engine.py`), so a tenant whose+ * detections fire all day still sees this panel empty.+ *+ * These are wording assertions, which is what the defect is. Populating+ * tactics from techniques is a data change and is deliberately not attempted+ * here — see the pull request.+ */++import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';++const dashboard = readFileSync(+ join(__dirname, 'DashboardView.tsx'),+ 'utf8',+);+const efficiency = readFileSync(join(__dirname, 'EfficiencyReport.tsx'), 'utf8');++/** The empty state of the tactics panel, as written in the source. */+function tacticsPanelEmptyState(): string {+ const anchor = dashboard.indexOf('Top MITRE ATT&CK Tactics');+ expect(anchor, 'the tactics panel has been renamed').toBeGreaterThan(-1);+ // The panel's own JSX block, up to the next sibling panel.+ const end = dashboard.indexOf('Connected Sources', anchor);+ return dashboard.slice(anchor, end > anchor ? end : anchor + 1200);+}++describe('the tactics panel describes tactics', () => {+ it('does not call its own empty state "technique coverage"', () => {+ expect(tacticsPanelEmptyState()).not.toMatch(/technique coverage/i);+ });++ it('names tactics in its empty title', () => {+ expect(tacticsPanelEmptyState()).toMatch(/emptyTitle="[^"]*tactic/i);+ });++ it('does not promise tactics appear once detections fire', () => {+ // They do not: the detection engine populates `mitre_techniques` only.+ expect(tacticsPanelEmptyState()).not.toMatch(/once detections start firing/i);+ });+});++describe('the coverage row describes techniques', () => {+ it('does not claim to count tactics', () => {+ // The `<BarRow>`, not the `<LoadingBar>` placeholder above it — only the+ // former carries a description.+ const start = efficiency.indexOf('label="MITRE coverage"\n');+ expect(start, 'the coverage row has been renamed').toBeGreaterThan(-1);+ const row = efficiency.slice(start, start + 600);++ expect(row).not.toMatch(/Tactic \+ technique/i);+ expect(row).toMatch(/technique/i);+ });+});diff --git a/apps/web/src/lib/api.alerts-list.test.ts b/apps/web/src/lib/api.alerts-list.test.tsindex 10fcecf2b..42d9234eb 100644--- a/apps/web/src/lib/api.alerts-list.test.ts+++ b/apps/web/src/lib/api.alerts-list.test.ts@@ -90,3 +90,75 @@ describe('alertsApi.list envelope', () => {expect(result.total).toBe(0);});});++/**+ * `facets` is the whole-result-set aggregate the stat strip renders. The strip+ * used to derive those numbers from the loaded page, so they were capped at+ * `page_size` and sat beside a `total` in the hundreds.+ */+describe('alertsApi.list facets', () => {+ it('reads the snake_case aggregate the API sends', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ items: [ALERT_ROW],+ total: 522,+ page: 1,+ page_size: 25,+ facets: {+ by_severity: { critical: 118, high: 64 },+ by_status: { new: 200, triaging: 90 },+ unresolved: 290,+ },+ }),+ );++ const result = await alertsApi.list();++ expect(result.facets).toEqual({+ bySeverity: { critical: 118, high: 64 },+ byStatus: { new: 200, triaging: 90 },+ unresolved: 290,+ });+ });++ it('leaves facets absent when the server sends none', async () => {+ // Absent is not empty: an empty-but-present object would let the strip+ // print a confident 0 for a count nobody made.+ fetchMock.mockResolvedValue(jsonResponse({ items: [], total: 0, page: 1, page_size: 25 }));++ expect((await alertsApi.list()).facets).toBeUndefined();+ });++ it('keeps a zero the server did send', async () => {+ fetchMock.mockResolvedValue(+ jsonResponse({+ items: [],+ total: 0,+ page: 1,+ page_size: 25,+ facets: { by_severity: {}, by_status: {}, unresolved: 0 },+ }),+ );++ expect((await alertsApi.list()).facets).toEqual({+ bySeverity: {},+ byStatus: {},+ unresolved: 0,+ });+ });+});++/**+ * `sort` is how the console avoids a flood burying a critical. The API+ * defaults to `newest` for its SDK clients, so the console has to ask.+ */+describe('alertsApi.list ordering', () => {+ it('sends the sort the caller asked for', async () => {+ fetchMock.mockResolvedValue(jsonResponse({ items: [], total: 0, page: 1, page_size: 25 }));++ await alertsApi.list({ page: 1, pageSize: 25, sort: 'priority' });++ const url = String(fetchMock.mock.calls[0][0]);+ expect(url).toContain('sort=priority');+ });+});diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex b64707c2b..ad4517452 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1252,7 +1252,9 @@ export interface Alert {source: string;sourceRef?: string;tenantId: string;- riskScore: number;+ /** Normalised 0-100 integer. Absent when nothing scored the alert — do not+ * render a `0` in its place, that is a measurement nobody made. */+ riskScore?: number;mitreAttack?: MitreAttack[];iocs?: AlertIOC[];rawEvent?: Record<string, unknown>;@@ -1480,14 +1482,33 @@ function normalizeAlert(raw: unknown): Alert {});}- // ``risk_score`` legacy fallback: fusion sometimes only ships- // ``confidence`` (0-100) and not the older ``risk_score``. Prefer- // the explicit field, fall back to confidence as a soft signal.+ // Risk has the same two-scales-one-field problem confidence had above, and+ // it resolved across three keys: `risk_score ?? ai_score ?? confidence ?? 0`.+ // `risk_score` and `ai_score` are [0,1] floats (fusion documents the first+ // as "0-1, vendor-provided"; `metrics.py` buckets the second "across+ // [0, 1]"), while `confidence` is the canonical 0-100 integer. The live+ // path is `ai_score` — the `alerts` table has no `risk_score` column — so a+ // real alert scoring 0.85 reached the console as 0.85, and the two surfaces+ // reading it disagreed: the rail printed `Math.round(0.85)` as "risk 1"+ // while the detail view printed "0.85".+ //+ // Normalised here, once, to the canonical 0-100 integer, with the scale+ // decided by the *key*: a genuine confidence of 1 is indistinguishable from+ // a model score of 1.0 by value alone. The camelCase `riskScore` is this+ // function's own output name, so it is already on the 0-100 scale and is+ // passed through — re-normalising an alert must not multiply it again.+ //+ // The `?? 0` that used to close the chain is gone too: an alert carrying+ // none of these keys is unscored, and "nobody scored this" is not "scored+ // zero risk". The rail already guards on `typeof riskScore === 'number'` to+ // omit the chip, and the default made that guard unreachable.+ const unitScaleRisk =+ pickNum('risk_score', 'risk_score') ?? pickNum('ai_score', 'aiScore');+ const alreadyNormalisedRisk = pickNum('riskScore', 'riskScore');const riskScore =- pickNum('risk_score', 'riskScore') ??- pickNum('ai_score', 'aiScore') ??- pickNum('confidence', 'confidence') ??- 0;+ unitScaleRisk !== undefined+ ? Math.round(unitScaleRisk * 100)+ : (alreadyNormalisedRisk ?? canonicalConfidence);return {id: String(r.id ?? ''),@@ -1551,6 +1572,52 @@ export interface AlertsResponse {total: number;page: number;pageSize: number;+ /** Absent when the server did not send them — see `AlertFacets`. */+ facets?: AlertFacets;+}++/**+ * Counts over the whole filtered result set, from `AlertListResponse.facets`.+ *+ * The stat strip used to derive these in the browser from the loaded page, so+ * they were capped at `pageSize` and sat beside a server-side `total` in the+ * hundreds. The server computes them off the same `WHERE` clause as `total`.+ *+ * A missing key inside `bySeverity` / `byStatus` means the server counted and+ * found none. The whole object being absent means the server told us nothing,+ * which is a different thing and must not render as a zero.+ */+export interface AlertFacets {+ bySeverity: Record<string, number>;+ byStatus: Record<string, number>;+ /** Uses the API's shared unresolved vocabulary (`new | triaging | in_progress`). */+ unresolved: number;+}++function countMap(raw: unknown): Record<string, number> {+ if (!raw || typeof raw !== 'object') return {};+ return Object.fromEntries(+ Object.entries(raw as Record<string, unknown>).filter(+ (entry): entry is [string, number] => typeof entry[1] === 'number',+ ),+ );+}++/**+ * Reads `AlertListResponse.facets`, or returns `undefined` when the server+ * sent none. Returning an empty-but-present object here would be the same+ * mistake as a `?? 0`: the strip could not tell "no criticals" from "nobody+ * counted".+ */+function normalizeAlertFacets(raw: unknown): AlertFacets | undefined {+ if (!raw || typeof raw !== 'object') return undefined;+ const r = raw as Record<string, unknown>;+ const unresolved = r.unresolved;+ return {+ bySeverity: countMap(r.by_severity ?? r.bySeverity),+ byStatus: countMap(r.by_status ?? r.byStatus),+ unresolved: typeof unresolved === 'number' ? unresolved : 0,+ };}export interface AlertFilters {@@ -1564,6 +1631,13 @@ export interface AlertFilters {page?: number;pageSize?: number;tenantId?: string;+ /**+ * `newest` (created_at descending) or `priority` (severity first, then+ * created_at). The API defaults to `newest` to keep its published contract;+ * the console asks for `priority` so a noisy low-severity source cannot+ * push a critical off page one.+ */+ sort?: 'newest' | 'priority';}export const alertsApi = {@@ -1575,6 +1649,7 @@ export const alertsApi = {page?: number;page_size?: number;pageSize?: number;+ facets?: unknown;}>('/api/v1/alerts', {params: filters as Record<string, string>,});@@ -1598,6 +1673,7 @@ export const alertsApi = {: typeof raw.page_size === 'number'? raw.page_size: 50,+ facets: normalizeAlertFacets(raw.facets),} satisfies AlertsResponse;},diff --git a/apps/web/src/lib/riskScale.test.ts b/apps/web/src/lib/riskScale.test.tsnew file mode 100644index 000000000..4d7b26b2a--- /dev/null+++ b/apps/web/src/lib/riskScale.test.ts@@ -0,0 +1,112 @@+/**+ * `Alert.riskScore` has to mean one thing — the sibling of `confidenceScale`.+ *+ * `normalizeAlert` resolved it as `risk_score ?? ai_score ?? confidence ?? 0`+ * across three keys carrying two different scales:+ *+ * `risk_score` fusion's vendor-supplied risk, a [0,1] float+ * (`services/fusion/app/services/confidence.py` documents it+ * as "0-1, vendor-provided")+ * `ai_score` the model's score, a [0,1] float — `metrics.py` buckets it+ * "across [0, 1]", and `seed_demo.py` writes 0.74-0.97+ * `confidence` the API's canonical 0-100 integer+ *+ * The `alerts` table has no `risk_score` column and `AlertResponse` does not+ * emit one, so the live path is `ai_score`: a real alert scoring 0.85 reached+ * the console as `riskScore = 0.85`. `InvestigationRail` rendered+ * `Math.round(0.85)` as **risk 1** while `AlertDetailView` rendered the raw+ * **0.85**, so one alert showed two different numbers on two surfaces.+ *+ * The trailing `?? 0` is the other half. An alert carrying none of the three+ * keys is unscored, and publishing a confident `0` for an unmeasured quantity+ * is the thing this repo's honesty rules exist to stop — the rail already has+ * a guard to omit the chip, which the `?? 0` made unreachable.+ *+ * Against the pre-change tree, every test below except+ * `passes the canonical 0-100 integer through` fails.+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { alertsApi } from '@/lib/api';++function respondWith(alert: Record<string, unknown>) {+ return vi.fn(+ async () =>+ new Response(+ JSON.stringify({ id: 'a1', title: 't', severity: 'medium', status: 'new', ...alert }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ),+ );+}++beforeEach(() => {+ vi.stubGlobal('fetch', respondWith({}));+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('risk normalises to one scale at the API boundary', () => {+ it("normalises the model's raw [0,1] `ai_score` to the 0-100 scale", async () => {+ vi.stubGlobal('fetch', respondWith({ ai_score: 0.85 }));++ expect((await alertsApi.get('a1')).riskScore).toBe(85);+ });++ it("normalises fusion's raw [0,1] `risk_score` to the same scale", async () => {+ vi.stubGlobal('fetch', respondWith({ risk_score: 0.42 }));++ expect((await alertsApi.get('a1')).riskScore).toBe(42);+ });++ it('passes the canonical 0-100 integer through when only `confidence` is present', async () => {+ vi.stubGlobal('fetch', respondWith({ confidence: 85 }));++ expect((await alertsApi.get('a1')).riskScore).toBe(85);+ });++ it('decides the scale from the key, never from the magnitude', async () => {+ // The tempting shortcut is `v <= 1 ? v * 100 : v`. A genuine confidence of+ // 1/100 is then indistinguishable from a model score of 1.0, and the+ // lowest-risk alert in the estate renders as the highest.+ vi.stubGlobal('fetch', respondWith({ ai_score: 1 }));+ expect((await alertsApi.get('a1')).riskScore).toBe(100);++ vi.stubGlobal('fetch', respondWith({ confidence: 1 }));+ expect((await alertsApi.get('a1')).riskScore).toBe(1);+ });++ it('leaves an unscored alert unscored rather than publishing a zero', async () => {+ // `?? 0` turned "nobody scored this" into "scored zero risk". The rail+ // already guards on `typeof riskScore === 'number'` to omit the chip; the+ // default made that guard unreachable.+ vi.stubGlobal('fetch', respondWith({}));++ expect((await alertsApi.get('a1')).riskScore).toBeUndefined();+ });++ it('keeps a genuine zero score distinct from an absent one', async () => {+ // The negative control for the test above: a fix that mapped 0 to+ // undefined would pass it and would lose a real measurement.+ vi.stubGlobal('fetch', respondWith({ ai_score: 0 }));++ expect((await alertsApi.get('a1')).riskScore).toBe(0);+ });++ it('is idempotent on an already-normalised alert', async () => {+ // The console's own camelCase field is the 0-100 output name. Re-reading+ // one must not multiply it by 100 again.+ vi.stubGlobal('fetch', respondWith({ riskScore: 85 }));++ expect((await alertsApi.get('a1')).riskScore).toBe(85);+ });++ it('prefers the dedicated risk keys over confidence', async () => {+ // Confidence answers "how sure are we", risk answers "how bad is it".+ // Confidence is only a fallback when nothing scored the alert's risk.+ vi.stubGlobal('fetch', respondWith({ ai_score: 0.9, confidence: 20 }));++ expect((await alertsApi.get('a1')).riskScore).toBe(90);+ });+});diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex b59ed18b7..16054a826 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -610,6 +610,23 @@ paths:confidence should only see alerts that actually carry the signal.+ `sort` is `newest` (created_at descending) or `priority` (severity++ descending, then created_at descending). It defaults to `newest`: this++ endpoint has generated SDK clients and "page one is the newest rows" is++ part of what they were built against, so changing the order silently++ would alter what every existing caller reads *without* altering the++ schema — which `openapi-breaking.yml` cannot detect. The console asks for++ `priority`, because a noisy low-severity source emitting faster than an++ analyst pages pushes a critical off page one and keeps it there.++`limit` is an accepted spelling of `page_size`. Supplying both withdifferent values is a 400.'@@ -705,6 +722,16 @@ paths:- type: string- type: 'null'title: Confidence Label+ - name: sort+ in: query+ required: false+ schema:+ enum:+ - newest+ - priority+ type: string+ default: newest+ title: Sortresponses:'200':description: Successful Response@@ -20396,6 +20423,39 @@ components:\ from the case timeline and the audit log.\n* ``recommended_actions`` — normalised\\ structured actions from\n the ResponderAgent (or the legacy list-of-strings\\ shape)."+ AlertFacetCounts:+ properties:+ by_severity:+ additionalProperties:+ type: integer+ type: object+ title: By Severity+ by_status:+ additionalProperties:+ type: integer+ type: object+ title: By Status+ unresolved:+ type: integer+ title: Unresolved+ default: 0+ type: object+ title: AlertFacetCounts+ description: 'Counts over the whole filtered result set, not the returned page.+++ The console''s Critical / High / Unresolved tiles used to be++ `alerts.filter(...)` over the 25 rows it had loaded, rendered beside a++ server-side `total` in the hundreds — so the tiles were arithmetically++ capped at the page size and changed when the analyst paged.+++ Computed from the same `WHERE` clause as `total` rather than over the++ whole tenant, so all four numbers on that strip describe one set of rows.'AlertLinkCreate:properties:alert_id:@@ -20475,6 +20535,8 @@ components:pages:type: integertitle: Pages+ facets:+ $ref: '#/components/schemas/AlertFacetCounts'type: objectrequired:- itemsdiff --git a/scripts/check_release_policy.py b/scripts/check_release_policy.pyindex 816230aab..02cc75793 100644--- a/scripts/check_release_policy.py+++ b/scripts/check_release_policy.py@@ -43,6 +43,7 @@ Usage::from __future__ import annotationsimport argparse+import jsonimport reimport sysfrom dataclasses import dataclass@@ -54,6 +55,7 @@ from gate_toolkit import repo_root, self_test_main # noqa: E402CHANGELOG = Path("CHANGELOG.md")VERSION_FILE = Path("VERSION")+WEB_PACKAGE = Path("apps/web/package.json")POLICY = Path("apps/docs/docs/operations/release-policy.md")#: The release from which "a major bump carries a BREAKING section" is@@ -109,6 +111,42 @@ def parse_sections(text: str) -> list[Section]:return sections+def version_surface_findings(version_text: str, package_json_text: str) -> list[str]:+ """``VERSION`` and ``apps/web/package.json`` must agree, always.++ Unlike the CHANGELOG comparison below, this one has no legitimate+ intermediate state. The console footer renders ``packageJson.version``+ while every other published surface derives from ``VERSION``, so the one+ number a signed-in operator can actually see came from a file no gate+ read. A release that bumped one and not the other shipped a console+ reporting the previous version to the people most likely to quote it in+ a bug report.++ Both inputs are strings so the self-test can inject the mismatch rather+ than assert the live tree has never had one.+ """+ declared = version_text.strip()+ if not declared:+ return [f"{VERSION_FILE} is empty, so no surface has a version to agree with"]++ try:+ package = json.loads(package_json_text)+ except json.JSONDecodeError as exc:+ return [f"{WEB_PACKAGE} is not valid JSON ({exc.msg}), so its version cannot be read"]++ web_version = package.get("version")+ if not isinstance(web_version, str) or not web_version:+ return [f"{WEB_PACKAGE} declares no version, so the console footer has nothing to render"]++ if web_version != declared:+ return [+ f"{VERSION_FILE} reads {declared} and {WEB_PACKAGE} reads {web_version}. The console footer "+ "renders the package version, so a signed-in operator would be told the wrong release. "+ "Bump both in the same commit"+ ]+ return []++def unreleased_body(text: str) -> str:match = _UNRELEASED_RE.search(text)if not match:@@ -269,8 +307,15 @@ def main(argv: list[str] | None = None) -> int:# A VERSION that disagrees with the newest section means the tag the# release workflow extracts notes for is not the version the tree claims.version_file = root / VERSION_FILE+ web_package = root / WEB_PACKAGEif version_file.is_file():declared = version_file.read_text(encoding="utf-8").strip()++ # A finding, not a note: these two have no intermediate state the way+ # VERSION and CHANGELOG do.+ if web_package.is_file():+ problems.extend(version_surface_findings(declared, web_package.read_text(encoding="utf-8")))+newest = parse_sections(text)[0].version if released else ""if declared and newest and declared != newest:notes.append(@@ -367,6 +412,37 @@ def _self_test() -> int:for n in findings(clean.replace("## [Unreleased]\n\n### Added", "## [Unreleased]\n\n### BREAKING"), floor=floor)[1]),),+ # ── VERSION ↔ apps/web/package.json ────────────────────────────────+ # Each arm injects the violation rather than asserting the live tree+ # has never had one, same as the two above.+ (+ "VERSION agreeing with the web package version passes",+ not version_surface_findings("18.0.0\n", '{"name": "@aisoc/web", "version": "18.0.0"}'),+ ),+ (+ "ARM THREE: a web package left on the previous version fails",+ any("console footer" in f for f in version_surface_findings("18.0.0\n", '{"version": "17.1.0"}')),+ ),+ (+ "and it fires in the other direction too — the gate is not one-directional",+ bool(version_surface_findings("17.1.0\n", '{"version": "18.0.0"}')),+ ),+ (+ "a web package with no version is refused rather than treated as agreeing",+ bool(version_surface_findings("18.0.0\n", '{"name": "@aisoc/web"}')),+ ),+ (+ "an unparseable web package is refused rather than silently skipped",+ any("not valid JSON" in f for f in version_surface_findings("18.0.0\n", "{oops")),+ ),+ (+ "an empty VERSION is refused rather than matching everything",+ bool(version_surface_findings("\n", '{"version": "18.0.0"}')),+ ),+ (+ "trailing whitespace in VERSION is not a mismatch",+ not version_surface_findings("18.0.0\n\n", '{"version": "18.0.0"}'),+ ),]ok = Truediff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.pyindex 8339c8996..af397ce7f 100644--- a/services/api/app/api/v1/endpoints/alerts.py+++ b/services/api/app/api/v1/endpoints/alerts.py@@ -28,6 +28,7 @@ from app.services.alert_queue import (QueueResponse,build_queue,claim_alert,+ severity_rank_expr,)from app.services.alert_rail import (MiniTimelineEvent,@@ -35,6 +36,7 @@ from app.services.alert_rail import (RelatedEntity,build_rail_envelope,)+from app.services.alert_status import is_unresolvedfrom app.services.audit import emit_auditfrom app.services.event_sanitiser import (SubmitPayloadTooLarge,@@ -202,12 +204,32 @@ class AlertSnoozeRequest(BaseModel):reason: str | None = None+class AlertFacetCounts(BaseModel):+ """Counts over the whole filtered result set, not the returned page.++ The console's Critical / High / Unresolved tiles used to be+ `alerts.filter(...)` over the 25 rows it had loaded, rendered beside a+ server-side `total` in the hundreds — so the tiles were arithmetically+ capped at the page size and changed when the analyst paged.++ Computed from the same `WHERE` clause as `total` rather than over the+ whole tenant, so all four numbers on that strip describe one set of rows.+ """++ by_severity: dict[str, int] = Field(default_factory=dict)+ by_status: dict[str, int] = Field(default_factory=dict)+ #: Resolved through `app.services.alert_status`, not by counting `new` —+ #: `triaging` and `in_progress` are outstanding work too.+ unresolved: int = 0++class AlertListResponse(BaseModel):items: list[AlertResponse]total: intpage: intpage_size: intpages: int+ facets: AlertFacetCounts = Field(default_factory=AlertFacetCounts)class AlertUpdateRequest(BaseModel):@@ -685,6 +707,36 @@ async def submit_alert(return AlertResponse.model_validate(alert)+async def _alert_facets(db: Any, tenant_id: Any, filters: list[Any]) -> AlertFacetCounts:+ """Severity / status breakdown of every row the filters select.++ Two `GROUP BY`s rather than one query per tile: the console renders four+ numbers off this and a per-tile round-trip would make them individually+ stale. `unresolved` is derived from the status breakdown through the+ shared `alert_status` vocabulary so it cannot drift from the four other+ sites that already carry the rule.++ The tenant is a parameter of its own and is applied here rather than+ being left to whatever `filters` happens to contain. The caller does+ pass it, but a predicate reached through a list cannot be seen at the+ statement — not by `check_tenant_query_predicates.py` and not by the+ next reader — and a second caller that forgot it would read every+ tenant's counts while still looking correct.+ """+ scoped = [Alert.tenant_id == tenant_id, *filters]+ sev_rows = (await db.execute(select(Alert.severity, func.count()).where(and_(*scoped)).group_by(Alert.severity))).all()+ status_rows = (await db.execute(select(Alert.status, func.count()).where(and_(*scoped)).group_by(Alert.status))).all()++ by_severity = {row[0]: row[1] for row in sev_rows if row[0]}+ by_status = {row[0]: row[1] for row in status_rows if row[0]}++ return AlertFacetCounts(+ by_severity=by_severity,+ by_status=by_status,+ unresolved=sum(count for state, count in by_status.items() if is_unresolved(state)),+ )++@router.get("", response_model=AlertListResponse)async def list_alerts(current_user: Annotated[AuthUser, Depends(require_permission("alerts:read"))],@@ -705,6 +757,7 @@ async def list_alerts(search: str | None = Query(default=None),min_confidence: int | None = Query(default=None, ge=0, le=100),confidence_label: str | None = Query(default=None),+ sort: Literal["newest", "priority"] = Query(default="newest"),) -> AlertListResponse:"""List alerts for the current tenant with filtering and pagination.@@ -714,6 +767,15 @@ async def list_alerts(match either filter — that's intentional; analysts who care aboutconfidence should only see alerts that actually carry the signal.+ `sort` is `newest` (created_at descending) or `priority` (severity+ descending, then created_at descending). It defaults to `newest`: this+ endpoint has generated SDK clients and "page one is the newest rows" is+ part of what they were built against, so changing the order silently+ would alter what every existing caller reads *without* altering the+ schema — which `openapi-breaking.yml` cannot detect. The console asks for+ `priority`, because a noisy low-severity source emitting faster than an+ analyst pages pushes a critical off page one and keeps it there.+`limit` is an accepted spelling of `page_size`. Supplying both withdifferent values is a 400."""@@ -763,13 +825,35 @@ async def list_alerts()filters.append(Alert.confidence_label == confidence_label)+ if sort not in ("newest", "priority"):+ # `Literal` makes FastAPI answer 422 before the handler runs, and+ # publishes the enum so an SDK generator knows the allowed values.+ # This guard covers the direct-call path, where `Literal` is not+ # enforced: the branch below treats anything that is not "priority"+ # as "newest", and silently serving an order the caller did not ask+ # for is how a typo becomes a buried critical.+ #+ # Literal 400 because the local `status` parameter shadows+ # `fastapi.status`, same as above.+ raise HTTPException(status_code=400, detail="sort must be one of: newest, priority")+# Countcount_result = await db.execute(select(func.count()).select_from(Alert).where(and_(*filters)))total = count_result.scalar_one()- # Fetch+ # Facets over the *same* filters as `total`, so the console's stat strip+ # describes one set of rows. It used to derive those tiles from the loaded+ # page, which capped them at `page_size`.+ facets = await _alert_facets(db, current_user.tenant_id, filters)++ # Fetch. `created_at` is always the final key so the order is total and+ # paging cannot repeat or skip a row.+ order_by = [Alert.created_at.desc()]+ if sort == "priority":+ order_by.insert(0, severity_rank_expr().asc())+offset = (page - 1) * page_size- result = await db.execute(select(Alert).where(and_(*filters)).order_by(Alert.created_at.desc()).offset(offset).limit(page_size))+ result = await db.execute(select(Alert).where(and_(*filters)).order_by(*order_by).offset(offset).limit(page_size))alerts = result.scalars().all()return AlertListResponse(@@ -778,6 +862,7 @@ async def list_alerts(page=page,page_size=page_size,pages=(total + page_size - 1) // page_size,+ facets=facets,)diff --git a/services/api/app/api/v1/endpoints/metrics.py b/services/api/app/api/v1/endpoints/metrics.pyindex b85a80b8d..89de1a1be 100644--- a/services/api/app/api/v1/endpoints/metrics.py+++ b/services/api/app/api/v1/endpoints/metrics.py@@ -444,6 +444,23 @@ async def get_dashboard_metrics())+ # `source_count_map` used to be built and then only ever *looked up*, so a+ # tenant pushing events through `POST /v1/ingest/batch` or an inbox+ # webhook — neither of which creates a connector instance — saw "Connected+ # Sources 0" above an empty panel while hundreds of their alerts sat in+ # the queue.+ #+ # Nothing is invented here: an entry exists only because alerts carrying+ # that `connector_type` landed inside the selected window, which is the+ # same evidence the count itself rests on. The status is `ingesting`+ # rather than `active` because `active` is a health value the poller+ # reports and nothing is polling these.+ for connector_type, count in sorted(source_count_map.items()):+ if connector_type in seen:+ continue+ seen.add(connector_type)+ sources.append(SourceStat(name=connector_type, count=count, status="ingesting"))+# ── Top MITRE tactics ─────────────────────────────────────────────────────# Python-side aggregation: avoids set-returning-function-in-SELECT pitfalls# across Postgres versions and gives identical results for our scalediff --git a/services/api/app/services/alert_queue.py b/services/api/app/services/alert_queue.pyindex 53d598e28..89bee0527 100644--- a/services/api/app/services/alert_queue.py+++ b/services/api/app/services/alert_queue.py@@ -208,6 +208,27 @@ async def load_sla_targets(return result+def severity_rank_expr():+ """SQL expression ordering severity most-urgent-first.++ `alerts.severity` is a string column, so "critical before high" needs a+ `CASE`. One definition because two surfaces now order by it — the+ investigation queue's tiebreaker and `GET /alerts?sort=priority` — and a+ second copy would drift the day a tier is added.++ An unrecognised severity sorts last: it is not evidence of urgency, and+ ranking it above `low` on a guess would put unknown rows in front of a+ real analyst queue.+ """+ return case(+ (Alert.severity == "critical", literal(0)),+ (Alert.severity == "high", literal(1)),+ (Alert.severity == "medium", literal(2)),+ (Alert.severity == "low", literal(3)),+ else_=literal(4),+ )++def sla_due_at_expression(targets: dict[str, int]):"""SQL expression for the virtual ``sla_due_at`` column.@@ -377,14 +398,7 @@ async def build_queue(else_=literal(1),)- # Severity rank for the tiebreaker: critical > high > medium > …- severity_rank = case(- (Alert.severity == "critical", literal(0)),- (Alert.severity == "high", literal(1)),- (Alert.severity == "medium", literal(2)),- (Alert.severity == "low", literal(3)),- else_=literal(4),- )+ severity_rank = severity_rank_expr()if owner == "me":where_clause = mine_filterdiff --git a/services/api/tests/test_alert_list_priority_sort.py b/services/api/tests/test_alert_list_priority_sort.pynew file mode 100644index 000000000..017f3287e--- /dev/null+++ b/services/api/tests/test_alert_list_priority_sort.py@@ -0,0 +1,214 @@+"""An analyst can ask the alert list for the dangerous ones first.++The defect+----------+`GET /api/v1/alerts` ordered by `Alert.created_at.desc()` and nothing else.+A noisy low-severity source emitting faster than the analyst pages pushes a+critical off page one and keeps it off: the only alert that mattered was on+page nine, sorted behind 200 informational ones that arrived after it.++Why a parameter rather than a new default+-----------------------------------------+`GET /api/v1/alerts` is a published endpoint with generated SDK clients, and+"page one is the newest rows" is part of what callers built on. Changing the+ordering silently would alter what every existing integration reads without+altering the schema — so `openapi-breaking.yml` would not catch it, which+makes it a worse change to make quietly, not a safer one.++`sort` therefore defaults to `newest`, preserving the contract exactly, and+the console asks for `priority` because the console is where the defect was+observed. A script paging for export keeps the order it had.++`/alerts/queue` already prioritises, but it is a different response model with+its own owner/period/SLA semantics and it does not accept the severity,+status, category, search or confidence filters the grid relies on, so the+grid cannot simply move to it.++Run against live Postgres: the defect is an `ORDER BY`, and a fake session+that answers any query cannot tell one ordering from another.+"""++from __future__ import annotations++import os+import uuid+from datetime import UTC, datetime, timedelta++import pytest+import pytest_asyncio+from sqlalchemy import text+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++DSN = os.environ.get("DATABASE_URL", "")+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")++TENANT = uuid.UUID("0c100000-0000-0000-0000-00000000503f")+++@pytest_asyncio.fixture+async def db():+ if "postgres" not in DSN and not REQUIRED:+ pytest.skip("needs a live Postgres with the migration chain applied (integration.yml)")+ engine = create_async_engine(DSN)+ try:+ async with engine.connect() as probe:+ await probe.execute(text("SELECT 1"))+ except Exception as exc:+ await engine.dispose()+ if REQUIRED:+ pytest.fail(+ "MSSP_ISOLATION_REQUIRED is set but no database answered at DATABASE_URL — "+ f"the alert-ordering proof did not run: {type(exc).__name__}: {exc}"+ )+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")++ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ await _reset(session)+ try:+ yield session+ finally:+ await _reset(session)+ await engine.dispose()+++async def _reset(session) -> None:+ await session.rollback()+ await session.execute(text("DELETE FROM alerts WHERE tenant_id = CAST(:t AS uuid)"), {"t": str(TENANT)})+ await session.execute(text("DELETE FROM tenants WHERE id = CAST(:t AS uuid)"), {"t": str(TENANT)})+ await session.commit()+++async def _seed_flood(session) -> None:+ """One critical, then a flood of newer low-severity noise on top of it."""+ await session.execute(+ text("INSERT INTO tenants (id, name, slug) VALUES (CAST(:t AS uuid), 'Flood', 'flood-test') ON CONFLICT (id) DO NOTHING"),+ {"t": str(TENANT)},+ )+ base = datetime.now(UTC) - timedelta(hours=6)+ rows = [("critical", "Ransomware encryption behaviour", base)]+ rows += [("low", f"Noise {i}", base + timedelta(minutes=i + 1)) for i in range(40)]+ for severity, title, created in rows:+ await session.execute(+ text(+ """+ INSERT INTO alerts (id, tenant_id, title, severity, status, created_at, updated_at)+ VALUES (CAST(:i AS uuid), CAST(:t AS uuid), :ti, :s, 'new', :c, :c)+ """+ ),+ {"i": str(uuid.uuid4()), "t": str(TENANT), "ti": title, "s": severity, "c": created},+ )+ await session.commit()+++def _principal():+ from app.api.v1.deps import CurrentUser++ return CurrentUser(user_id=uuid.uuid4(), tenant_id=TENANT, role="admin", email="[email protected]")+++async def _list(db, **overrides):+ """Every parameter explicit — a FastAPI handler called as a plain function+ receives the `Query(...)` objects, not the values they declare."""+ from app.api.v1.endpoints.alerts import list_alerts++ kwargs = {+ "page": 1,+ "page_size": 25,+ "severity": None,+ "status": None,+ "category": None,+ "assigned_to_me": False,+ "search": None,+ "min_confidence": None,+ "confidence_label": None,+ "sort": "newest",+ **overrides,+ }+ return await list_alerts(current_user=_principal(), db=db, **kwargs)+++class TestAFloodDoesNotBuryACritical:+ async def test_the_critical_is_first_under_priority_sort(self, db) -> None:+ """The reproduction: 40 newer low alerts on top of one critical."""+ await _seed_flood(db)++ page = await _list(db, sort="priority")++ assert page.items[0].severity == "critical", f"page one opens with a {page.items[0].severity} alert — the critical is buried"++ async def test_the_critical_is_not_on_page_one_by_default(self, db) -> None:+ """What the console used to show, and still shows to any caller that+ does not ask for the other order. Pinning it proves the default is+ genuinely unchanged rather than accidentally fixed."""+ await _seed_flood(db)++ page = await _list(db)++ assert {a.severity for a in page.items} == {"low"}++ async def test_priority_still_breaks_ties_by_recency(self, db) -> None:+ """Within one severity the newest first, so the order is total and+ paging is stable."""+ await _seed_flood(db)++ page = await _list(db, sort="priority")+ lows = [a for a in page.items if a.severity == "low"]++ assert lows == sorted(lows, key=lambda a: a.created_at, reverse=True)++ async def test_priority_changes_the_order_and_not_the_rows(self, db) -> None:+ """The negative control. A sort that also filtered would hide work."""+ await _seed_flood(db)++ newest = await _list(db, page_size=200)+ priority = await _list(db, page_size=200, sort="priority")++ assert {a.id for a in newest.items} == {a.id for a in priority.items}+ assert newest.total == priority.total == 41++ async def test_an_unknown_sort_is_refused(self, db) -> None:+ """Not silently ignored: a caller that misspells the value should be+ told, not served an order it did not ask for."""+ from fastapi import HTTPException++ await _seed_flood(db)++ with pytest.raises(HTTPException) as caught:+ await _list(db, sort="most-critical")++ assert caught.value.status_code == 400+++class TestTheContract:+ def test_sort_is_published_with_newest_as_the_default(self) -> None:+ from app.main import app++ spec = app.openapi()+ params = {p["name"]: p for p in spec["paths"]["/api/v1/alerts"]["get"]["parameters"]}++ assert "sort" in params, "the console cannot request an order the spec does not declare"+ assert params["sort"]["schema"].get("default") == "newest", (+ "changing the default ordering of a published list endpoint is a contract change "+ "the OpenAPI breaking-change detector cannot see"+ )++ def test_the_severity_ladder_has_one_definition(self) -> None:+ """`build_queue` already ranks severity. A second copy in `alerts.py`+ would drift the day a tier is added."""+ from pathlib import Path++ source = (Path(__file__).resolve().parents[1] / "app" / "api" / "v1" / "endpoints" / "alerts.py").read_text(encoding="utf-8")++ assert "severity_rank" in source++ # A single `Alert.severity == "critical"` is a legitimate filter —+ # `get_alert_stats` counts open criticals that way. A *ladder* is the+ # thing to refuse, and its signature is the mid tiers appearing as+ # comparisons, which only a ranking needs.+ ladder_tiers = [t for t in ("high", "medium", "low") if f'Alert.severity == "{t}"' in source]+ assert len(ladder_tiers) < 2, (+ f"alerts.py ranks severity itself (tiers {ladder_tiers}) instead of importing "+ "severity_rank_expr — two ladders drift the day a tier is added"+ )diff --git a/services/api/tests/test_alert_tiles_cover_the_whole_result_set.py b/services/api/tests/test_alert_tiles_cover_the_whole_result_set.pynew file mode 100644index 000000000..991a2fe97--- /dev/null+++ b/services/api/tests/test_alert_tiles_cover_the_whole_result_set.py@@ -0,0 +1,253 @@+"""The Alerts page tiles describe the whole result set, not the loaded page.++The defect+----------+`AlertsView` computed its Critical / High / Unresolved tiles in the browser::++ const alerts = data?.alerts || []; // one page+ const critCount = alerts.filter(a => a.severity === 'critical').length;++`pageSize` is 25, so the three tiles were arithmetically capped at 25 and sat+beside a **Total** read straight from the server-side `total`. A tenant with+522 alerts saw "Total 522 / Critical 7" where 7 was however many criticals+happened to land on page one -- and paging changed the tiles.++The fix is a server-side aggregate over the *same* `WHERE` clause that+produces `total`, returned on the list response so the four tiles describe one+set. Computing it over the whole tenant instead would have traded one+inconsistency for another: filter to `severity=high` and a whole-tenant+critical count would contradict a filtered total sitting next to it.++`unresolved` is resolved through `app.services.alert_status` rather than+counting `status == 'new'`, which is what the tile labelled *Unresolved* was+actually doing -- `triaging` and `in_progress` are outstanding work too.++Run against live Postgres: the defect is about which rows an aggregate covers,+and a fake session that answers any query cannot tell a page from a result+set. Skips when no database answers so a local run stays green, but **cannot**+skip where it is meant to run -- `integration.yml` sets+`MSSP_ISOLATION_REQUIRED=1` and an unreachable database is then a failure.+"""++from __future__ import annotations++import os+import uuid++import pytest+import pytest_asyncio+from sqlalchemy import text+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++DSN = os.environ.get("DATABASE_URL", "")+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")++# Fixed so a failure names something greppable.+TENANT = uuid.UUID("0c100000-0000-0000-0000-00000000f1ce")+OTHER_TENANT = uuid.UUID("0c100000-0000-0000-0000-00000000f1cf")+++@pytest_asyncio.fixture+async def db():+ if "postgres" not in DSN and not REQUIRED:+ pytest.skip("needs a live Postgres with the migration chain applied (integration.yml)")+ engine = create_async_engine(DSN)+ try:+ async with engine.connect() as probe:+ await probe.execute(text("SELECT 1"))+ except Exception as exc:+ await engine.dispose()+ if REQUIRED:+ pytest.fail(+ "MSSP_ISOLATION_REQUIRED is set but no database answered at DATABASE_URL — "+ f"the alert-facet proof did not run: {type(exc).__name__}: {exc}"+ )+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")++ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ await _reset(session)+ try:+ yield session+ finally:+ await _reset(session)+ await engine.dispose()+++async def _reset(session) -> None:+ await session.rollback()+ for tenant in (TENANT, OTHER_TENANT):+ await session.execute(text("DELETE FROM alerts WHERE tenant_id = CAST(:t AS uuid)"), {"t": str(tenant)})+ await session.execute(text("DELETE FROM tenants WHERE id = CAST(:t AS uuid)"), {"t": str(tenant)})+ await session.commit()+++async def _seed(session, tenant: uuid.UUID, slug: str, pairs: list[tuple[str, str]]) -> None:+ await session.execute(+ text("INSERT INTO tenants (id, name, slug) VALUES (CAST(:t AS uuid), :n, :s) ON CONFLICT (id) DO NOTHING"),+ {"t": str(tenant), "n": f"Facet {slug}", "s": slug},+ )+ for severity, status in pairs:+ await session.execute(+ text(+ """+ INSERT INTO alerts (id, tenant_id, title, severity, status, created_at, updated_at)+ VALUES (CAST(:i AS uuid), CAST(:t AS uuid), :ti, :s, :st, NOW(), NOW())+ """+ ),+ {+ "i": str(uuid.uuid4()),+ "t": str(tenant),+ "ti": f"{severity} alert in {status}",+ "s": severity,+ "st": status,+ },+ )+ await session.commit()+++def _principal(tenant: uuid.UUID):+ from app.api.v1.deps import CurrentUser++ return CurrentUser(+ user_id=uuid.uuid4(),+ tenant_id=tenant,+ role="admin",+ email="[email protected]",+ )+++async def _list(db, tenant: uuid.UUID, **overrides):+ """Call the real handler.++ Every parameter is passed explicitly: calling a FastAPI handler as a plain+ function hands it the `Query(...)` *objects* as defaults rather than the+ values they declare, and `confidence_label` then fails its own validation.+ """+ from app.api.v1.endpoints.alerts import list_alerts++ kwargs = {+ "page": 1,+ "page_size": 25,+ "severity": None,+ "status": None,+ "category": None,+ "assigned_to_me": False,+ "search": None,+ "min_confidence": None,+ "confidence_label": None,+ "sort": "newest",+ **overrides,+ }+ return await list_alerts(current_user=_principal(tenant), db=db, **kwargs)+++# A queue far larger than one page, so a page-local count cannot accidentally+# equal the real one: 30 criticals against a `page_size` of 25.+BIG_QUEUE: list[tuple[str, str]] = [("critical", "new")] * 30 + [("high", "triaging")] * 8 + [("low", "resolved")] * 4+++class TestTheTilesAreNotCappedByThePage:+ async def test_the_critical_facet_counts_past_the_end_of_the_page(self, db) -> None:+ """The reproduction. 30 criticals, 25 to a page: the tile must read 30."""+ await _seed(db, TENANT, "facet-big", BIG_QUEUE)++ page = await _list(db, TENANT)++ assert len(page.items) == 25, "fixture no longer exceeds one page"+ assert page.facets.by_severity.get("critical") == 30, (+ f"the critical tile reads {page.facets.by_severity.get('critical')} — it is counting the loaded page, not the result set"+ )++ async def test_the_facets_do_not_move_when_the_analyst_pages(self, db) -> None:+ """A count that changes because you clicked 'next' is not a count."""+ await _seed(db, TENANT, "facet-big", BIG_QUEUE)++ first = await _list(db, TENANT, page=1)+ second = await _list(db, TENANT, page=2)++ assert first.facets == second.facets++ async def test_the_facets_describe_the_same_rows_as_total(self, db) -> None:+ """The tiles sit beside `total`. Filtering must move both together, or+ the page shows a critical count larger than the total above it."""+ await _seed(db, TENANT, "facet-big", BIG_QUEUE)++ page = await _list(db, TENANT, severity="high")++ assert page.total == 8+ assert page.facets.by_severity == {"high": 8}+ assert sum(page.facets.by_severity.values()) == page.total++ async def test_unresolved_means_unresolved_and_not_merely_new(self, db) -> None:+ """The tile is labelled *Unresolved* and counted `status == 'new'`.+ `triaging` and `in_progress` are outstanding work too."""+ await _seed(+ db,+ TENANT,+ "facet-status",+ [+ ("critical", "new"),+ ("high", "triaging"),+ ("medium", "in_progress"),+ ("low", "resolved"),+ ("low", "closed"),+ ],+ )++ page = await _list(db, TENANT)++ assert page.facets.unresolved == 3+ assert page.total == 5++ async def test_a_worked_queue_reports_zero_unresolved(self, db) -> None:+ """The negative control for the test above: a count that always+ returned the total would pass it."""+ await _seed(db, TENANT, "facet-done", [("critical", "resolved"), ("high", "closed")])++ page = await _list(db, TENANT)++ assert page.facets.unresolved == 0+ assert page.total == 2++ async def test_another_tenants_alerts_are_not_counted(self, db) -> None:+ """A whole-result-set aggregate is exactly the shape that leaks across+ tenants if the predicate is dropped."""+ await _seed(db, TENANT, "facet-mine", [("critical", "new")])+ await _seed(db, OTHER_TENANT, "facet-theirs", [("critical", "new")] * 9)++ page = await _list(db, TENANT)++ assert page.facets.by_severity == {"critical": 1}+ assert page.total == 1+++class TestTheContractCarriesTheFacets:+ """No database needed, so these hold wherever the suite runs."""++ def test_the_list_response_declares_facets(self) -> None:+ from app.api.v1.endpoints.alerts import AlertListResponse++ assert "facets" in AlertListResponse.model_fields++ def test_the_published_spec_exposes_them(self) -> None:+ """Read off `app.openapi()`, not `app.routes`: on FastAPI 0.141.x+ `include_router` leaves an opaque object there and an enumeration+ silently compares nothing."""+ from app.main import app++ spec = app.openapi()+ schema = spec["paths"]["/api/v1/alerts"]["get"]["responses"]["200"]+ assert "AlertListResponse" in str(schema["content"]["application/json"]["schema"])++ properties = spec["components"]["schemas"]["AlertListResponse"]["properties"]+ assert "facets" in properties, "the console cannot read a facet the spec does not publish"++ def test_unresolved_uses_the_shared_definition(self) -> None:+ """Five hand-written copies of one rule drift one at a time."""+ from pathlib import Path++ source = (Path(__file__).resolve().parents[1] / "app" / "api" / "v1" / "endpoints" / "alerts.py").read_text(encoding="utf-8")++ assert "alert_status" in source, "alerts.py does not import the shared status definition"diff --git a/services/api/tests/test_alerts_tenant_isolation.py b/services/api/tests/test_alerts_tenant_isolation.pyindex de4c2db19..0e2d38a72 100644--- a/services/api/tests/test_alerts_tenant_isolation.py+++ b/services/api/tests/test_alerts_tenant_isolation.py@@ -295,6 +295,9 @@ _LIST_ALERTS_DEFAULTS: dict[str, Any] = {"search": None,"min_confidence": None,"confidence_label": None,+ # `list_alerts` is called here as a plain function, so FastAPI's+ # `Query(...)` defaults never apply and every parameter must be named.+ "sort": "newest",}@@ -302,11 +305,23 @@ _LIST_ALERTS_DEFAULTS: dict[str, Any] = {async def test_list_alerts_scopes_by_tenant() -> None:"""Both the count and the SELECT for /alerts must filter on tenant_id."""user = _user()- # ``list_alerts`` runs two queries: count (scalar_one int) + select.- db = _mk_db([3, [_alert(user.tenant_id), _alert(user.tenant_id), _alert(user.tenant_id)]])+ # ``list_alerts`` runs four queries: count (scalar_one int), the two+ # facet GROUP BYs behind the console's stat strip (tuple lists), then the+ # page itself. The facet queries matter here as much as the others —+ # they are whole-result-set aggregates, which is exactly the shape that+ # leaks across tenants if the predicate is dropped.+ db = _mk_db(+ [+ 3,+ [("critical", 2), ("high", 1)],+ [("new", 3)],+ [_alert(user.tenant_id), _alert(user.tenant_id), _alert(user.tenant_id)],+ ]+ )response = await list_alerts(current_user=user, db=db, http_request=_http_request(), **_LIST_ALERTS_DEFAULTS)assert response.total == 3assert len(response.items) == 3+ assert response.facets.by_severity == {"critical": 2, "high": 1}_assert_tenant_scoped(db.executed, user.tenant_id)@@ -314,7 +329,7 @@ async def test_list_alerts_scopes_by_tenant() -> None:async def test_list_alerts_with_filters_keeps_tenant_scope() -> None:"""Severity/status/category/min_confidence filters must not relax tenant scope."""user = _user()- db = _mk_db([0, []])+ db = _mk_db([0, [], [], []])kwargs = {**_LIST_ALERTS_DEFAULTS,"severity": "critical",@@ -328,7 +343,7 @@ async def test_list_alerts_with_filters_keeps_tenant_scope() -> None:_assert_tenant_scoped(db.executed, user.tenant_id)# Every alerts statement should mention tenant_id (count + select).alerts_stmts = [(sql, params) for sql, params in db.executed if "alerts" in re.sub(r"\s+", " ", sql).lower()]- assert len(alerts_stmts) >= 2, "expected count + select to both hit alerts"+ assert len(alerts_stmts) >= 4, "expected count + two facet GROUP BYs + select to all hit alerts"for sql, _params in alerts_stmts:normalized = re.sub(r"\s+", " ", sql).lower()assert "tenant_id" in normalized, f"alerts statement missing tenant_id: {sql}"diff --git a/services/api/tests/test_dashboard_sources_include_direct_ingest.py b/services/api/tests/test_dashboard_sources_include_direct_ingest.pynew file mode 100644index 000000000..ae90a8317--- /dev/null+++ b/services/api/tests/test_dashboard_sources_include_direct_ingest.py@@ -0,0 +1,184 @@+"""A source that is demonstrably delivering events is a connected source.++The defect+----------+`GET /api/v1/metrics/dashboard` built its `sources` list by iterating rows of+the `connectors` table and looking each one up in a `GROUP BY+Alert.connector_type` map::++ for row in connectors_rows:+ sources.append(SourceStat(name=row.name, count=source_count_map.get(...)))++The map was never iterated. Events pushed through `POST /v1/ingest/batch` or a+tenant inbox webhook create no connector instance, so a tenant with 522 alerts+arriving from three distinct `connector_type` values saw **Connected Sources+0** and an empty panel telling them to go and connect a source.++The fix adds the delivering-but-unregistered types to the list. It does not+invent a connector row: an entry appears only because alerts carrying that+`connector_type` exist inside the selected window, which is the same evidence+the count itself rests on. Their status is `ingesting` rather than `active` —+`active` is a connector *health* value reported by the poller, and nothing is+polling these.++Run against live Postgres: the defect is which rows an aggregate iterates.+Skips when no database answers, but cannot skip where it is meant to run.+"""++from __future__ import annotations++import os+import uuid++import pytest+import pytest_asyncio+from sqlalchemy import text+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++DSN = os.environ.get("DATABASE_URL", "")+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")++TENANT = uuid.UUID("0c100000-0000-0000-0000-0000000005c3")+++@pytest_asyncio.fixture+async def db():+ if "postgres" not in DSN and not REQUIRED:+ pytest.skip("needs a live Postgres with the migration chain applied (integration.yml)")+ engine = create_async_engine(DSN)+ try:+ async with engine.connect() as probe:+ await probe.execute(text("SELECT 1"))+ except Exception as exc:+ await engine.dispose()+ if REQUIRED:+ pytest.fail(+ "MSSP_ISOLATION_REQUIRED is set but no database answered at DATABASE_URL — "+ f"the source-visibility proof did not run: {type(exc).__name__}: {exc}"+ )+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")++ factory = async_sessionmaker(engine, expire_on_commit=False)+ async with factory() as session:+ await _reset(session)+ try:+ yield session+ finally:+ await _reset(session)+ await engine.dispose()+++async def _reset(session) -> None:+ await session.rollback()+ for table in ("alerts", "connectors"):+ await session.execute(text(f"DELETE FROM {table} WHERE tenant_id = CAST(:t AS uuid)"), {"t": str(TENANT)})+ await session.execute(text("DELETE FROM tenants WHERE id = CAST(:t AS uuid)"), {"t": str(TENANT)})+ await session.commit()+++async def _tenant(session) -> None:+ await session.execute(+ text("INSERT INTO tenants (id, name, slug) VALUES (CAST(:t AS uuid), 'Sources', 'sources-test') ON CONFLICT (id) DO NOTHING"),+ {"t": str(TENANT)},+ )+++async def _alerts(session, connector_type: str, count: int) -> None:+ for _ in range(count):+ await session.execute(+ text(+ """+ INSERT INTO alerts (id, tenant_id, title, severity, status, connector_type,+ created_at, updated_at)+ VALUES (CAST(:i AS uuid), CAST(:t AS uuid), :ti, 'medium', 'new', :ct, NOW(), NOW())+ """+ ),+ {"i": str(uuid.uuid4()), "t": str(TENANT), "ti": f"from {connector_type}", "ct": connector_type},+ )+ await session.commit()+++async def _connector(session, name: str, connector_type: str, health: str) -> None:+ await session.execute(+ text(+ """+ INSERT INTO connectors (id, tenant_id, name, connector_type, health_status,+ created_at, updated_at)+ VALUES (CAST(:i AS uuid), CAST(:t AS uuid), :n, :ct, :h, NOW(), NOW())+ """+ ),+ {"i": str(uuid.uuid4()), "t": str(TENANT), "n": name, "ct": connector_type, "h": health},+ )+ await session.commit()+++async def _sources(db):+ from app.api.v1.endpoints.metrics import get_dashboard_metrics++ metrics = await get_dashboard_metrics(user=_principal(), db=db, period="30d")+ return {s.name: s for s in metrics.sources}+++def _principal():+ from app.api.v1.deps import CurrentUser++ return CurrentUser(user_id=uuid.uuid4(), tenant_id=TENANT, role="admin", email="[email protected]")+++class TestWebhookIngestIsVisible:+ async def test_a_delivering_source_with_no_connector_row_is_listed(self, db) -> None:+ """The reproduction. 522 events, zero connector rows, panel read empty."""+ await _tenant(db)+ await _alerts(db, "splunk_notable", 7)++ sources = await _sources(db)++ assert "splunk_notable" in sources, f"a source delivering 7 alerts is invisible; the panel lists {sorted(sources)}"+ assert sources["splunk_notable"].count == 7++ async def test_it_is_not_labelled_as_a_healthy_connector(self, db) -> None:+ """`active` is a health value the poller reports. Nothing polls these,+ and claiming otherwise would be inventing a connector."""+ await _tenant(db)+ await _alerts(db, "generic_webhook", 3)++ assert (await _sources(db))["generic_webhook"].status == "ingesting"++ async def test_a_registered_connector_still_wins_its_own_row(self, db) -> None:+ """The negative control for the two above: a connector row must keep+ its configured name and its real health, not be duplicated by a+ second entry named after its type."""+ await _tenant(db)+ await _connector(db, "Prod CrowdStrike", "crowdstrike", "active")+ await _alerts(db, "crowdstrike", 5)++ sources = await _sources(db)++ assert "Prod CrowdStrike" in sources+ assert sources["Prod CrowdStrike"].count == 5+ assert sources["Prod CrowdStrike"].status == "active"+ assert "crowdstrike" not in sources, "the connector is listed twice"++ async def test_nothing_is_invented_for_a_tenant_with_no_events(self, db) -> None:+ """The honesty control. No alerts means no sources — the panel's empty+ state is correct there and must not be papered over."""+ await _tenant(db)++ assert await _sources(db) == {}++ async def test_another_tenants_traffic_does_not_appear(self, db) -> None:+ other = uuid.UUID("0c100000-0000-0000-0000-0000000005c4")+ await _tenant(db)+ await _alerts(db, "okta", 2)++ from app.api.v1.deps import CurrentUser+ from app.api.v1.endpoints.metrics import get_dashboard_metrics++ metrics = await get_dashboard_metrics(+ user=CurrentUser(user_id=uuid.uuid4(), tenant_id=other, role="admin", email="[email protected]"),+ db=db,+ period="30d",+ )++ assert metrics.sources == []