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
feat(detections): WS-B3 — detection management UI
beenu90a90b17a60d
diff --git a/apps/web/src/components/detections/DetectionsView.tsx b/apps/web/src/components/detections/DetectionsView.tsxindex ac3354b8a..3945ffddc 100644--- a/apps/web/src/components/detections/DetectionsView.tsx+++ b/apps/web/src/components/detections/DetectionsView.tsx@@ -15,6 +15,8 @@ import { Skeleton } from '@/components/ui/Skeleton';import { ErrorState } from '@/components/ui/ErrorState';import { EmptyState } from '@/components/ui/EmptyState';import { ContributorLeaderboard } from './ContributorLeaderboard';+import { MitreRuleHeatmap } from './MitreRuleHeatmap';+import { DriftInbox } from './DriftInbox';// ─── Demo fallback ────────────────────────────────────────────────────────────@@ -134,6 +136,30 @@ const SEVERITY_BADGE: Record<string, string> = {low: 'bg-blue-500/10 text-blue-300 ring-blue-500/40',};+// ─── Tabs ────────────────────────────────────────────────────────────────────++type DetectionsTab = 'rules' | 'coverage' | 'drift';++const TABS: { id: DetectionsTab; label: string; description: string }[] = [+ {+ id: 'rules',+ label: 'Rules',+ description: 'Author, tune, and operate the active rule library.',+ },+ {+ id: 'coverage',+ label: 'Coverage',+ description:+ 'Rule-centric MITRE ATT&CK heatmap — see what kill-chain stages are well covered and where the tuning gaps are.',+ },+ {+ id: 'drift',+ label: 'Drift',+ description:+ 'Rules that need attention: noisy false-positive rates, low confidence, or stale ones that have stopped firing.',+ },+];+// ─── Component ────────────────────────────────────────────────────────────────export function DetectionsView() {@@ -144,14 +170,26 @@ export function DetectionsView() {);const useFallback = !!error;- const rules = data?.rules ?? (useFallback ? DEMO_RULES : []);+ // Memoise so `useMemo(filtered)` and selection helpers don't see a fresh+ // array reference on every render — important because we feed `rules`+ // into a downstream useMemo dep array.+ const rules = useMemo<DetectionRule[]>(+ () => data?.rules ?? (useFallback ? DEMO_RULES : []),+ [data, useFallback],+ );+ const [tab, setTab] = useState<DetectionsTab>('rules');const [search, setSearch] = useState('');const [language, setLanguage] = useState<DetectionLanguage | 'all'>('all');const [enabledFilter, setEnabledFilter] = useState<'all' | 'on' | 'off'>('all',);+ // Selection state for bulk operations. We keep it as a Set so we can+ // do O(1) `has()` checks while rendering each rule card.+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [bulkPending, setBulkPending] = useState(false);+const filtered = useMemo(() => {const q = search.trim().toLowerCase();return rules.filter((r) => {@@ -171,6 +209,37 @@ export function DetectionsView() {});}, [rules, search, language, enabledFilter]);+ // ─── Selection helpers ─────────────────────────────────────────────────────++ const toggleSelected = (id: string) => {+ setSelected((prev) => {+ const next = new Set(prev);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ return next;+ });+ };++ const allFilteredSelected =+ filtered.length > 0 && filtered.every((r) => selected.has(r.id));++ const toggleSelectAll = () => {+ setSelected((prev) => {+ if (allFilteredSelected) {+ const next = new Set(prev);+ for (const r of filtered) next.delete(r.id);+ return next;+ }+ const next = new Set(prev);+ for (const r of filtered) next.add(r.id);+ return next;+ });+ };++ const clearSelection = () => setSelected(new Set());++ // ─── Mutations ─────────────────────────────────────────────────────────────+const toggleEnabled = async (rule: DetectionRule) => {const next = !rule.enabled;// Optimistic@@ -200,6 +269,76 @@ export function DetectionsView() {}};+ const runBulkToggle = async (enabled: boolean) => {+ const ids = Array.from(selected);+ if (ids.length === 0) return;++ if (useFallback) {+ // Demo mode — apply optimistically with no backend round-trip.+ mutate(+ (curr) =>+ curr+ ? {+ ...curr,+ rules: curr.rules.map((r) =>+ selected.has(r.id) ? { ...r, enabled } : r,+ ),+ }+ : curr,+ { revalidate: false },+ );+ toast.success(+ `${ids.length} rule${ids.length === 1 ? '' : 's'} ${enabled ? 'enabled' : 'disabled'} (demo)`,+ );+ clearSelection();+ return;+ }++ setBulkPending(true);+ // Optimistic update — flip enabled state in-memory so the UI reflects the+ // intent immediately. We re-fetch on completion to reconcile against+ // anything the backend skipped.+ mutate(+ (curr) =>+ curr+ ? {+ ...curr,+ rules: curr.rules.map((r) =>+ selected.has(r.id) ? { ...r, enabled } : r,+ ),+ }+ : curr,+ { revalidate: false },+ );++ try {+ const result = await detectionApi.bulkToggle(ids, enabled);+ const updatedCount = result.updated;+ const skippedCount = result.skipped.length;+ if (updatedCount > 0) {+ toast.success(+ `${updatedCount} rule${updatedCount === 1 ? '' : 's'} ${enabled ? 'enabled' : 'disabled'}` ++ (skippedCount > 0+ ? ` — ${skippedCount} built-in or unknown skipped`+ : ''),+ );+ } else if (skippedCount > 0) {+ toast(+ `No rules updated — ${skippedCount} were built-in or unknown.`,+ { icon: 'ℹ️' },+ );+ }+ clearSelection();+ mutate();+ } catch (err) {+ console.warn('Bulk toggle failed', err);+ toast.error('Could not update rules');+ mutate(); // Re-fetch to revert+ } finally {+ setBulkPending(false);+ }+ };+// ─── Render ────────────────────────────────────────────────────────────────return (@@ -211,9 +350,8 @@ export function DetectionsView() {Detection rules</h1><p className="mt-1 max-w-2xl text-sm text-gray-500">- Author, test, and operate detection logic across log sources. Rules- run continuously against ingested telemetry and emit alerts when- triggered.+ {TABS.find((t) => t.id === tab)?.description ??+ 'Author, test, and operate detection logic across log sources.'}</p></div><div className="flex items-center gap-2">@@ -241,6 +379,34 @@ export function DetectionsView() {</div></div>+ {/* Tabs */}+ <div+ className="flex gap-1 rounded-md border border-gray-800 bg-gray-950 p-0.5 text-sm"+ role="tablist"+ aria-label="Detection management views"+ >+ {TABS.map((t) => (+ <button+ key={t.id}+ type="button"+ role="tab"+ aria-selected={tab === t.id}+ onClick={() => {+ setTab(t.id);+ if (t.id !== 'rules') clearSelection();+ }}+ className={clsx(+ 'flex-1 rounded px-3 py-1.5 transition-colors sm:flex-none sm:min-w-[7rem]',+ tab === t.id+ ? 'bg-gray-800 text-gray-100'+ : 'text-gray-400 hover:text-gray-200',+ )}+ >+ {t.label}+ </button>+ ))}+ </div>+{/* Demo banner */}{useFallback && (<div className="rounded-md border border-amber-500/30 bg-amber-500/5 px-4 py-2 text-xs text-amber-200">@@ -249,132 +415,209 @@ export function DetectionsView() {</div>)}- {/* Filters */}- <div className="flex flex-col gap-3 rounded-lg border border-gray-800 bg-gray-900/40 p-3 lg:flex-row lg:items-center">- <div className="relative flex-1">- <input- value={search}- onChange={(e) => setSearch(e.target.value)}- placeholder="Search by name, tag, or technique (T1059, lolbin, identity)…"- className="w-full rounded-md border border-gray-800 bg-gray-950 px-9 py-2 text-sm text-gray-200 placeholder-gray-600 outline-none transition-colors focus:border-blue-500/60 focus:ring-1 focus:ring-blue-500/40"- />- <svg- className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth={2}- >- <circle cx="11" cy="11" r="7" />- <path d="m20 20-3.5-3.5" strokeLinecap="round" />- </svg>- </div>+ {tab === 'rules' && (+ <>+ {/* Filters */}+ <div className="flex flex-col gap-3 rounded-lg border border-gray-800 bg-gray-900/40 p-3 lg:flex-row lg:items-center">+ <div className="relative flex-1">+ <input+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search by name, tag, or technique (T1059, lolbin, identity)…"+ className="w-full rounded-md border border-gray-800 bg-gray-950 px-9 py-2 text-sm text-gray-200 placeholder-gray-600 outline-none transition-colors focus:border-blue-500/60 focus:ring-1 focus:ring-blue-500/40"+ />+ <svg+ className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth={2}+ >+ <circle cx="11" cy="11" r="7" />+ <path d="m20 20-3.5-3.5" strokeLinecap="round" />+ </svg>+ </div>- <select- value={language}- onChange={(e) =>- setLanguage(e.target.value as DetectionLanguage | 'all')- }- className="rounded-md border border-gray-800 bg-gray-950 px-3 py-2 text-sm text-gray-300 outline-none focus:border-blue-500/60"- >- <option value="all">All languages</option>- <option value="sigma">Sigma</option>- <option value="yara">YARA</option>- <option value="kql">KQL</option>- <option value="eql">EQL</option>- <option value="lucene">Lucene</option>- <option value="regex">Regex</option>- </select>-- <div className="inline-flex rounded-md border border-gray-800 bg-gray-950 p-0.5 text-xs">- {(['all', 'on', 'off'] as const).map((opt) => (- <button- key={opt}- onClick={() => setEnabledFilter(opt)}- className={clsx(- 'rounded px-3 py-1.5 transition-colors',- enabledFilter === opt- ? 'bg-gray-800 text-gray-100'- : 'text-gray-400 hover:text-gray-200',- )}+ <select+ value={language}+ onChange={(e) =>+ setLanguage(e.target.value as DetectionLanguage | 'all')+ }+ className="rounded-md border border-gray-800 bg-gray-950 px-3 py-2 text-sm text-gray-300 outline-none focus:border-blue-500/60">- {opt === 'all' ? 'All' : opt === 'on' ? 'Enabled' : 'Disabled'}- </button>- ))}- </div>- </div>+ <option value="all">All languages</option>+ <option value="sigma">Sigma</option>+ <option value="yara">YARA</option>+ <option value="kql">KQL</option>+ <option value="eql">EQL</option>+ <option value="lucene">Lucene</option>+ <option value="regex">Regex</option>+ </select>++ <div className="inline-flex rounded-md border border-gray-800 bg-gray-950 p-0.5 text-xs">+ {(['all', 'on', 'off'] as const).map((opt) => (+ <button+ key={opt}+ type="button"+ onClick={() => setEnabledFilter(opt)}+ className={clsx(+ 'rounded px-3 py-1.5 transition-colors',+ enabledFilter === opt+ ? 'bg-gray-800 text-gray-100'+ : 'text-gray-400 hover:text-gray-200',+ )}+ >+ {opt === 'all' ? 'All' : opt === 'on' ? 'Enabled' : 'Disabled'}+ </button>+ ))}+ </div>+ </div>- {/* Body */}- {isLoading ? (- <div className="space-y-3">- {[0, 1, 2].map((i) => (- <Skeleton key={i} className="h-24 w-full" />- ))}- </div>- ) : filtered.length === 0 ? (- rules.length === 0 ? (- <EmptyState- title="No detection rules yet"- description="Author your first detection in Sigma, KQL, or EQL — or import the AiSOC starter pack to bootstrap coverage across the MITRE ATT&CK matrix."- action={- <div className="flex gap-2">- <Link- href="/detection/new"- className="rounded-md bg-blue-500 px-4 py-2 text-sm font-medium text-white hover:bg-blue-600"+ {/* Bulk action bar — appears when rules are selected. */}+ {selected.size > 0 && (+ <div+ className="flex flex-wrap items-center gap-3 rounded-md border border-blue-500/30 bg-blue-500/5 px-4 py-2.5 text-sm"+ role="toolbar"+ aria-label="Bulk rule actions"+ >+ <span className="text-blue-200">+ <span className="font-mono font-semibold">{selected.size}</span>{' '}+ rule{selected.size === 1 ? '' : 's'} selected+ </span>+ <div className="ml-auto flex items-center gap-2">+ <button+ type="button"+ onClick={() => runBulkToggle(true)}+ disabled={bulkPending}+ className="rounded-md bg-emerald-500 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition-colors hover:bg-emerald-600 disabled:cursor-not-allowed disabled:opacity-60">- Create a rule- </Link>+ Enable+ </button><button- onClick={() =>- toast('Starter pack import is coming soon')- }- className="rounded-md border border-gray-700 px-4 py-2 text-sm text-gray-300 hover:bg-gray-800"+ type="button"+ onClick={() => runBulkToggle(false)}+ disabled={bulkPending}+ className="rounded-md bg-gray-700 px-3 py-1.5 text-xs font-medium text-gray-100 transition-colors hover:bg-gray-600 disabled:cursor-not-allowed disabled:opacity-60">- Import starter pack+ Disable+ </button>+ <button+ type="button"+ onClick={clearSelection}+ disabled={bulkPending}+ className="rounded-md border border-gray-700 px-3 py-1.5 text-xs text-gray-300 hover:bg-gray-800 disabled:opacity-60"+ >+ Clear</button></div>- }- />- ) : (- <EmptyState- title="No rules match your filters"- description="Try clearing the search, switching language, or showing all enabled states."- action={- <button- onClick={() => {- setSearch('');- setLanguage('all');- setEnabledFilter('all');- }}- className="rounded-md border border-gray-700 px-4 py-2 text-sm text-gray-300 hover:bg-gray-800"- >- Clear filters- </button>- }- />- )- ) : (- <ul className="space-y-3">- {filtered.map((rule) => (- <li key={rule.id}>- <RuleCard rule={rule} onToggle={() => toggleEnabled(rule)} />- </li>- ))}- </ul>- )}+ </div>+ )}++ {/* Body */}+ {isLoading ? (+ <div className="space-y-3">+ {[0, 1, 2].map((i) => (+ <Skeleton key={i} className="h-24 w-full" />+ ))}+ </div>+ ) : filtered.length === 0 ? (+ rules.length === 0 ? (+ <EmptyState+ title="No detection rules yet"+ description="Author your first detection in Sigma, KQL, or EQL — or import the AiSOC starter pack to bootstrap coverage across the MITRE ATT&CK matrix."+ action={+ <div className="flex gap-2">+ <Link+ href="/detection/new"+ className="rounded-md bg-blue-500 px-4 py-2 text-sm font-medium text-white hover:bg-blue-600"+ >+ Create a rule+ </Link>+ <button+ type="button"+ onClick={() =>+ toast('Starter pack import is coming soon')+ }+ className="rounded-md border border-gray-700 px-4 py-2 text-sm text-gray-300 hover:bg-gray-800"+ >+ Import starter pack+ </button>+ </div>+ }+ />+ ) : (+ <EmptyState+ title="No rules match your filters"+ description="Try clearing the search, switching language, or showing all enabled states."+ action={+ <button+ type="button"+ onClick={() => {+ setSearch('');+ setLanguage('all');+ setEnabledFilter('all');+ }}+ className="rounded-md border border-gray-700 px-4 py-2 text-sm text-gray-300 hover:bg-gray-800"+ >+ Clear filters+ </button>+ }+ />+ )+ ) : (+ <>+ {/* Select-all header — small horizontal strip above the list */}+ <div className="flex items-center gap-2 px-1 text-xs text-gray-500">+ <input+ type="checkbox"+ checked={allFilteredSelected}+ onChange={toggleSelectAll}+ aria-label={+ allFilteredSelected+ ? 'Deselect all visible rules'+ : 'Select all visible rules'+ }+ className="h-3.5 w-3.5 cursor-pointer rounded border-gray-700 bg-gray-950 accent-blue-500"+ />+ <span>+ {allFilteredSelected+ ? `All ${filtered.length} visible rule${filtered.length === 1 ? '' : 's'} selected`+ : `Select all ${filtered.length} visible rule${filtered.length === 1 ? '' : 's'}`}+ </span>+ </div>+ <ul className="space-y-3">+ {filtered.map((rule) => (+ <li key={rule.id}>+ <RuleCard+ rule={rule}+ selected={selected.has(rule.id)}+ onSelect={() => toggleSelected(rule.id)}+ onToggle={() => toggleEnabled(rule)}+ />+ </li>+ ))}+ </ul>+ </>+ )}++ {/* Footer / errors */}+ {error && !useFallback && (+ <ErrorState+ title="Couldn't load detection rules"+ description="The detection service didn't respond. We've shown the local demo set instead."+ error={error}+ onRetry={() => mutate()}+ />+ )}- {/* Footer / errors */}- {error && !useFallback && (- <ErrorState- title="Couldn't load detection rules"- description="The detection service didn't respond. We've shown the local demo set instead."- error={error}- onRetry={() => mutate()}- />+ {/* Contributor leaderboard */}+ <ContributorLeaderboard />+ </>)}- {/* Contributor leaderboard */}- <ContributorLeaderboard />+ {tab === 'coverage' && <MitreRuleHeatmap />}++ {tab === 'drift' && <DriftInbox />}</div>);}@@ -383,18 +626,40 @@ export function DetectionsView() {interface RuleCardProps {rule: DetectionRule;+ selected: boolean;+ onSelect: () => void;onToggle: () => void;}-function RuleCard({ rule, onToggle }: RuleCardProps) {+function RuleCard({ rule, selected, onSelect, onToggle }: RuleCardProps) {return (<Linkhref={`/detection/${rule.id}`}- className="group block rounded-lg border border-gray-800 bg-gray-900/40 p-4 transition-colors hover:border-gray-700 hover:bg-gray-900/70"+ className={clsx(+ 'group block rounded-lg border bg-gray-900/40 p-4 transition-colors',+ selected+ ? 'border-blue-500/50 bg-blue-500/5 hover:bg-blue-500/10'+ : 'border-gray-800 hover:border-gray-700 hover:bg-gray-900/70',+ )}><div className="flex items-start gap-4">- {/* Status dot */}+ {/* Selection checkbox + status dot stacked */}<div className="mt-1 flex flex-col items-center gap-2">+ <input+ type="checkbox"+ checked={selected}+ onClick={(e) => {+ // Don't navigate to the rule detail page on checkbox click.+ e.preventDefault();+ e.stopPropagation();+ onSelect();+ }}+ onChange={() => {+ // Click handler does the work; keep onChange to satisfy React.+ }}+ aria-label={`Select rule ${rule.name}`}+ className="h-3.5 w-3.5 cursor-pointer rounded border-gray-700 bg-gray-950 accent-blue-500"+ /><spanclassName={clsx('inline-flex h-2.5 w-2.5 rounded-full',@@ -495,6 +760,7 @@ function Toggle({ enabled, onChange }: ToggleProps) {}}role="switch"aria-checked={enabled}+ aria-label={enabled ? 'Disable rule' : 'Enable rule'}className={clsx('relative inline-flex h-5 w-9 items-center rounded-full transition-colors',enabled ? 'bg-emerald-500/70' : 'bg-gray-700',@@ -509,4 +775,3 @@ function Toggle({ enabled, onChange }: ToggleProps) {</button>);}-diff --git a/apps/web/src/components/detections/DriftInbox.tsx b/apps/web/src/components/detections/DriftInbox.tsxnew file mode 100644index 000000000..e82e128d9--- /dev/null+++ b/apps/web/src/components/detections/DriftInbox.tsx@@ -0,0 +1,317 @@+'use client';++/**+ * Detection drift inbox (WS-B3).+ *+ * Lists detection rules that need analyst attention based on rule-quality+ * heuristics computed server-side:+ *+ * - high_fp_rate — rule's false-positive rate exceeds the tuning gate+ * - low_confidence — rule confidence has decayed below the trust gate+ * - stale — rule is enabled but hasn't triggered in N days+ *+ * Thresholds live with the backend (see ``DRIFT_FP_RATE_THRESHOLD``,+ * ``DRIFT_LOW_CONFIDENCE_THRESHOLD``, ``DRIFT_STALE_DAYS`` in+ * ``services/api/app/api/v1/endpoints/detection_compat.py``) so the UI+ * doesn't drift from operator policy when the gates change.+ */++import { useMemo, useState } from 'react';+import Link from 'next/link';+import useSWR from 'swr';+import { clsx } from 'clsx';+import { formatDistanceToNow } from 'date-fns';++import { detectionApi, type DetectionDrift, type DetectionDriftEntry } from '@/lib/api';+import { Skeleton } from '@/components/ui/Skeleton';+import { ErrorState } from '@/components/ui/ErrorState';+import { EmptyState } from '@/components/ui/EmptyState';++// ─── Issue presentation ──────────────────────────────────────────────────────++type IssueId = 'high_fp_rate' | 'low_confidence' | 'stale';++interface IssueMeta {+ label: string;+ description: string;+ badge: string;+}++const ISSUE_META: Record<IssueId, IssueMeta> = {+ high_fp_rate: {+ label: 'High FP rate',+ description:+ 'False-positive rate is above the tuning gate. Tune the rule or raise its confidence threshold.',+ badge: 'bg-rose-500/15 text-rose-200 ring-1 ring-rose-500/30',+ },+ low_confidence: {+ label: 'Low confidence',+ description:+ 'Rule confidence has decayed. Either re-tune against fresh telemetry or retire it.',+ badge: 'bg-amber-500/15 text-amber-200 ring-1 ring-amber-500/30',+ },+ stale: {+ label: 'Stale',+ description:+ 'Rule is enabled but has not fired recently. Confirm coverage is still relevant.',+ badge: 'bg-sky-500/15 text-sky-200 ring-1 ring-sky-500/30',+ },+};++const ALL_ISSUES: (IssueId | 'all')[] = [+ 'all',+ 'high_fp_rate',+ 'low_confidence',+ 'stale',+];++const FILTER_LABEL: Record<(typeof ALL_ISSUES)[number], string> = {+ all: 'All',+ high_fp_rate: 'High FP',+ low_confidence: 'Low conf.',+ stale: 'Stale',+};++// ─── Component ───────────────────────────────────────────────────────────────++export function DriftInbox() {+ const { data, error, isLoading, mutate } = useSWR<DetectionDrift>(+ 'detection:drift',+ () => detectionApi.drift(),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++ const [issueFilter, setIssueFilter] = useState<IssueId | 'all'>('all');++ const filtered = useMemo(() => {+ if (!data) return [];+ if (issueFilter === 'all') return data.entries;+ return data.entries.filter((entry) =>+ entry.issues.includes(issueFilter),+ );+ }, [data, issueFilter]);++ if (isLoading) {+ return (+ <div className="space-y-3">+ <Skeleton className="h-20 w-full" />+ {[0, 1, 2].map((i) => (+ <Skeleton key={i} className="h-16 w-full" />+ ))}+ </div>+ );+ }++ if (error) {+ return (+ <ErrorState+ title="Couldn't load drift inbox"+ description="The detection service didn't respond. Try reloading once it's back."+ error={error as Error}+ onRetry={() => mutate()}+ />+ );+ }++ if (!data || data.entries.length === 0) {+ return (+ <EmptyState+ title="No rules need attention"+ description="Every active rule is firing on schedule with healthy confidence and a tolerable false-positive rate. Drop back into the rule list to author new coverage."+ />+ );+ }++ const { summary } = data;++ return (+ <div className="space-y-4">+ {/* Summary strip */}+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ <SummaryCard+ label="Need attention"+ value={summary.total}+ tone={summary.total > 0 ? 'warning' : 'neutral'}+ />+ <SummaryCard+ label="High FP rate"+ value={summary.highFpRate}+ tone={summary.highFpRate > 0 ? 'critical' : 'neutral'}+ />+ <SummaryCard+ label="Low confidence"+ value={summary.lowConfidence}+ tone={summary.lowConfidence > 0 ? 'warning' : 'neutral'}+ />+ <SummaryCard+ label="Stale"+ value={summary.stale}+ tone={summary.stale > 0 ? 'info' : 'neutral'}+ />+ </div>++ {/* Filter */}+ <div className="inline-flex rounded-md border border-gray-800 bg-gray-950 p-0.5 text-xs">+ {ALL_ISSUES.map((opt) => (+ <button+ key={opt}+ type="button"+ onClick={() => setIssueFilter(opt)}+ className={clsx(+ 'rounded px-3 py-1.5 transition-colors',+ issueFilter === opt+ ? 'bg-gray-800 text-gray-100'+ : 'text-gray-400 hover:text-gray-200',+ )}+ >+ {FILTER_LABEL[opt]}+ {opt !== 'all' && (+ <span className="ml-1.5 text-gray-500">+ ({issueCount(data.entries, opt as IssueId)})+ </span>+ )}+ </button>+ ))}+ </div>++ {/* Entries */}+ {filtered.length === 0 ? (+ <EmptyState+ title="No rules in this bucket"+ description="Switch to another bucket to see rules that need attention."+ />+ ) : (+ <ul className="space-y-2">+ {filtered.map((entry) => (+ <li key={entry.ruleId}>+ <DriftRow entry={entry} />+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}++// ─── Sub-components ──────────────────────────────────────────────────────────++interface DriftRowProps {+ entry: DetectionDriftEntry;+}++function DriftRow({ entry }: DriftRowProps) {+ const lastFired = entry.lastTriggeredAt+ ? formatDistanceToNow(new Date(entry.lastTriggeredAt), { addSuffix: true })+ : 'never';+ return (+ <Link+ href={`/detection/${entry.ruleId}`}+ className="group block rounded-lg border border-gray-800 bg-gray-900/40 p-3 transition-colors hover:border-gray-700 hover:bg-gray-900/70"+ >+ <div className="flex items-center gap-3">+ {/* Status dot */}+ <span+ className={clsx(+ 'inline-flex h-2 w-2 rounded-full',+ entry.enabled ? 'bg-emerald-400' : 'bg-gray-600',+ )}+ title={entry.enabled ? 'Enabled' : 'Disabled'}+ />++ {/* Body */}+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <h3 className="truncate text-sm font-medium text-gray-100 group-hover:text-blue-300">+ {entry.name}+ </h3>+ {entry.issues.map((issueId) => {+ const meta = ISSUE_META[issueId as IssueId];+ if (!meta) return null;+ return (+ <span+ key={issueId}+ title={meta.description}+ className={clsx(+ 'rounded-md px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide',+ meta.badge,+ )}+ >+ {meta.label}+ </span>+ );+ })}+ </div>+ <div+ className="mt-1 flex flex-wrap items-center gap-3 text-[11px] text-gray-500"+ suppressHydrationWarning+ >+ <span>+ Confidence{' '}+ <span className="font-mono text-gray-300">+ {Math.round(entry.confidence)}+ </span>+ {' / 100'}+ </span>+ <span>+ FP rate{' '}+ <span className="font-mono text-gray-300">+ {(entry.fpRate * 100).toFixed(1)}%+ </span>+ </span>+ <span>+ Last fired{' '}+ <span className="text-gray-400">{lastFired}</span>+ {entry.daysSinceTriggered != null && (+ <span className="text-gray-600">+ {' '}+ ({entry.daysSinceTriggered}d)+ </span>+ )}+ </span>+ </div>+ </div>++ {/* Severity */}+ <div className="text-[10px] uppercase tracking-wide text-gray-500">+ {entry.severity}+ </div>+ </div>+ </Link>+ );+}++interface SummaryCardProps {+ label: string;+ value: number;+ tone: 'neutral' | 'info' | 'warning' | 'critical';+}++function SummaryCard({ label, value, tone }: SummaryCardProps) {+ const toneClass =+ tone === 'critical'+ ? 'text-rose-300'+ : tone === 'warning'+ ? 'text-amber-300'+ : tone === 'info'+ ? 'text-sky-300'+ : 'text-gray-100';+ return (+ <div className="rounded-lg border border-gray-800 bg-gray-900/40 px-3 py-2.5">+ <div className="text-[11px] uppercase tracking-wide text-gray-500">+ {label}+ </div>+ <div className={clsx('mt-1 font-mono text-xl font-semibold', toneClass)}>+ {value}+ </div>+ </div>+ );+}++// ─── Helpers ─────────────────────────────────────────────────────────────────++function issueCount(entries: DetectionDriftEntry[], issue: IssueId): number {+ return entries.reduce(+ (acc, entry) => (entry.issues.includes(issue) ? acc + 1 : acc),+ 0,+ );+}diff --git a/apps/web/src/components/detections/MitreRuleHeatmap.tsx b/apps/web/src/components/detections/MitreRuleHeatmap.tsxnew file mode 100644index 000000000..8d1e9aadc--- /dev/null+++ b/apps/web/src/components/detections/MitreRuleHeatmap.tsx@@ -0,0 +1,263 @@+'use client';++/**+ * Rule-centric MITRE ATT&CK coverage heatmap (WS-B3).+ *+ * Distinct from `CoverageView.tsx` which shows the *marketplace* tier mix+ * (how many community / imported / stable rules exist per technique). This+ * heatmap is purely about the operator's *current rule library state* —+ * "how many of my enabled rules cover technique T1059?". That's the+ * question senior analysts ask when deciding what to hunt for next, and+ * what tuning work to prioritise.+ *+ * Data shape comes from `GET /api/v1/detection/coverage` which is computed+ * server-side from the `detection_rules` table and uses the rule's first+ * declared MITRE tactic to plot it (see `_primary_tactic` in+ * `services/api/app/api/v1/endpoints/detection_compat.py`).+ */++import { useMemo } from 'react';+import useSWR from 'swr';+import { clsx } from 'clsx';++import { detectionApi, type DetectionCoverage } from '@/lib/api';+import { Skeleton } from '@/components/ui/Skeleton';+import { ErrorState } from '@/components/ui/ErrorState';+import { EmptyState } from '@/components/ui/EmptyState';++// ─── Constants ───────────────────────────────────────────────────────────────++/** Bucket thresholds for the heatmap color ramp. */+const HEAT_BUCKETS: { min: number; class: string; label: string }[] = [+ { min: 5, class: 'bg-emerald-500/70 text-white', label: '5+' },+ { min: 3, class: 'bg-emerald-500/45 text-emerald-50', label: '3–4' },+ { min: 2, class: 'bg-emerald-500/30 text-emerald-100', label: '2' },+ { min: 1, class: 'bg-emerald-500/15 text-emerald-200', label: '1' },+];++const EMPTY_CELL_CLASS = 'bg-gray-800/40 text-gray-600';++function bucketClassFor(active: number, total: number): string {+ if (active === 0 && total > 0) {+ // Technique appears (rule exists) but no enabled rule — flag as a tuning gap.+ return 'bg-amber-500/15 text-amber-200 ring-1 ring-amber-500/30';+ }+ for (const bucket of HEAT_BUCKETS) {+ if (active >= bucket.min) return bucket.class;+ }+ return EMPTY_CELL_CLASS;+}++// ─── Component ───────────────────────────────────────────────────────────────++export function MitreRuleHeatmap() {+ const { data, error, isLoading, mutate } = useSWR<DetectionCoverage>(+ 'detection:coverage',+ () => detectionApi.coverage(),+ { revalidateOnFocus: false, shouldRetryOnError: false },+ );++ // Group cells by tactic for column-style rendering. Using ``useMemo`` so+ // we don't re-bucket on every keystroke when this is embedded in a tab+ // panel that re-renders often.+ const grouped = useMemo(() => {+ if (!data) return null;+ const byTactic = new Map<string, typeof data.cells>();+ for (const cell of data.cells) {+ const key = cell.tactic ?? 'unmapped';+ const list = byTactic.get(key) ?? [];+ list.push(cell);+ byTactic.set(key, list);+ }+ // Sort cells within each tactic by active count descending so the+ // strongest coverage is visible first.+ for (const list of byTactic.values()) {+ list.sort(+ (a, b) =>+ b.activeRules - a.activeRules ||+ a.techniqueId.localeCompare(b.techniqueId),+ );+ }+ return byTactic;+ }, [data]);++ if (isLoading) {+ return (+ <div className="space-y-3">+ <Skeleton className="h-20 w-full" />+ <Skeleton className="h-64 w-full" />+ </div>+ );+ }++ if (error) {+ return (+ <ErrorState+ title="Couldn't load detection coverage"+ description="The detection service didn't respond. Try reloading once it's back."+ error={error as Error}+ onRetry={() => mutate()}+ />+ );+ }++ if (!data || data.cells.length === 0) {+ return (+ <EmptyState+ title="No MITRE-mapped rules yet"+ description="Once your detection rules carry MITRE ATT&CK tactic and technique tags, they'll appear here grouped by kill-chain phase."+ />+ );+ }++ const { summary, tactics } = data;++ return (+ <div className="space-y-4">+ {/* Summary strip */}+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">+ <SummaryCard+ label="Total rules"+ value={summary.totalRules}+ tone="neutral"+ />+ <SummaryCard+ label="Enabled rules"+ value={summary.activeRules}+ tone="positive"+ />+ <SummaryCard+ label="Techniques covered"+ value={summary.coveredTechniques}+ suffix={` / ${summary.techniques}`}+ tone="positive"+ />+ <SummaryCard+ label="Disabled rules"+ value={summary.inactiveRules}+ tone={summary.inactiveRules > 0 ? 'warning' : 'neutral'}+ />+ </div>++ {/* Heatmap */}+ <div className="overflow-x-auto rounded-lg border border-gray-800 bg-gray-900/40 p-3">+ <div className="flex gap-3 min-w-max">+ {tactics.map((tactic) => {+ const cells = grouped?.get(tactic) ?? [];+ return (+ <div+ key={tactic}+ className="flex w-32 flex-col gap-1.5"+ data-testid={`tactic-column-${tactic}`}+ >+ <header className="border-b border-gray-800 pb-1.5">+ <div className="truncate text-[11px] font-semibold uppercase tracking-wide text-gray-300">+ {humanizeTactic(tactic)}+ </div>+ <div className="text-[10px] text-gray-500">+ {cells.length} technique{cells.length === 1 ? '' : 's'}+ </div>+ </header>+ <div className="space-y-1">+ {cells.map((cell) => (+ <div+ key={cell.techniqueId}+ className={clsx(+ 'rounded px-1.5 py-1 text-[11px] font-mono leading-tight transition-colors',+ bucketClassFor(cell.activeRules, cell.totalRules),+ )}+ title={[+ cell.techniqueId,+ `${cell.activeRules} enabled / ${cell.totalRules} total`,+ cell.inactiveRules > 0+ ? `${cell.inactiveRules} disabled`+ : null,+ ]+ .filter(Boolean)+ .join(' • ')}+ >+ <div className="flex items-center justify-between gap-1">+ <span className="truncate">{cell.techniqueId}</span>+ <span className="text-[10px] opacity-80">+ {cell.activeRules}+ </span>+ </div>+ </div>+ ))}+ {cells.length === 0 && (+ <div className="rounded px-1.5 py-1 text-[10px] italic text-gray-600">+ No rules+ </div>+ )}+ </div>+ </div>+ );+ })}+ </div>+ </div>++ {/* Legend */}+ <div className="flex flex-wrap items-center gap-3 text-[11px] text-gray-500">+ <span className="font-medium text-gray-400">Active rules:</span>+ {[...HEAT_BUCKETS]+ .reverse()+ .map((bucket) => (+ <span key={bucket.label} className="inline-flex items-center gap-1.5">+ <span className={clsx('h-3 w-4 rounded', bucket.class)} />+ {bucket.label}+ </span>+ ))}+ <span className="inline-flex items-center gap-1.5">+ <span className="h-3 w-4 rounded bg-amber-500/15 ring-1 ring-amber-500/30" />+ tuning gap (rules disabled)+ </span>+ </div>+ </div>+ );+}++// ─── Helpers ─────────────────────────────────────────────────────────────────++interface SummaryCardProps {+ label: string;+ value: number;+ suffix?: string;+ tone: 'neutral' | 'positive' | 'warning';+}++function SummaryCard({ label, value, suffix, tone }: SummaryCardProps) {+ const toneClass =+ tone === 'positive'+ ? 'text-emerald-300'+ : tone === 'warning'+ ? 'text-amber-300'+ : 'text-gray-100';+ return (+ <div className="rounded-lg border border-gray-800 bg-gray-900/40 px-3 py-2.5">+ <div className="text-[11px] uppercase tracking-wide text-gray-500">+ {label}+ </div>+ <div className={clsx('mt-1 font-mono text-xl font-semibold', toneClass)}>+ {value}+ {suffix && (+ <span className="text-sm font-normal text-gray-500">{suffix}</span>+ )}+ </div>+ </div>+ );+}++/**+ * Convert backend tactic strings (kebab-case or snake_case) into the+ * Title-Case labels analysts read in the ATT&CK navigator.+ *+ * We do this in the UI rather than the API so the wire format stays close+ * to what `DetectionRule.mitre_tactics` actually stores.+ */+function humanizeTactic(raw: string): string {+ if (raw === 'unmapped') return 'Unmapped';+ return raw+ .split(/[-_]/)+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))+ .join(' ');+}diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex 1d3b36bd2..7d2df2325 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -2081,6 +2081,70 @@ export interface DetectionRule {hitCount?: number;}+// ─── Detection management UI (WS-B3) ─────────────────────────────────────────+//+// Rule-centric MITRE coverage, bulk enable/disable, and the drift inbox are+// powered by ``services/api/app/api/v1/endpoints/detection_compat.py``.+// Schemas are mirrored here field-for-field so the UI gets autocomplete and+// the compiler catches drift if the backend payload ever changes shape.++export interface DetectionCoverageCell {+ techniqueId: string;+ tactic: string | null;+ techniqueName?: string | null;+ totalRules: number;+ activeRules: number;+ inactiveRules: number;+}++export interface DetectionCoverageSummary {+ totalRules: number;+ activeRules: number;+ inactiveRules: number;+ techniques: number;+ /** Techniques with at least one *active* rule. */+ coveredTechniques: number;+}++export interface DetectionCoverage {+ tactics: string[];+ cells: DetectionCoverageCell[];+ summary: DetectionCoverageSummary;+ generatedAt: string;+}++export interface DetectionDriftEntry {+ ruleId: string;+ name: string;+ severity: string;+ enabled: boolean;+ confidence: number;+ fpRate: number;+ lastTriggeredAt: string | null;+ daysSinceTriggered: number | null;+ /** ``high_fp_rate``, ``low_confidence``, ``stale``. */+ issues: string[];+}++export interface DetectionDriftSummary {+ total: number;+ highFpRate: number;+ lowConfidence: number;+ stale: number;+}++export interface DetectionDrift {+ entries: DetectionDriftEntry[];+ summary: DetectionDriftSummary;+ generatedAt: string;+}++export interface DetectionBulkToggleResult {+ updated: number;+ /** Rule IDs the backend refused (not tenant-owned, malformed, missing). */+ skipped: string[];+}+export const detectionApi = {list: () =>request<{ rules: DetectionRule[]; total: number }>(@@ -2112,6 +2176,24 @@ export const detectionApi = {body: JSON.stringify(rule),},),++ // ─── WS-B3 management endpoints ──────────────────────────────────────────++ coverage: () =>+ request<DetectionCoverage>('/api/v1/detection/coverage'),++ drift: () => request<DetectionDrift>('/api/v1/detection/drift'),++ /**+ * Enable or disable many rules in one round-trip. Built-in /+ * cross-tenant rules are silently skipped server-side and reported in+ * the ``skipped`` array of the response so the UI can surface them.+ */+ bulkToggle: (ruleIds: string[], enabled: boolean) =>+ request<DetectionBulkToggleResult>('/api/v1/detection/rules/bulk-toggle', {+ method: 'POST',+ body: JSON.stringify({ ruleIds, enabled }),+ }),};// ─── Detection-as-code proposals (Wave 2 — w2-dac) ──────────────────────────diff --git a/services/api/app/api/v1/endpoints/detection_compat.py b/services/api/app/api/v1/endpoints/detection_compat.pyindex 7bd9d4cc8..054f71da5 100644--- a/services/api/app/api/v1/endpoints/detection_compat.py+++ b/services/api/app/api/v1/endpoints/detection_compat.py@@ -24,7 +24,8 @@ from __future__ import annotationsimport jsonimport uuid-from datetime import UTC, datetime+from collections import Counter, defaultdict+from datetime import UTC, datetime, timedeltafrom typing import Annotated, Anyfrom fastapi import APIRouter, Depends, HTTPException, status@@ -379,3 +380,411 @@ async def test_rule_compat()return TestResponse(matches=len(matched_events), preview=preview)+++# ─── WS-B3: Detection management UI ──────────────────────────────────────────+#+# Three pure-data endpoints power the detection management UI in+# ``apps/web/src/components/detections``:+#+# * ``GET /api/v1/detection/coverage`` — MITRE ATT&CK heatmap data+# * ``POST /api/v1/detection/rules/bulk-toggle`` — enable/disable many rules+# * ``GET /api/v1/detection/drift`` — rules drifting from baseline+#+# All three reuse the same ``DetectionRule`` ORM model and tenant scoping as+# the existing CRUD shim above so we don't fork the permission model. The+# heuristics are kept in pure helpers (``_build_coverage`` / ``_build_drift``)+# so they can be unit-tested without spinning up a database.+++# ─── WS-B3 wire models ───────────────────────────────────────────────────────+++class CoverageCell(BaseModel):+ """One technique cell in the rule-centric MITRE coverage heatmap.++ ``intensity`` is a 0-1 ratio that the heatmap uses to pick a color+ bucket; it's max(activeRules, 1) / max-active-in-grid normalized+ client-side so we don't have to know the global max here.+ """++ techniqueId: str+ tactic: str | None = None+ techniqueName: str | None = None+ totalRules: int+ activeRules: int+ inactiveRules: int+++class CoverageSummary(BaseModel):+ totalRules: int+ activeRules: int+ inactiveRules: int+ techniques: int+ coveredTechniques: int # techniques with at least one *active* rule+++class CoverageResponse(BaseModel):+ tactics: list[str]+ cells: list[CoverageCell]+ summary: CoverageSummary+ generatedAt: str+++class BulkToggleBody(BaseModel):+ """Bulk enable/disable payload from the analyst console.++ ``ruleIds`` are accepted as plain strings so the frontend can pass the+ same IDs it already renders from ``GET /rules`` without parsing UUIDs.+ """++ ruleIds: list[str] = Field(default_factory=list, min_length=1)+ enabled: bool+++class BulkToggleResponse(BaseModel):+ updated: int+ skipped: list[str] # rule IDs that weren't found or aren't tenant-owned+++class DriftEntry(BaseModel):+ """One rule that has drifted from its tuning baseline.++ ``issues`` enumerates *which* heuristics flagged it; the UI renders one+ chip per issue so analysts see the reason without having to read the+ metric values.+ """++ ruleId: str+ name: str+ severity: str+ enabled: bool+ confidence: int+ fpRate: float+ lastTriggeredAt: str | None = None+ daysSinceTriggered: int | None = None+ issues: list[str]+++class DriftSummary(BaseModel):+ total: int+ highFpRate: int+ lowConfidence: int+ stale: int+++class DriftResponse(BaseModel):+ entries: list[DriftEntry]+ summary: DriftSummary+ generatedAt: str+++# ─── WS-B3 pure helpers (unit-testable, no DB) ───────────────────────────────+++# Drift heuristic thresholds — kept as module constants so tests can import+# them and so an operator can later expose them via env without rewriting+# the logic.+DRIFT_FP_RATE_THRESHOLD = 0.2+DRIFT_LOW_CONFIDENCE_THRESHOLD = 40+DRIFT_STALE_DAYS = 30+++def _primary_tactic(rule: DetectionRule) -> str | None:+ """Pick a single tactic to plot a rule's techniques against.++ A rule can map to multiple tactics (e.g. T1059 spans Execution and+ Initial Access). For the heatmap we just need *some* deterministic+ placement, so we take the first declared tactic and fall back to+ ``None`` (rendered as "unmapped" in the UI) if the rule didn't ship+ with a tactic at all.+ """+ if not rule.mitre_tactics:+ return None+ first = rule.mitre_tactics[0]+ return str(first) if first else None+++def _build_coverage(rules: list[DetectionRule], *, now: datetime | None = None) -> CoverageResponse:+ """Compute MITRE ATT&CK coverage from a list of rules.++ Rules without any technique mapping are still counted in the totals so+ the summary line matches the rule count an analyst sees in the table —+ they just don't appear on the heatmap.+ """++ now = now or datetime.now(UTC)++ total_rules = len(rules)+ active_rules = sum(1 for r in rules if r.status == "active")++ # technique_id -> {"tactic": str|None, "active": int, "inactive": int}+ by_technique: dict[str, dict[str, Any]] = defaultdict(+ lambda: {"tactic": None, "active": 0, "inactive": 0}+ )+ tactics_set: set[str] = set()++ for rule in rules:+ is_active = rule.status == "active"+ tactic = _primary_tactic(rule)+ if tactic:+ tactics_set.add(tactic)++ for tech in rule.mitre_techniques or []:+ tech_id = str(tech).strip()+ if not tech_id:+ continue+ cell = by_technique[tech_id]+ # Keep the first non-null tactic we see for stable plotting.+ if cell["tactic"] is None and tactic:+ cell["tactic"] = tactic+ if is_active:+ cell["active"] = int(cell["active"]) + 1+ else:+ cell["inactive"] = int(cell["inactive"]) + 1++ cells = [+ CoverageCell(+ techniqueId=tech_id,+ tactic=cell["tactic"],+ totalRules=int(cell["active"]) + int(cell["inactive"]),+ activeRules=int(cell["active"]),+ inactiveRules=int(cell["inactive"]),+ )+ for tech_id, cell in by_technique.items()+ ]+ cells.sort(key=lambda c: (c.tactic or "zzz-unmapped", c.techniqueId))++ covered = sum(1 for c in cells if c.activeRules > 0)++ return CoverageResponse(+ tactics=sorted(tactics_set),+ cells=cells,+ summary=CoverageSummary(+ totalRules=total_rules,+ activeRules=active_rules,+ inactiveRules=total_rules - active_rules,+ techniques=len(cells),+ coveredTechniques=covered,+ ),+ generatedAt=now.isoformat(),+ )+++def _build_drift(+ rules: list[DetectionRule],+ *,+ now: datetime | None = None,+ fp_threshold: float = DRIFT_FP_RATE_THRESHOLD,+ confidence_threshold: int = DRIFT_LOW_CONFIDENCE_THRESHOLD,+ stale_days: int = DRIFT_STALE_DAYS,+) -> DriftResponse:+ """Identify rules that have drifted from their tuning baseline.++ A rule lands in the inbox if *any* of these are true:++ * ``fp_rate`` exceeds the FP threshold (alert quality is degrading)+ * ``confidence`` is below the floor (analysts won't trust it anyway)+ * Rule is *enabled* but hasn't triggered in ``stale_days`` (silent+ detector — either the threat went away or the rule is broken)++ Disabled rules are never reported as "stale" since the absence of+ triggers is expected, but a disabled rule with high historical FP+ rate or low confidence still surfaces so analysts can clean it up.+ """++ now = now or datetime.now(UTC)+ stale_cutoff = now - timedelta(days=stale_days)++ entries: list[DriftEntry] = []+ counts = Counter()++ for rule in rules:+ issues: list[str] = []++ if rule.fp_rate is not None and rule.fp_rate >= fp_threshold:+ issues.append("high_fp_rate")+ counts["highFpRate"] += 1++ if rule.confidence is not None and rule.confidence < confidence_threshold:+ issues.append("low_confidence")+ counts["lowConfidence"] += 1++ is_active = rule.status == "active"+ last_trig = rule.last_triggered+ days_since: int | None = None+ if last_trig is not None:+ # Normalize to UTC if the column came back naive (depends on+ # backend driver) so the timedelta math doesn't crash on a+ # mix of aware / naive datetimes.+ ref = last_trig+ if ref.tzinfo is None:+ ref = ref.replace(tzinfo=UTC)+ days_since = max(0, (now - ref).days)++ # Stale only applies to active rules — a disabled rule with no+ # triggers is *expected* to be quiet.+ if is_active:+ if last_trig is None or last_trig.replace(+ tzinfo=last_trig.tzinfo or UTC+ ) < stale_cutoff:+ issues.append("stale")+ counts["stale"] += 1++ if not issues:+ continue++ entries.append(+ DriftEntry(+ ruleId=str(rule.id),+ name=rule.name,+ severity=rule.severity or "medium",+ enabled=is_active,+ confidence=int(rule.confidence or 0),+ fpRate=float(rule.fp_rate or 0.0),+ lastTriggeredAt=last_trig.isoformat() if last_trig else None,+ daysSinceTriggered=days_since,+ issues=issues,+ )+ )++ # Worst offenders first: more issues -> higher severity -> higher FP rate.+ severity_rank = {"critical": 4, "high": 3, "medium": 2, "low": 1, "info": 0}+ entries.sort(+ key=lambda e: (+ -len(e.issues),+ -severity_rank.get(e.severity, 0),+ -e.fpRate,+ e.name,+ )+ )++ return DriftResponse(+ entries=entries,+ summary=DriftSummary(+ total=len(entries),+ highFpRate=counts["highFpRate"],+ lowConfidence=counts["lowConfidence"],+ stale=counts["stale"],+ ),+ generatedAt=now.isoformat(),+ )+++def _coerce_uuid(raw: str) -> uuid.UUID | None:+ """Best-effort cast of a frontend rule ID to ``uuid.UUID``.++ Returns ``None`` for malformed strings so the bulk-toggle endpoint can+ surface them as ``skipped`` instead of returning a 422 for the whole+ batch — a single bad ID shouldn't block the rest.+ """+ try:+ return uuid.UUID(raw)+ except (TypeError, ValueError, AttributeError):+ return None+++# ─── WS-B3 routes ────────────────────────────────────────────────────────────++[email protected]("/coverage", response_model=CoverageResponse)+async def get_detection_coverage(+ current_user: Annotated[AuthUser, Depends(require_permission("rules:read"))],+ db: DBSession,+) -> CoverageResponse:+ """Rule-centric MITRE ATT&CK coverage for the current tenant.++ Distinct from ``/api/v1/graph/mitre/coverage`` which derives coverage+ from *alerts* — this one is what an analyst opens before a tuning+ sprint to answer "which techniques is my rule library blind to?".+ """+ tid = current_user.tenant_id+ stmt = select(DetectionRule).where(+ or_(+ DetectionRule.tenant_id == tid,+ and_(DetectionRule.tenant_id.is_(None), DetectionRule.is_builtin.is_(True)),+ )+ )+ rules = (await db.execute(stmt)).scalars().all()+ return _build_coverage(list(rules))++[email protected]("/rules/bulk-toggle", response_model=BulkToggleResponse)+async def bulk_toggle_rules(+ body: BulkToggleBody,+ current_user: Annotated[AuthUser, Depends(require_permission("rules:write"))],+ db: DBSession,+) -> BulkToggleResponse:+ """Enable or disable many tenant-owned rules in one round-trip.++ Built-in / cross-tenant rules are silently skipped (returned in+ ``skipped``) so an MSSP analyst toggling a whole category from the UI+ doesn't get a 403 just because one of the rules is platform-provided.+ """+ requested = body.ruleIds or []+ if not requested:+ return BulkToggleResponse(updated=0, skipped=[])++ parsed: dict[uuid.UUID, str] = {} # uuid -> original string+ skipped: list[str] = []+ for raw in requested:+ as_uuid = _coerce_uuid(raw)+ if as_uuid is None:+ skipped.append(raw)+ else:+ parsed[as_uuid] = raw++ if not parsed:+ return BulkToggleResponse(updated=0, skipped=skipped)++ target_status = "active" if body.enabled else "inactive"++ # Look up which of the requested IDs are actually tenant-owned. Built-in+ # rules (tenant_id IS NULL) and other-tenant rules get pushed onto+ # ``skipped`` rather than mutated.+ stmt = select(DetectionRule.id).where(+ DetectionRule.id.in_(parsed.keys()),+ DetectionRule.tenant_id == current_user.tenant_id,+ )+ owned_ids: list[uuid.UUID] = list((await db.execute(stmt)).scalars().all())+ owned_set = set(owned_ids)++ for rid in parsed.keys():+ if rid not in owned_set:+ skipped.append(parsed[rid])++ if not owned_ids:+ return BulkToggleResponse(updated=0, skipped=skipped)++ now = datetime.now(UTC)+ await db.execute(+ update(DetectionRule)+ .where(DetectionRule.id.in_(owned_ids))+ .values(status=target_status, updated_at=now)+ )+ await db.commit()++ return BulkToggleResponse(updated=len(owned_ids), skipped=skipped)++[email protected]("/drift", response_model=DriftResponse)+async def get_detection_drift(+ current_user: Annotated[AuthUser, Depends(require_permission("rules:read"))],+ db: DBSession,+) -> DriftResponse:+ """Detection drift inbox — rules that need an analyst's attention.++ Surfaces rules with elevated FP rate, low confidence, or stale (no+ recent triggers despite being enabled). The UI renders this as a tab+ on the Detections page so analysts have a single queue to work+ instead of paginating the full library hunting for noise.+ """+ tid = current_user.tenant_id+ stmt = select(DetectionRule).where(+ or_(+ DetectionRule.tenant_id == tid,+ and_(DetectionRule.tenant_id.is_(None), DetectionRule.is_builtin.is_(True)),+ )+ )+ rules = (await db.execute(stmt)).scalars().all()+ return _build_drift(list(rules))diff --git a/services/api/tests/test_detection_management.py b/services/api/tests/test_detection_management.pynew file mode 100644index 000000000..97347315b--- /dev/null+++ b/services/api/tests/test_detection_management.py@@ -0,0 +1,392 @@+"""Tests for WS-B3 — Detection management UI backend.++These tests pin the contract the analyst console relies on for:++* ``GET /api/v1/detection/coverage`` — rule-centric MITRE heatmap+* ``POST /api/v1/detection/rules/bulk-toggle`` — bulk enable/disable+* ``GET /api/v1/detection/drift`` — rules that need attention++The HTTP wrappers are thin DB queries that defer all interesting logic to+``_build_coverage``, ``_build_drift``, and ``_coerce_uuid``. Testing the+pure helpers gives full coverage of the heuristics without needing+Postgres or the full FastAPI app, which keeps these tests fast and+trivially runnable in CI on every push.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass, field+from datetime import UTC, datetime, timedelta++import pytest+from app.api.v1.endpoints.detection_compat import (+ DRIFT_FP_RATE_THRESHOLD,+ DRIFT_LOW_CONFIDENCE_THRESHOLD,+ DRIFT_STALE_DAYS,+ _build_coverage,+ _build_drift,+ _coerce_uuid,+ _primary_tactic,+)+++# ---------------------------------------------------------------------------+# Test doubles+# ---------------------------------------------------------------------------+++@dataclass+class FakeRule:+ """Minimal stand-in for ``DetectionRule`` rows.++ The pure helpers only read attributes — they never persist — so a+ plain dataclass with the right field names is enough. We use this+ instead of ``DetectionRule`` directly so tests don't drag in the ORM+ machinery.+ """++ id: uuid.UUID = field(default_factory=uuid.uuid4)+ name: str = "Rule"+ severity: str = "medium"+ status: str = "active" # "active" | "inactive" | "testing"+ confidence: int = 50+ fp_rate: float = 0.0+ mitre_tactics: list[str] = field(default_factory=list)+ mitre_techniques: list[str] = field(default_factory=list)+ last_triggered: datetime | None = None+++# ---------------------------------------------------------------------------+# _primary_tactic+# ---------------------------------------------------------------------------+++class TestPrimaryTactic:+ """We deterministically pick the first declared tactic for plotting."""++ def test_picks_first_tactic(self):+ rule = FakeRule(mitre_tactics=["execution", "initial-access"])+ assert _primary_tactic(rule) == "execution"++ def test_returns_none_when_no_tactics(self):+ rule = FakeRule(mitre_tactics=[])+ assert _primary_tactic(rule) is None++ def test_handles_falsy_first_entry(self):+ rule = FakeRule(mitre_tactics=["", "execution"])+ assert _primary_tactic(rule) is None+++# ---------------------------------------------------------------------------+# _build_coverage+# ---------------------------------------------------------------------------+++class TestBuildCoverage:+ """Coverage heatmap should reflect the enabled-rule distribution."""++ def test_empty_library(self):+ cov = _build_coverage([])+ assert cov.tactics == []+ assert cov.cells == []+ assert cov.summary.totalRules == 0+ assert cov.summary.activeRules == 0+ assert cov.summary.coveredTechniques == 0++ def test_single_active_rule_one_technique(self):+ rule = FakeRule(+ status="active",+ mitre_tactics=["execution"],+ mitre_techniques=["T1059"],+ )+ cov = _build_coverage([rule])+ assert cov.tactics == ["execution"]+ assert len(cov.cells) == 1+ cell = cov.cells[0]+ assert cell.techniqueId == "T1059"+ assert cell.tactic == "execution"+ assert cell.activeRules == 1+ assert cell.inactiveRules == 0+ assert cell.totalRules == 1+ assert cov.summary.activeRules == 1+ assert cov.summary.coveredTechniques == 1++ def test_inactive_rule_does_not_count_as_covered(self):+ # A disabled rule shouldn't paint a technique as "covered" — that's+ # the whole point of the heatmap surfacing tuning gaps.+ rule = FakeRule(+ status="inactive",+ mitre_tactics=["execution"],+ mitre_techniques=["T1059"],+ )+ cov = _build_coverage([rule])+ assert len(cov.cells) == 1+ assert cov.cells[0].activeRules == 0+ assert cov.cells[0].inactiveRules == 1+ # The technique appears in the grid (so analysts can re-enable+ # it) but coveredTechniques is 0.+ assert cov.summary.coveredTechniques == 0+ assert cov.summary.techniques == 1++ def test_multiple_rules_same_technique_aggregate(self):+ rules = [+ FakeRule(status="active", mitre_techniques=["T1059"], mitre_tactics=["execution"]),+ FakeRule(status="active", mitre_techniques=["T1059"], mitre_tactics=["execution"]),+ FakeRule(status="inactive", mitre_techniques=["T1059"], mitre_tactics=["execution"]),+ ]+ cov = _build_coverage(rules)+ assert len(cov.cells) == 1+ cell = cov.cells[0]+ assert cell.activeRules == 2+ assert cell.inactiveRules == 1+ assert cell.totalRules == 3++ def test_unmapped_rules_count_in_summary_but_not_in_cells(self):+ # Rules without a technique mapping shouldn't appear on the+ # heatmap (we have nothing to plot), but they still count toward+ # totalRules so the analyst sees the right library size.+ rules = [+ FakeRule(status="active", mitre_techniques=[]),+ FakeRule(status="active", mitre_techniques=["T1059"], mitre_tactics=["execution"]),+ ]+ cov = _build_coverage(rules)+ assert cov.summary.totalRules == 2+ assert cov.summary.activeRules == 2+ assert len(cov.cells) == 1 # only the mapped technique+ assert cov.summary.techniques == 1++ def test_skips_blank_technique_strings(self):+ # JSONB columns occasionally contain stray empty strings; they+ # shouldn't end up as their own grid cell.+ rule = FakeRule(+ status="active",+ mitre_techniques=["", "T1059", " "],+ mitre_tactics=["execution"],+ )+ cov = _build_coverage([rule])+ assert [c.techniqueId for c in cov.cells] == ["T1059"]++ def test_cells_sorted_for_stable_rendering(self):+ # Heatmap cells must be returned in a stable order so the UI+ # doesn't shuffle rows on every refresh.+ rules = [+ FakeRule(status="active", mitre_techniques=["T1059"], mitre_tactics=["execution"]),+ FakeRule(status="active", mitre_techniques=["T1003"], mitre_tactics=["credential-access"]),+ FakeRule(status="active", mitre_techniques=["T1566"], mitre_tactics=["initial-access"]),+ ]+ cov = _build_coverage(rules)+ # First by tactic alphabetical, then by technique id.+ tactics_in_order = [c.tactic for c in cov.cells]+ assert tactics_in_order == sorted(tactics_in_order)+++# ---------------------------------------------------------------------------+# _build_drift+# ---------------------------------------------------------------------------+++class TestBuildDrift:+ """Drift inbox surfaces rules that need analyst attention."""++ NOW = datetime(2026, 5, 9, tzinfo=UTC)++ def test_empty_library(self):+ out = _build_drift([], now=self.NOW)+ assert out.entries == []+ assert out.summary.total == 0++ def test_clean_rule_does_not_appear(self):+ # Active, low FP, recently triggered, decent confidence → nothing+ # to flag.+ rule = FakeRule(+ status="active",+ confidence=80,+ fp_rate=0.05,+ last_triggered=self.NOW - timedelta(days=1),+ )+ out = _build_drift([rule], now=self.NOW)+ assert out.entries == []+ assert out.summary.total == 0++ def test_high_fp_rate_flags_rule(self):+ rule = FakeRule(+ status="active",+ confidence=80,+ fp_rate=DRIFT_FP_RATE_THRESHOLD + 0.05,+ last_triggered=self.NOW - timedelta(hours=1),+ )+ out = _build_drift([rule], now=self.NOW)+ assert len(out.entries) == 1+ assert "high_fp_rate" in out.entries[0].issues+ assert out.summary.highFpRate == 1++ def test_low_confidence_flags_rule(self):+ rule = FakeRule(+ status="active",+ confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD - 1,+ fp_rate=0.0,+ last_triggered=self.NOW - timedelta(hours=1),+ )+ out = _build_drift([rule], now=self.NOW)+ assert len(out.entries) == 1+ assert "low_confidence" in out.entries[0].issues+ assert out.summary.lowConfidence == 1++ def test_stale_active_rule_flags_rule(self):+ rule = FakeRule(+ status="active",+ confidence=80,+ fp_rate=0.0,+ last_triggered=self.NOW - timedelta(days=DRIFT_STALE_DAYS + 1),+ )+ out = _build_drift([rule], now=self.NOW)+ assert len(out.entries) == 1+ assert "stale" in out.entries[0].issues+ assert out.entries[0].daysSinceTriggered == DRIFT_STALE_DAYS + 1++ def test_active_rule_never_triggered_is_stale(self):+ # A rule that's been enabled long enough to expect a trigger but+ # has none recorded — likely broken or noisy syntax.+ rule = FakeRule(status="active", confidence=80, fp_rate=0.0, last_triggered=None)+ out = _build_drift([rule], now=self.NOW)+ assert len(out.entries) == 1+ assert "stale" in out.entries[0].issues+ assert out.entries[0].daysSinceTriggered is None++ def test_inactive_rule_is_never_stale(self):+ # A disabled rule with no recent triggers is *expected* — don't+ # nag analysts about it.+ rule = FakeRule(+ status="inactive",+ confidence=80,+ fp_rate=0.0,+ last_triggered=None,+ )+ out = _build_drift([rule], now=self.NOW)+ assert out.entries == []++ def test_inactive_rule_with_high_fp_still_flagged(self):+ # …but a disabled rule with a bad FP history still surfaces so+ # someone can clean it up rather than letting it rot in the DB.+ rule = FakeRule(+ status="inactive",+ confidence=80,+ fp_rate=DRIFT_FP_RATE_THRESHOLD + 0.1,+ last_triggered=None,+ )+ out = _build_drift([rule], now=self.NOW)+ assert len(out.entries) == 1+ assert "high_fp_rate" in out.entries[0].issues+ assert "stale" not in out.entries[0].issues+ assert out.entries[0].enabled is False++ def test_multiple_issues_aggregated(self):+ rule = FakeRule(+ status="active",+ confidence=10,+ fp_rate=0.5,+ last_triggered=self.NOW - timedelta(days=90),+ )+ out = _build_drift([rule], now=self.NOW)+ assert len(out.entries) == 1+ issues = set(out.entries[0].issues)+ assert issues == {"high_fp_rate", "low_confidence", "stale"}++ def test_entries_sorted_worst_first(self):+ # 3-issue rule beats 1-issue rule; within the same issue count,+ # higher severity wins.+ rule_a = FakeRule(+ name="aa",+ status="active",+ confidence=80,+ fp_rate=DRIFT_FP_RATE_THRESHOLD + 0.05,+ last_triggered=self.NOW - timedelta(hours=1),+ )+ rule_b = FakeRule(+ name="bb",+ status="active",+ confidence=10,+ fp_rate=0.5,+ last_triggered=self.NOW - timedelta(days=90),+ severity="critical",+ )+ rule_c = FakeRule(+ name="cc",+ status="active",+ confidence=10,+ fp_rate=0.5,+ last_triggered=self.NOW - timedelta(days=90),+ severity="medium",+ )+ out = _build_drift([rule_a, rule_b, rule_c], now=self.NOW)+ names_in_order = [e.name for e in out.entries]+ assert names_in_order == ["bb", "cc", "aa"]++ def test_summary_counts_each_issue_independently(self):+ # A rule with 2 issues contributes to 2 counters, not just 1.+ rule = FakeRule(+ status="active",+ confidence=10,+ fp_rate=0.5,+ last_triggered=self.NOW - timedelta(days=1),+ )+ out = _build_drift([rule], now=self.NOW)+ assert out.summary.total == 1 # one entry…+ assert out.summary.highFpRate == 1+ assert out.summary.lowConfidence == 1+ assert out.summary.stale == 0 # …recent trigger so not stale.++ def test_handles_naive_datetime(self):+ # Some DB drivers return naive datetimes — make sure we don't+ # blow up on tz-mixing.+ rule = FakeRule(+ status="active",+ confidence=80,+ fp_rate=0.0,+ last_triggered=datetime(2026, 5, 1), # naive+ )+ out = _build_drift([rule], now=self.NOW)+ # 8 days ago → not stale at default threshold.+ assert out.entries == []+++# ---------------------------------------------------------------------------+# _coerce_uuid+# ---------------------------------------------------------------------------+++class TestCoerceUuid:+ """Bulk-toggle mustn't 422 on a single bad ID — bad IDs go to ``skipped``."""++ def test_valid_uuid_string(self):+ u = uuid.uuid4()+ assert _coerce_uuid(str(u)) == u++ def test_garbage_returns_none(self):+ assert _coerce_uuid("not-a-uuid") is None++ def test_empty_string_returns_none(self):+ assert _coerce_uuid("") is None++ def test_none_input_returns_none(self):+ # The frontend technically can't send ``None``, but defensive+ # coding because pydantic's coercion can produce surprises.+ assert _coerce_uuid(None) is None # type: ignore[arg-type]+++# ---------------------------------------------------------------------------+# Threshold sanity (catches accidental regressions in product behavior)+# ---------------------------------------------------------------------------+++def test_thresholds_are_documented_constants():+ """Catch accidental changes to the drift thresholds.++ Tuning the thresholds is a product decision; this test exists so that+ if someone tightens them they have to update this assertion *and*+ docs, not silently change the inbox volume.+ """+ assert DRIFT_FP_RATE_THRESHOLD == pytest.approx(0.2)+ assert DRIFT_LOW_CONFIDENCE_THRESHOLD == 40+ assert DRIFT_STALE_DAYS == 30