Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

feat(detections): WS-B3.1 — confidence trends endpoint + UI panel

beenu20494a3a9fe7
diff --git a/apps/web/src/components/detections/ConfidenceTrends.tsx b/apps/web/src/components/detections/ConfidenceTrends.tsx
new file mode 100644
index 000000000..e6756efa0
--- /dev/null
+++ b/apps/web/src/components/detections/ConfidenceTrends.tsx
@@ -0,0 +1,458 @@
+'use client';
+
+/**
+ * Rule-confidence trends panel (WS-B3).
+ *
+ * The plan asks for "confidence trends". We don't capture rule confidence
+ * historically yet, so we render the *snapshot* analyst question that
+ * actually drives tuning work:
+ *
+ * 1. How is rule confidence distributed across the library? (histogram)
+ * 2. Which MITRE tactics are weakest on average? (per-tactic averages)
+ * 3. Which specific rules are dragging the average down vs which are
+ * pulling it up? (lowest / highest tables)
+ *
+ * Backed by `GET /api/v1/detection/confidence`. See
+ * `_build_confidence` in `services/api/app/api/v1/endpoints/detection_compat.py`.
+ */
+
+import { useMemo } from 'react';
+import Link from 'next/link';
+import useSWR from 'swr';
+import { clsx } from 'clsx';
+
+import {
+ detectionApi,
+ type DetectionConfidence,
+ type ConfidenceBucket,
+ type ConfidenceRuleEntry,
+ type TacticConfidence,
+} from '@/lib/api';
+import { Skeleton } from '@/components/ui/Skeleton';
+import { ErrorState } from '@/components/ui/ErrorState';
+import { EmptyState } from '@/components/ui/EmptyState';
+
+// ─── Constants ───────────────────────────────────────────────────────────────
+
+/**
+ * Confidence-floor → tone mapping for histogram bars and tactic bars.
+ *
+ * 0–25 is critically untrustworthy (red), 26–50 needs tuning (amber),
+ * 51–75 is acceptable (sky), 76–100 is high-trust (emerald). The same
+ * scale is used everywhere on this page so an analyst's eye learns one
+ * color story.
+ */
+function toneForConfidence(
+ value: number,
+): { bar: string; text: string; ring: string } {
+ if (value < 26) {
+ return {
+ bar: 'bg-rose-500/70',
+ text: 'text-rose-300',
+ ring: 'ring-rose-500/30',
+ };
+ }
+ if (value < 51) {
+ return {
+ bar: 'bg-amber-500/70',
+ text: 'text-amber-300',
+ ring: 'ring-amber-500/30',
+ };
+ }
+ if (value < 76) {
+ return {
+ bar: 'bg-sky-500/70',
+ text: 'text-sky-300',
+ ring: 'ring-sky-500/30',
+ };
+ }
+ return {
+ bar: 'bg-emerald-500/70',
+ text: 'text-emerald-300',
+ ring: 'ring-emerald-500/30',
+ };
+}
+
+const SEVERITY_BADGE: Record<string, string> = {
+ critical: 'bg-red-500/10 text-red-300 ring-red-500/40',
+ high: 'bg-orange-500/10 text-orange-300 ring-orange-500/40',
+ medium: 'bg-yellow-500/10 text-yellow-300 ring-yellow-500/40',
+ low: 'bg-blue-500/10 text-blue-300 ring-blue-500/40',
+};
+
+// ─── Component ───────────────────────────────────────────────────────────────
+
+export function ConfidenceTrends() {
+ const { data, error, isLoading, mutate } = useSWR<DetectionConfidence>(
+ 'detection:confidence',
+ () => detectionApi.confidence(),
+ { revalidateOnFocus: false, shouldRetryOnError: false },
+ );
+
+ const maxBucketCount = useMemo(() => {
+ if (!data) return 0;
+ return data.buckets.reduce((acc, b) => Math.max(acc, b.count), 0);
+ }, [data]);
+
+ if (isLoading) {
+ return (
+ <div className="space-y-4">
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ {[0, 1, 2, 3].map((i) => (
+ <Skeleton key={i} className="h-20 w-full" />
+ ))}
+ </div>
+ <Skeleton className="h-56 w-full" />
+ <Skeleton className="h-72 w-full" />
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <ErrorState
+ title="Couldn't load confidence trends"
+ description="The detection service didn't respond. Try reloading once it's back."
+ error={error as Error}
+ onRetry={() => mutate()}
+ />
+ );
+ }
+
+ if (!data || data.summary.totalRules === 0) {
+ return (
+ <EmptyState
+ title="No rules yet"
+ description="Once you author or import a few detection rules, this view tracks how confident the library is per MITRE tactic and surfaces the weakest rules to tune first."
+ />
+ );
+ }
+
+ const { summary, buckets, tactics, lowest, highest } = data;
+ const summaryTone = toneForConfidence(summary.avgConfidence);
+
+ return (
+ <div className="space-y-5">
+ {/* Summary strip */}
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <SummaryCard
+ label="Avg confidence"
+ value={`${summary.avgConfidence}/100`}
+ tone={summaryTone.text}
+ hint={`Active ${summary.avgConfidenceActive}/100`}
+ />
+ <SummaryCard
+ label="Median"
+ value={`${summary.medianConfidence}/100`}
+ tone="text-gray-100"
+ hint={`${summary.totalRules} rule${summary.totalRules === 1 ? '' : 's'}`}
+ />
+ <SummaryCard
+ label="Active rules"
+ value={String(summary.activeRules)}
+ tone="text-gray-100"
+ hint={`${summary.totalRules - summary.activeRules} disabled`}
+ />
+ <SummaryCard
+ label="Below trust gate"
+ value={String(summary.lowConfidence)}
+ tone={summary.lowConfidence > 0 ? 'text-amber-300' : 'text-gray-100'}
+ hint="< 60/100 confidence"
+ />
+ </div>
+
+ {/* Histogram */}
+ <section
+ aria-label="Confidence distribution"
+ className="rounded-lg border border-gray-800 bg-gray-900/40 p-4"
+ >
+ <header className="flex items-baseline justify-between">
+ <h2 className="text-sm font-semibold text-gray-100">
+ Confidence distribution
+ </h2>
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">
+ Active rules shown stacked on enabled rules
+ </span>
+ </header>
+ <p className="mt-1 text-xs text-gray-500">
+ Where the rule library sits today on the 0–100 confidence scale.
+ Bars fill more darkly with their <em>active</em> share so a tall
+ but pale bar means many disabled rules in that band.
+ </p>
+ <div className="mt-4 grid grid-cols-4 gap-3">
+ {buckets.map((bucket) => (
+ <HistogramBar
+ key={bucket.label}
+ bucket={bucket}
+ maxCount={maxBucketCount}
+ />
+ ))}
+ </div>
+ </section>
+
+ {/* Per-tactic averages */}
+ <section
+ aria-label="Average confidence by MITRE tactic"
+ className="rounded-lg border border-gray-800 bg-gray-900/40 p-4"
+ >
+ <header className="flex items-baseline justify-between">
+ <h2 className="text-sm font-semibold text-gray-100">
+ Confidence by MITRE tactic
+ </h2>
+ <span className="text-[11px] uppercase tracking-wide text-gray-500">
+ Lower bars = tuning priority
+ </span>
+ </header>
+ <p className="mt-1 text-xs text-gray-500">
+ Each row averages the confidence of every rule whose primary
+ MITRE tactic falls in that column. Faded portion of each bar
+ shows the gap between all rules and the *active* rules — wide
+ gaps mean low-confidence rules have been disabled but never
+ retired.
+ </p>
+ <ul className="mt-4 space-y-2.5">
+ {tactics.length === 0 ? (
+ <li className="text-xs text-gray-500">
+ No rules tagged with a MITRE tactic yet.
+ </li>
+ ) : (
+ tactics.map((tactic) => (
+ <TacticBar key={tactic.tactic} tactic={tactic} />
+ ))
+ )}
+ </ul>
+ </section>
+
+ {/* Worst & best lists side by side on desktop */}
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <RuleList
+ title="Lowest confidence"
+ subtitle="Tune or retire — these rules are dragging the average down."
+ tone="critical"
+ entries={lowest}
+ />
+ <RuleList
+ title="Highest confidence"
+ subtitle="High-trust rules — copy their tradecraft when you author new coverage."
+ tone="positive"
+ entries={highest}
+ />
+ </div>
+ </div>
+ );
+}
+
+// ─── Sub-components ──────────────────────────────────────────────────────────
+
+interface HistogramBarProps {
+ bucket: ConfidenceBucket;
+ maxCount: number;
+}
+
+function HistogramBar({ bucket, maxCount }: HistogramBarProps) {
+ // Use the bucket midpoint as the tone signal so visual color tracks
+ // confidence rather than count.
+ const mid = (bucket.floor + bucket.ceil) / 2;
+ const tone = toneForConfidence(mid);
+ const totalPct = maxCount === 0 ? 0 : (bucket.count / maxCount) * 100;
+ const activePct =
+ bucket.count === 0 ? 0 : (bucket.activeCount / bucket.count) * 100;
+ return (
+ <div className="flex flex-col items-center gap-1.5">
+ <div className="flex h-32 w-full items-end justify-center">
+ <div
+ className="relative w-full max-w-[3.5rem] overflow-hidden rounded-t-md bg-gray-800/60"
+ style={{ height: `${Math.max(totalPct, bucket.count > 0 ? 4 : 0)}%` }}
+ aria-label={`${bucket.count} rules between ${bucket.label} confidence, ${bucket.activeCount} active`}
+ >
+ <div
+ className={clsx('absolute bottom-0 left-0 right-0', tone.bar)}
+ style={{ height: `${activePct}%` }}
+ />
+ </div>
+ </div>
+ <div className="text-center">
+ <div className={clsx('font-mono text-sm font-semibold', tone.text)}>
+ {bucket.count}
+ </div>
+ <div className="text-[10px] uppercase tracking-wide text-gray-500">
+ {bucket.label}
+ </div>
+ {bucket.activeCount !== bucket.count && (
+ <div className="text-[10px] text-gray-500">
+ {bucket.activeCount} active
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+interface TacticBarProps {
+ tactic: TacticConfidence;
+}
+
+function TacticBar({ tactic }: TacticBarProps) {
+ const tone = toneForConfidence(tactic.avgConfidence);
+ const total = Math.max(0, Math.min(100, tactic.avgConfidence));
+ const active = Math.max(0, Math.min(100, tactic.avgConfidenceActive));
+ return (
+ <li className="grid grid-cols-[10rem_1fr_5rem] items-center gap-3">
+ <div className="truncate text-xs font-medium text-gray-300">
+ {humanizeTactic(tactic.tactic)}
+ </div>
+ <div className="relative h-2.5 w-full overflow-hidden rounded-full bg-gray-800/70">
+ <div
+ className={clsx('absolute inset-y-0 left-0 opacity-40', tone.bar)}
+ style={{ width: `${total}%` }}
+ aria-hidden
+ />
+ <div
+ className={clsx('absolute inset-y-0 left-0', tone.bar)}
+ style={{ width: `${active}%` }}
+ aria-hidden
+ />
+ </div>
+ <div className="text-right text-xs">
+ <span className={clsx('font-mono font-semibold', tone.text)}>
+ {tactic.avgConfidenceActive}
+ </span>
+ <span className="text-gray-600">/100</span>
+ <div className="text-[10px] text-gray-500">
+ {tactic.activeRules}/{tactic.rules} active
+ </div>
+ </div>
+ </li>
+ );
+}
+
+interface RuleListProps {
+ title: string;
+ subtitle: string;
+ tone: 'critical' | 'positive';
+ entries: ConfidenceRuleEntry[];
+}
+
+function RuleList({ title, subtitle, tone, entries }: RuleListProps) {
+ const headerTone =
+ tone === 'critical' ? 'text-rose-200' : 'text-emerald-200';
+ return (
+ <section
+ aria-label={title}
+ className="rounded-lg border border-gray-800 bg-gray-900/40 p-4"
+ >
+ <header>
+ <h2 className={clsx('text-sm font-semibold', headerTone)}>{title}</h2>
+ <p className="mt-1 text-xs text-gray-500">{subtitle}</p>
+ </header>
+ {entries.length === 0 ? (
+ <p className="mt-4 text-xs text-gray-500">No rules to show.</p>
+ ) : (
+ <ul className="mt-3 divide-y divide-gray-800/80">
+ {entries.map((entry) => (
+ <li key={entry.ruleId}>
+ <RuleListRow entry={entry} />
+ </li>
+ ))}
+ </ul>
+ )}
+ </section>
+ );
+}
+
+interface RuleListRowProps {
+ entry: ConfidenceRuleEntry;
+}
+
+function RuleListRow({ entry }: RuleListRowProps) {
+ const tone = toneForConfidence(entry.confidence);
+ return (
+ <Link
+ href={`/detection/${entry.ruleId}`}
+ className="group flex items-center gap-3 py-2.5 transition-colors hover:bg-gray-900/60"
+ >
+ <span
+ className={clsx(
+ 'inline-flex h-2 w-2 shrink-0 rounded-full',
+ entry.enabled ? 'bg-emerald-400' : 'bg-gray-600',
+ )}
+ title={entry.enabled ? 'Enabled' : 'Disabled'}
+ />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <h3 className="truncate text-sm text-gray-100 group-hover:text-blue-300">
+ {entry.name}
+ </h3>
+ {entry.severity && (
+ <span
+ className={clsx(
+ 'rounded-md px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide ring-1',
+ SEVERITY_BADGE[entry.severity] ??
+ 'bg-gray-800 text-gray-300 ring-gray-700',
+ )}
+ >
+ {entry.severity}
+ </span>
+ )}
+ </div>
+ <div className="mt-0.5 flex items-center gap-3 text-[11px] text-gray-500">
+ {entry.primaryTactic && (
+ <span>{humanizeTactic(entry.primaryTactic)}</span>
+ )}
+ <span>
+ FP rate{' '}
+ <span className="font-mono text-gray-400">
+ {(entry.fpRate * 100).toFixed(1)}%
+ </span>
+ </span>
+ </div>
+ </div>
+ <div className="text-right">
+ <div className={clsx('font-mono text-sm font-semibold', tone.text)}>
+ {entry.confidence}
+ </div>
+ <div className="text-[10px] uppercase tracking-wide text-gray-500">
+ /100
+ </div>
+ </div>
+ </Link>
+ );
+}
+
+interface SummaryCardProps {
+ label: string;
+ value: string;
+ hint?: string;
+ tone: string;
+}
+
+function SummaryCard({ label, value, hint, tone }: SummaryCardProps) {
+ 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', tone)}>
+ {value}
+ </div>
+ {hint && (
+ <div className="mt-0.5 text-[11px] text-gray-500">{hint}</div>
+ )}
+ </div>
+ );
+}
+
+// ─── Helpers ─────────────────────────────────────────────────────────────────
+
+/**
+ * MITRE tactic IDs come back as ``initial-access`` or ``credential-access``
+ * — render them as ``Initial Access`` for the UI without a lookup table.
+ */
+function humanizeTactic(tactic: string): string {
+ if (!tactic) return 'Unmapped';
+ return tactic
+ .split(/[-_\s]+/)
+ .filter(Boolean)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(' ');
+}
diff --git a/apps/web/src/components/detections/DetectionsView.tsx b/apps/web/src/components/detections/DetectionsView.tsx
index 3945ffddc..4536deab1 100644
--- a/apps/web/src/components/detections/DetectionsView.tsx
+++ b/apps/web/src/components/detections/DetectionsView.tsx
@@ -16,6 +16,7 @@ import { ErrorState } from '@/components/ui/ErrorState';
import { EmptyState } from '@/components/ui/EmptyState';
import { ContributorLeaderboard } from './ContributorLeaderboard';
import { MitreRuleHeatmap } from './MitreRuleHeatmap';
+import { ConfidenceTrends } from './ConfidenceTrends';
import { DriftInbox } from './DriftInbox';
// ─── Demo fallback ────────────────────────────────────────────────────────────
@@ -138,7 +139,7 @@ const SEVERITY_BADGE: Record<string, string> = {
// ─── Tabs ────────────────────────────────────────────────────────────────────
-type DetectionsTab = 'rules' | 'coverage' | 'drift';
+type DetectionsTab = 'rules' | 'coverage' | 'confidence' | 'drift';
const TABS: { id: DetectionsTab; label: string; description: string }[] = [
{
@@ -152,6 +153,12 @@ const TABS: { id: DetectionsTab; label: string; description: string }[] = [
description:
'Rule-centric MITRE ATT&CK heatmap — see what kill-chain stages are well covered and where the tuning gaps are.',
},
+ {
+ id: 'confidence',
+ label: 'Confidence',
+ description:
+ 'How trustworthy is your rule library? Distribution, per-tactic averages, and the rules dragging the average down.',
+ },
{
id: 'drift',
label: 'Drift',
@@ -617,6 +624,8 @@ export function DetectionsView() {
{tab === 'coverage' && <MitreRuleHeatmap />}
+ {tab === 'confidence' && <ConfidenceTrends />}
+
{tab === 'drift' && <DriftInbox />}
</div>
);
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 7d2df2325..a37bc5ee7 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -2145,6 +2145,55 @@ export interface DetectionBulkToggleResult {
skipped: string[];
}
+/** One bar in the confidence histogram. */
+export interface ConfidenceBucket {
+ /** Display label, e.g. ``"0–25"``. */
+ label: string;
+ floor: number;
+ ceil: number;
+ count: number;
+ activeCount: number;
+}
+
+/** Per-MITRE-tactic confidence average. */
+export interface TacticConfidence {
+ tactic: string;
+ rules: number;
+ activeRules: number;
+ avgConfidence: number;
+ avgConfidenceActive: number;
+}
+
+/** Compact rule reference for the lowest/highest tables. */
+export interface ConfidenceRuleEntry {
+ ruleId: string;
+ name: string;
+ severity: string;
+ enabled: boolean;
+ confidence: number;
+ fpRate: number;
+ primaryTactic: string | null;
+}
+
+export interface ConfidenceSummary {
+ totalRules: number;
+ activeRules: number;
+ avgConfidence: number;
+ avgConfidenceActive: number;
+ medianConfidence: number;
+ /** Rules below the drift low-confidence threshold (server side: 60). */
+ lowConfidence: number;
+}
+
+export interface DetectionConfidence {
+ summary: ConfidenceSummary;
+ buckets: ConfidenceBucket[];
+ tactics: TacticConfidence[];
+ lowest: ConfidenceRuleEntry[];
+ highest: ConfidenceRuleEntry[];
+ generatedAt: string;
+}
+
export const detectionApi = {
list: () =>
request<{ rules: DetectionRule[]; total: number }>(
@@ -2184,6 +2233,14 @@ export const detectionApi = {
drift: () => request<DetectionDrift>('/api/v1/detection/drift'),
+ /**
+ * Confidence distribution + per-tactic averages + worst/best rules.
+ * The plan calls this "confidence trends"; we surface it as a
+ * snapshot histogram + ranked tables since rule confidence isn't
+ * captured historically yet.
+ */
+ confidence: () => request<DetectionConfidence>('/api/v1/detection/confidence'),
+
/**
* Enable or disable many rules in one round-trip. Built-in /
* cross-tenant rules are silently skipped server-side and reported in
diff --git a/services/api/app/api/v1/endpoints/detection_compat.py b/services/api/app/api/v1/endpoints/detection_compat.py
index 054f71da5..29c36b97e 100644
--- a/services/api/app/api/v1/endpoints/detection_compat.py
+++ b/services/api/app/api/v1/endpoints/detection_compat.py
@@ -479,6 +479,67 @@ class DriftResponse(BaseModel):
generatedAt: str
+class ConfidenceBucket(BaseModel):
+ """One column in the confidence histogram.
+
+ ``label`` is the human-friendly bucket label rendered on the x-axis
+ ("0–25", "26–50", …). ``floor`` / ``ceil`` are inclusive bounds so the
+ UI can highlight the bucket a particular rule falls into without
+ re-parsing the label.
+ """
+
+ label: str
+ floor: int
+ ceil: int
+ count: int
+ activeCount: int
+
+
+class TacticConfidence(BaseModel):
+ """Average rule confidence within one MITRE tactic.
+
+ Useful for the "where is my coverage weakest?" question — analysts
+ plot tactics as bars and immediately see that, e.g. *exfiltration*
+ averages 38/100 while *execution* averages 78/100.
+ """
+
+ tactic: str
+ rules: int
+ activeRules: int
+ avgConfidence: float
+ avgConfidenceActive: float
+
+
+class ConfidenceRuleEntry(BaseModel):
+ """A rule highlighted in the worst/best lists."""
+
+ ruleId: str
+ name: str
+ severity: str
+ enabled: bool
+ confidence: int
+ fpRate: float
+ primaryTactic: str | None = None
+
+
+class ConfidenceSummary(BaseModel):
+ totalRules: int
+ activeRules: int
+ avgConfidence: float
+ avgConfidenceActive: float
+ medianConfidence: int
+ lowConfidence: int # rules below ``DRIFT_LOW_CONFIDENCE_THRESHOLD``
+
+
+class ConfidenceResponse(BaseModel):
+ summary: ConfidenceSummary
+ buckets: list[ConfidenceBucket]
+ tactics: list[TacticConfidence]
+ lowest: list[ConfidenceRuleEntry]
+ highest: list[ConfidenceRuleEntry]
+ generatedAt: str
+
+
# ─── WS-B3 pure helpers (unit-testable, no DB) ───────────────────────────────
@@ -671,6 +732,167 @@ def _build_drift(
)
+# Confidence histogram is fixed at 4 buckets (0-25 / 26-50 / 51-75 / 76-100)
+# so a tuning analyst can compare libraries across tenants without having to
+# pick a binning scheme. Tweak with care: the frontend assumes 4 buckets when
+# rendering the histogram component.
+_CONFIDENCE_BUCKETS: tuple[tuple[str, int, int], ...] = (
+ ("0–25", 0, 25),
+ ("26–50", 26, 50),
+ ("51–75", 51, 75),
+ ("76–100", 76, 100),
+)
+
+
+def _build_confidence(
+ rules: list[DetectionRule],
+ *,
+ now: datetime | None = None,
+ top_n: int = 5,
+ low_confidence_threshold: int = DRIFT_LOW_CONFIDENCE_THRESHOLD,
+) -> ConfidenceResponse:
+ """Compute the rule confidence distribution for the WS-B3 trends panel.
+
+ The plan asks for *trends* but the schema doesn't snapshot confidence
+ over time, so we surface the most useful trend-like cuts instead:
+
+ * histogram across 4 fixed confidence buckets,
+ * average confidence overall and per tactic — "where is my library
+ weakest?" is the question analysts actually ask,
+ * top-``top_n`` rules at each end so they have something concrete to
+ tune (or trust) right now.
+
+ All math is plain Python so it stays unit-testable without a database.
+ """
+
+ now = now or datetime.now(UTC)
+
+ total = len(rules)
+ if total == 0:
+ empty_buckets = [
+ ConfidenceBucket(label=lbl, floor=lo, ceil=hi, count=0, activeCount=0)
+ for lbl, lo, hi in _CONFIDENCE_BUCKETS
+ ]
+ return ConfidenceResponse(
+ summary=ConfidenceSummary(
+ totalRules=0,
+ activeRules=0,
+ avgConfidence=0.0,
+ avgConfidenceActive=0.0,
+ medianConfidence=0,
+ lowConfidence=0,
+ ),
+ buckets=empty_buckets,
+ tactics=[],
+ lowest=[],
+ highest=[],
+ generatedAt=now.isoformat(),
+ )
+
+ confidences = [int(r.confidence or 0) for r in rules]
+ active_rules = [r for r in rules if r.status == "active"]
+ active_confidences = [int(r.confidence or 0) for r in active_rules]
+
+ avg_conf = sum(confidences) / total
+ avg_active = (
+ sum(active_confidences) / len(active_confidences) if active_confidences else 0.0
+ )
+
+ sorted_conf = sorted(confidences)
+ mid = len(sorted_conf) // 2
+ if len(sorted_conf) % 2:
+ median = sorted_conf[mid]
+ else:
+ median = (sorted_conf[mid - 1] + sorted_conf[mid]) // 2
+
+ low_count = sum(1 for c in confidences if c < low_confidence_threshold)
+
+ # Histogram buckets.
+ buckets: list[ConfidenceBucket] = []
+ for label, floor, ceil in _CONFIDENCE_BUCKETS:
+ count = sum(1 for c in confidences if floor <= c <= ceil)
+ active = sum(
+ 1
+ for r in rules
+ if r.status == "active" and floor <= int(r.confidence or 0) <= ceil
+ )
+ buckets.append(
+ ConfidenceBucket(
+ label=label,
+ floor=floor,
+ ceil=ceil,
+ count=count,
+ activeCount=active,
+ )
+ )
+
+ # Per-tactic average confidence.
+ by_tactic: dict[str, dict[str, Any]] = defaultdict(
+ lambda: {"sum": 0, "count": 0, "active_sum": 0, "active_count": 0}
+ )
+ for rule, conf in zip(rules, confidences):
+ tactic = _primary_tactic(rule)
+ if not tactic:
+ continue
+ bucket = by_tactic[tactic]
+ bucket["sum"] = int(bucket["sum"]) + conf
+ bucket["count"] = int(bucket["count"]) + 1
+ if rule.status == "active":
+ bucket["active_sum"] = int(bucket["active_sum"]) + conf
+ bucket["active_count"] = int(bucket["active_count"]) + 1
+
+ tactics: list[TacticConfidence] = []
+ for tactic, agg in by_tactic.items():
+ rules_in = int(agg["count"])
+ active_in = int(agg["active_count"])
+ avg = (int(agg["sum"]) / rules_in) if rules_in else 0.0
+ avg_active_t = (int(agg["active_sum"]) / active_in) if active_in else 0.0
+ tactics.append(
+ TacticConfidence(
+ tactic=tactic,
+ rules=rules_in,
+ activeRules=active_in,
+ avgConfidence=round(avg, 2),
+ avgConfidenceActive=round(avg_active_t, 2),
+ )
+ )
+ # Worst-first so the UI doesn't have to re-sort.
+ tactics.sort(key=lambda t: (t.avgConfidence, t.tactic))
+
+ def _entry(rule: DetectionRule) -> ConfidenceRuleEntry:
+ return ConfidenceRuleEntry(
+ ruleId=str(rule.id),
+ name=rule.name,
+ severity=rule.severity or "medium",
+ enabled=rule.status == "active",
+ confidence=int(rule.confidence or 0),
+ fpRate=float(rule.fp_rate or 0.0),
+ primaryTactic=_primary_tactic(rule),
+ )
+
+ # Lowest / highest confidence rules. Stable secondary sort by name so
+ # consecutive responses don't flip order on rules with identical scores.
+ sorted_rules = sorted(rules, key=lambda r: (int(r.confidence or 0), r.name))
+ lowest = [_entry(r) for r in sorted_rules[:top_n]]
+ highest = [_entry(r) for r in list(reversed(sorted_rules))[:top_n]]
+
+ return ConfidenceResponse(
+ summary=ConfidenceSummary(
+ totalRules=total,
+ activeRules=len(active_rules),
+ avgConfidence=round(avg_conf, 2),
+ avgConfidenceActive=round(avg_active, 2),
+ medianConfidence=int(median),
+ lowConfidence=low_count,
+ ),
+ buckets=buckets,
+ tactics=tactics,
+ lowest=lowest,
+ highest=highest,
+ generatedAt=now.isoformat(),
+ )
+
+
def _coerce_uuid(raw: str) -> uuid.UUID | None:
"""Best-effort cast of a frontend rule ID to ``uuid.UUID``.
@@ -788,3 +1010,30 @@ async def get_detection_drift(
)
rules = (await db.execute(stmt)).scalars().all()
return _build_drift(list(rules))
+
+
[email protected]("/confidence", response_model=ConfidenceResponse)
+async def get_detection_confidence(
+ current_user: Annotated[AuthUser, Depends(require_permission("rules:read"))],
+ db: DBSession,
+) -> ConfidenceResponse:
+ """Rule-confidence trend panel for the WS-B3 Detections UI.
+
+ Returns a 4-bucket histogram of rule confidence, the per-tactic
+ average, and the top/bottom rules so analysts can see at a glance
+ where the rule library is brittle and which tactics need the most
+ tuning love.
+
+ No history table is needed — this view derives its trend signal from
+ the current confidence/FP-rate columns set by the rule engine and
+ operator review on every match.
+ """
+ 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_confidence(list(rules))
diff --git a/services/api/tests/api/__init__.py b/services/api/tests/api/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/services/api/tests/api/v1/__init__.py b/services/api/tests/api/v1/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/services/api/tests/api/v1/endpoints/__init__.py b/services/api/tests/api/v1/endpoints/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/services/api/tests/api/v1/endpoints/test_detection_compat_helpers.py b/services/api/tests/api/v1/endpoints/test_detection_compat_helpers.py
new file mode 100644
index 000000000..8d3f90e3c
--- /dev/null
+++ b/services/api/tests/api/v1/endpoints/test_detection_compat_helpers.py
@@ -0,0 +1,356 @@
+"""Pure-function tests for the WS-B3 detection-compat helpers.
+
+The Detections UI relies on three helper functions:
+
+* :func:`detection_compat._build_coverage` – MITRE coverage heatmap
+* :func:`detection_compat._build_drift` – drift inbox
+* :func:`detection_compat._build_confidence` – confidence trends panel
+
+All three are intentionally pure — they take a list of in-memory
+``DetectionRule`` instances and return a Pydantic response model — so we
+can lock in the contract without spinning up a DB. These tests are the
+behavioural backstop for the API → frontend bridge.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from app.api.v1.endpoints.detection_compat import (
+ DRIFT_FP_RATE_THRESHOLD,
+ DRIFT_LOW_CONFIDENCE_THRESHOLD,
+ DRIFT_STALE_DAYS,
+ _build_confidence,
+ _build_coverage,
+ _build_drift,
+)
+from app.models.detection_rule import DetectionRule
+
+
+def _make_rule(
+ *,
+ name: str = "Rule",
+ status: str = "active",
+ confidence: int = 50,
+ fp_rate: float = 0.0,
+ severity: str = "medium",
+ tactics: list[str] | None = None,
+ techniques: list[str] | None = None,
+ last_triggered: datetime | None = None,
+ rule_id: uuid.UUID | None = None,
+) -> DetectionRule:
+ """Build an in-memory ``DetectionRule`` with sensible defaults.
+
+ We construct via the SQLAlchemy mapped class but never persist — these
+ helpers operate on plain Python objects, so attribute access is enough.
+ """
+ rule = DetectionRule(
+ id=rule_id or uuid.uuid4(),
+ tenant_id=uuid.uuid4(),
+ name=name,
+ rule_language="sigma",
+ rule_body="title: x",
+ category="custom",
+ status=status,
+ severity=severity,
+ confidence=confidence,
+ mitre_tactics=tactics or [],
+ mitre_techniques=techniques or [],
+ fp_rate=fp_rate,
+ suppression_config={},
+ threshold_config={},
+ total_hits=0,
+ last_triggered=last_triggered,
+ tags=[],
+ is_builtin=False,
+ version=1,
+ provenance={},
+ )
+ return rule
+
+
+# ─── _build_confidence ──────────────────────────────────────────────────────
+
+
+def test_confidence_empty_library_returns_zero_summary_and_empty_buckets() -> None:
+ """An empty rule library still returns 4 zero-filled histogram buckets.
+
+ The frontend assumes a fixed four-bucket layout, so we always return
+ that shape — even when there's nothing to plot — to avoid an empty
+ array conditional in the UI.
+ """
+ resp = _build_confidence([])
+
+ assert resp.summary.totalRules == 0
+ assert resp.summary.activeRules == 0
+ assert resp.summary.avgConfidence == 0.0
+ assert resp.summary.medianConfidence == 0
+ assert resp.summary.lowConfidence == 0
+ assert [b.label for b in resp.buckets] == ["0–25", "26–50", "51–75", "76–100"]
+ assert all(b.count == 0 and b.activeCount == 0 for b in resp.buckets)
+ assert resp.tactics == []
+ assert resp.lowest == []
+ assert resp.highest == []
+
+
+def test_confidence_buckets_assign_rules_to_correct_band() -> None:
+ """Rules must land in inclusive [floor, ceil] buckets."""
+ rules = [
+ _make_rule(name="floor", confidence=0),
+ _make_rule(name="band1-mid", confidence=20),
+ _make_rule(name="band1-edge", confidence=25),
+ _make_rule(name="band2-edge", confidence=26),
+ _make_rule(name="band3", confidence=70),
+ _make_rule(name="band4", confidence=100),
+ ]
+ resp = _build_confidence(rules)
+
+ by_label = {b.label: b for b in resp.buckets}
+ assert by_label["0–25"].count == 3 # 0, 20, 25
+ assert by_label["26–50"].count == 1 # 26
+ assert by_label["51–75"].count == 1 # 70
+ assert by_label["76–100"].count == 1 # 100
+
+
+def test_confidence_active_count_only_includes_active_rules() -> None:
+ """Disabled rules count toward ``count`` but not ``activeCount``.
+
+ This drives the "tall but pale" histogram bars in the UI, which signal
+ "lots of rules in this band but most are disabled — clean them up".
+ """
+ rules = [
+ _make_rule(name="enabled-low", status="active", confidence=10),
+ _make_rule(name="disabled-low", status="testing", confidence=10),
+ _make_rule(name="disabled-low2", status="archived", confidence=10),
+ ]
+ resp = _build_confidence(rules)
+
+ low_band = next(b for b in resp.buckets if b.label == "0–25")
+ assert low_band.count == 3
+ assert low_band.activeCount == 1
+
+
+def test_confidence_summary_averages_match_reference_math() -> None:
+ """Average confidences are population means rounded to 2dp."""
+ rules = [
+ _make_rule(name="a", status="active", confidence=80),
+ _make_rule(name="b", status="active", confidence=60),
+ _make_rule(name="c", status="testing", confidence=20),
+ ]
+ resp = _build_confidence(rules)
+
+ # Overall mean = (80 + 60 + 20) / 3 = 53.3333… → 53.33
+ assert resp.summary.avgConfidence == 53.33
+ # Active mean = (80 + 60) / 2 = 70.0
+ assert resp.summary.avgConfidenceActive == 70.0
+
+
+def test_confidence_median_uses_lower_midpoint_for_even_n() -> None:
+ """Even-length lists use ``(lower + upper) // 2`` so result stays int."""
+ rules = [
+ _make_rule(confidence=10),
+ _make_rule(confidence=20),
+ _make_rule(confidence=40),
+ _make_rule(confidence=80),
+ ]
+ resp = _build_confidence(rules)
+ # sorted = [10, 20, 40, 80] → (20 + 40) // 2 = 30
+ assert resp.summary.medianConfidence == 30
+
+
+def test_confidence_low_count_uses_drift_threshold() -> None:
+ """``lowConfidence`` mirrors the drift heuristic for the same threshold.
+
+ Keeping the cutoff in lockstep with the drift inbox means the UI's
+ "below trust gate" badge and the drift "low confidence" chip refer to
+ the same set of rules — analysts shouldn't have to translate.
+ """
+ rules = [
+ _make_rule(confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD - 1), # under
+ _make_rule(confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD), # at threshold = OK
+ _make_rule(confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD + 10), # over
+ ]
+ resp = _build_confidence(rules)
+ assert resp.summary.lowConfidence == 1
+
+
+def test_confidence_per_tactic_drops_unmapped_rules() -> None:
+ """Rules without a primary tactic don't pollute the per-tactic chart."""
+ rules = [
+ _make_rule(name="exec1", confidence=80, tactics=["execution"]),
+ _make_rule(name="exec2", confidence=40, tactics=["execution"]),
+ _make_rule(name="unmapped", confidence=10, tactics=[]),
+ ]
+ resp = _build_confidence(rules)
+
+ assert [t.tactic for t in resp.tactics] == ["execution"]
+ assert resp.tactics[0].rules == 2
+ assert resp.tactics[0].avgConfidence == 60.0
+
+
+def test_confidence_per_tactic_sorted_worst_first_then_alpha() -> None:
+ """Tactics sort by avg ASC so the UI doesn't have to re-sort."""
+ rules = [
+ _make_rule(name="exec", confidence=90, tactics=["execution"]),
+ _make_rule(name="exfil", confidence=20, tactics=["exfiltration"]),
+ _make_rule(name="cred", confidence=20, tactics=["credential-access"]),
+ ]
+ resp = _build_confidence(rules)
+ # 20 < 90, ties broken alphabetically
+ assert [t.tactic for t in resp.tactics] == [
+ "credential-access",
+ "exfiltration",
+ "execution",
+ ]
+
+
+def test_confidence_lowest_and_highest_lists_are_capped_and_ordered() -> None:
+ """Worst rules listed asc, best listed desc, both capped at top_n."""
+ rules = [_make_rule(name=f"rule-{c:03d}", confidence=c) for c in range(0, 100, 10)]
+ resp = _build_confidence(rules, top_n=3)
+
+ assert [e.confidence for e in resp.lowest] == [0, 10, 20]
+ assert [e.confidence for e in resp.highest] == [90, 80, 70]
+
+
+def test_confidence_lowest_uses_stable_secondary_sort_by_name() -> None:
+ """Identical scores must be ordered deterministically by name.
+
+ Without this, two consecutive ``GET /confidence`` calls could reorder
+ rules with the same confidence, causing the worst-offenders list to
+ flicker in the UI.
+ """
+ rules = [
+ _make_rule(name="zeta", confidence=10),
+ _make_rule(name="alpha", confidence=10),
+ _make_rule(name="mu", confidence=10),
+ ]
+ resp = _build_confidence(rules, top_n=3)
+
+ assert [e.name for e in resp.lowest] == ["alpha", "mu", "zeta"]
+
+
+def test_confidence_handles_none_confidence_as_zero() -> None:
+ """``rule.confidence`` is non-null in the schema, but defensive.
+
+ The model has a default of 50, but ORM round-trips can return None
+ in edge cases (e.g. fresh objects before flush). The helper coerces
+ to 0 so the histogram math doesn't blow up.
+ """
+ r = _make_rule(name="null-conf")
+ r.confidence = None # type: ignore[assignment]
+ resp = _build_confidence([r])
+
+ assert resp.summary.avgConfidence == 0.0
+ assert resp.summary.medianConfidence == 0
+ assert resp.buckets[0].count == 1 # 0 falls in the 0–25 band
+
+
+# ─── _build_drift ───────────────────────────────────────────────────────────
+
+
+def test_drift_clean_library_returns_empty_inbox() -> None:
+ """A library with no FP / confidence / staleness issues is empty."""
+ fresh = datetime.now(UTC) - timedelta(days=1)
+ rules = [
+ _make_rule(
+ name="healthy",
+ status="active",
+ confidence=80,
+ fp_rate=0.05,
+ last_triggered=fresh,
+ ),
+ ]
+ resp = _build_drift(rules)
+
+ assert resp.entries == []
+ assert resp.summary.total == 0
+
+
+def test_drift_active_rule_with_no_triggers_marked_stale() -> None:
+ """Active rules without any trigger history are stale by definition."""
+ rules = [
+ _make_rule(name="silent-active", status="active", confidence=80, fp_rate=0.01),
+ ]
+ resp = _build_drift(rules)
+
+ assert resp.summary.stale == 1
+ assert resp.entries[0].issues == ["stale"]
+ assert resp.entries[0].daysSinceTriggered is None
+
+
+def test_drift_disabled_rule_is_not_stale_but_other_issues_still_flag() -> None:
+ """Disabled rules aren't expected to fire, so absence of triggers != drift.
+
+ But a disabled rule with bad FP / confidence is still surfaced so an
+ analyst can clean it up rather than leave dead weight in the library.
+ """
+ rules = [
+ _make_rule(
+ name="disabled-noisy",
+ status="testing",
+ confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD - 5,
+ fp_rate=DRIFT_FP_RATE_THRESHOLD + 0.1,
+ last_triggered=None,
+ ),
+ ]
+ resp = _build_drift(rules)
+
+ assert resp.summary.stale == 0
+ assert resp.summary.lowConfidence == 1
+ assert resp.summary.highFpRate == 1
+ assert set(resp.entries[0].issues) == {"high_fp_rate", "low_confidence"}
+
+
+def test_drift_orders_worst_offenders_first() -> None:
+ """Sort priority is issues desc → severity desc → fp_rate desc → name asc."""
+ fresh = datetime.now(UTC) - timedelta(days=1)
+ rules = [
+ # 1 issue, low severity
+ _make_rule(
+ name="a-low-issue",
+ status="active",
+ confidence=10,
+ fp_rate=0.05,
+ severity="low",
+ last_triggered=fresh,
+ ),
+ # 3 issues, critical severity
+ _make_rule(
+ name="b-many-issues",
+ status="active",
+ confidence=10,
+ fp_rate=DRIFT_FP_RATE_THRESHOLD + 0.5,
+ severity="critical",
+ last_triggered=datetime.now(UTC) - timedelta(days=DRIFT_STALE_DAYS + 5),
+ ),
+ ]
+ resp = _build_drift(rules)
+
+ assert resp.entries[0].name == "b-many-issues"
+ assert resp.entries[1].name == "a-low-issue"
+
+
+# ─── _build_coverage ────────────────────────────────────────────────────────
+
+
+def test_coverage_counts_rules_with_and_without_techniques() -> None:
+ """Unmapped rules count in totals but not in technique cells."""
+ rules = [
+ _make_rule(
+ name="mapped",
+ status="active",
+ tactics=["execution"],
+ techniques=["T1059"],
+ ),
+ _make_rule(name="unmapped", status="active", tactics=[], techniques=[]),
+ ]
+ resp = _build_coverage(rules)
+
+ assert resp.summary.totalRules == 2
+ assert resp.summary.activeRules == 2
+ # Coverage is technique-keyed, so unmapped rules don't appear in cells.
+ technique_ids = {cell.techniqueId for cell in resp.cells}
+ assert technique_ids == {"T1059"}
diff --git a/services/api/tests/test_detection_management.py b/services/api/tests/test_detection_management.py
index 97347315b..1b2ce06d0 100644
--- a/services/api/tests/test_detection_management.py
+++ b/services/api/tests/test_detection_management.py
@@ -24,6 +24,7 @@ from app.api.v1.endpoints.detection_compat import (
DRIFT_FP_RATE_THRESHOLD,
DRIFT_LOW_CONFIDENCE_THRESHOLD,
DRIFT_STALE_DAYS,
+ _build_confidence,
_build_coverage,
_build_drift,
_coerce_uuid,
@@ -375,6 +376,182 @@ class TestCoerceUuid:
assert _coerce_uuid(None) is None # type: ignore[arg-type]
+# ---------------------------------------------------------------------------
+# _build_confidence (WS-B3.1 — confidence trends panel)
+# ---------------------------------------------------------------------------
+
+
+class TestBuildConfidence:
+ """Histogram + per-tactic averages + worst/best leaderboards.
+
+ The confidence panel is the analyst's "what's brittle in my library?"
+ view — it has to be deterministic across calls so the UI doesn't
+ flicker when nothing changed, and it has to handle edge cases
+ (empty library, all-active, no MITRE coverage) without raising.
+ """
+
+ NOW = datetime(2026, 5, 9, tzinfo=UTC)
+
+ def test_empty_library_returns_zeroed_buckets(self):
+ # Empty library should still emit all 4 buckets so the UI doesn't
+ # have to special-case "no data" — it just renders zeros.
+ out = _build_confidence([], now=self.NOW)
+ assert out.summary.totalRules == 0
+ assert out.summary.activeRules == 0
+ assert out.summary.avgConfidence == 0.0
+ assert out.summary.medianConfidence == 0
+ assert out.summary.lowConfidence == 0
+ assert len(out.buckets) == 4
+ assert [b.label for b in out.buckets] == ["0–25", "26–50", "51–75", "76–100"]
+ assert all(b.count == 0 and b.activeCount == 0 for b in out.buckets)
+ assert out.tactics == []
+ assert out.lowest == []
+ assert out.highest == []
+
+ def test_histogram_bins_inclusively(self):
+ # Bucket bounds are inclusive on both sides — 25 lands in 0–25,
+ # 26 lands in 26–50. This test pins that contract.
+ rules = [
+ FakeRule(name="r0", confidence=0),
+ FakeRule(name="r25", confidence=25),
+ FakeRule(name="r26", confidence=26),
+ FakeRule(name="r50", confidence=50),
+ FakeRule(name="r51", confidence=51),
+ FakeRule(name="r75", confidence=75),
+ FakeRule(name="r76", confidence=76),
+ FakeRule(name="r100", confidence=100),
+ ]
+ out = _build_confidence(rules, now=self.NOW)
+ counts = {b.label: b.count for b in out.buckets}
+ assert counts == {"0–25": 2, "26–50": 2, "51–75": 2, "76–100": 2}
+
+ def test_active_only_count_is_separate(self):
+ # The histogram tracks both total and active counts so the UI can
+ # render a "active vs disabled" stacked bar without a second call.
+ rules = [
+ FakeRule(name="active_low", confidence=10, status="active"),
+ FakeRule(name="disabled_low", confidence=10, status="inactive"),
+ FakeRule(name="active_high", confidence=90, status="active"),
+ ]
+ out = _build_confidence(rules, now=self.NOW)
+ low_bucket = next(b for b in out.buckets if b.label == "0–25")
+ high_bucket = next(b for b in out.buckets if b.label == "76–100")
+ assert low_bucket.count == 2
+ assert low_bucket.activeCount == 1
+ assert high_bucket.count == 1
+ assert high_bucket.activeCount == 1
+
+ def test_summary_avg_and_median(self):
+ rules = [
+ FakeRule(confidence=20),
+ FakeRule(confidence=40),
+ FakeRule(confidence=60),
+ FakeRule(confidence=80),
+ ]
+ out = _build_confidence(rules, now=self.NOW)
+ # avg = 50, median (even count) = (40+60)//2 = 50
+ assert out.summary.avgConfidence == pytest.approx(50.0)
+ assert out.summary.medianConfidence == 50
+
+ def test_median_with_odd_count(self):
+ rules = [FakeRule(confidence=c) for c in (10, 30, 50, 70, 90)]
+ out = _build_confidence(rules, now=self.NOW)
+ assert out.summary.medianConfidence == 50
+
+ def test_low_confidence_count_uses_drift_threshold(self):
+ # ``lowConfidence`` is gated on ``DRIFT_LOW_CONFIDENCE_THRESHOLD``
+ # so the confidence panel and the drift inbox agree on what "low"
+ # means. If the threshold ever changes, both views move together.
+ rules = [
+ FakeRule(confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD - 1),
+ FakeRule(confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD),
+ FakeRule(confidence=DRIFT_LOW_CONFIDENCE_THRESHOLD + 1),
+ ]
+ out = _build_confidence(rules, now=self.NOW)
+ # Strictly below the threshold counts as low; at-or-above does not.
+ assert out.summary.lowConfidence == 1
+
+ def test_active_avg_excludes_disabled(self):
+ # Average across all rules vs. active-only should diverge once a
+ # disabled rule pulls the overall average down.
+ rules = [
+ FakeRule(confidence=100, status="active"),
+ FakeRule(confidence=100, status="active"),
+ FakeRule(confidence=0, status="inactive"),
+ ]
+ out = _build_confidence(rules, now=self.NOW)
+ assert out.summary.avgConfidence == pytest.approx(200 / 3, abs=0.01)
+ assert out.summary.avgConfidenceActive == pytest.approx(100.0)
+
+ def test_per_tactic_averages_sorted_worst_first(self):
+ # Multiple tactics → worst-average first so the UI can render the
+ # chart without re-sorting on the client.
+ rules = [
+ FakeRule(confidence=20, mitre_tactics=["exfiltration"]),
+ FakeRule(confidence=30, mitre_tactics=["exfiltration"]),
+ FakeRule(confidence=80, mitre_tactics=["execution"]),
+ FakeRule(confidence=90, mitre_tactics=["execution"]),
+ ]
+ out = _build_confidence(rules, now=self.NOW)
+ assert [t.tactic for t in out.tactics] == ["exfiltration", "execution"]
+ ex = next(t for t in out.tactics if t.tactic == "exfiltration")
+ assert ex.rules == 2
+ assert ex.avgConfidence == pytest.approx(25.0)
+
+ def test_rules_without_tactic_skipped_in_per_tactic(self):
+ # A rule with no MITRE tactic still contributes to the histogram
+ # and summary, but shouldn't show up in the per-tactic view —
+ # we'd be inventing a "no-tactic" pseudo-tactic otherwise.
+ rules = [
+ FakeRule(confidence=10, mitre_tactics=[]),
+ FakeRule(confidence=90, mitre_tactics=["execution"]),
+ ]
+ out = _build_confidence(rules, now=self.NOW)
+ assert out.summary.totalRules == 2
+ assert [t.tactic for t in out.tactics] == ["execution"]
+
+ def test_lowest_and_highest_leaderboards(self):
+ # ``lowest`` / ``highest`` are top-N by confidence, ascending /
+ # descending. We use top_n=2 here so the assertion is tight.
+ rules = [
+ FakeRule(name="a", confidence=10),
+ FakeRule(name="b", confidence=20),
+ FakeRule(name="c", confidence=80),
+ FakeRule(name="d", confidence=95),
+ ]
+ out = _build_confidence(rules, now=self.NOW, top_n=2)
+ assert [e.name for e in out.lowest] == ["a", "b"]
+ assert [e.name for e in out.highest] == ["d", "c"]
+
+ def test_lowest_stable_secondary_sort(self):
+ # Tied confidence → stable, alphabetical secondary sort so the
+ # leaderboard doesn't flicker between calls.
+ rules = [
+ FakeRule(name="zebra", confidence=10),
+ FakeRule(name="apple", confidence=10),
+ FakeRule(name="mango", confidence=10),
+ ]
+ out = _build_confidence(rules, now=self.NOW, top_n=3)
+ assert [e.name for e in out.lowest] == ["apple", "mango", "zebra"]
+
+ def test_top_n_clamped_to_library_size(self):
+ # A small library shouldn't crash when top_n is larger than the
+ # number of rules — we just return everything.
+ rules = [FakeRule(name="only", confidence=50)]
+ out = _build_confidence(rules, now=self.NOW, top_n=10)
+ assert len(out.lowest) == 1
+ assert len(out.highest) == 1
+
+ def test_none_confidence_treated_as_zero(self):
+ # ``confidence`` is non-null in the schema but the helper guards
+ # against ``None`` defensively (DB drivers can return ``None``
+ # for newly inserted rows before the default kicks in).
+ rule = FakeRule(name="r", confidence=None) # type: ignore[arg-type]
+ out = _build_confidence([rule], now=self.NOW)
+ assert out.summary.avgConfidence == 0.0
+ assert out.summary.lowConfidence == 1
+
+
# ---------------------------------------------------------------------------
# Threshold sanity (catches accidental regressions in product behavior)
# ---------------------------------------------------------------------------