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(severity): add critical tier and alert.confidence (PR-2)

Beenu Arorab750ff481a2b
diff --git a/AGENTS.md b/AGENTS.md
index 01244849a..5ced3fcdf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -29,7 +29,7 @@
- The API service (`services/api`) holds the encrypt/decrypt keypair authority; `services/connectors` ships a vendored read-path `decrypt_dict()` so the scheduler can decrypt at poll time without owning the write path.
- Polling runs in-process inside `services/connectors` via APScheduler (`ConnectorScheduler`). One job per enabled instance, 5-min default cadence, overridable per-instance via `connector_config.poll_interval_seconds`. The scheduler reloads jobs every 30s. Disable in tests with `AISOC_CONNECTORS_DISABLE_SCHEDULER=1`.
- Normalized events flow through `IngestClient` (`services/connectors/app/ingest_client.py`) to `services/ingest`'s `/v1/ingest/batch` endpoint with an `X-Tenant-ID` header.
- - Severity ladder is exactly four tiers: `info | low | medium | high`. Vendor-native ladders (Azure 5-tier, SCC 5-tier, GitHub 4-tier) collapse into this set in each connector's `normalize()` method.
+ - Severity ladder is exactly five tiers: `info | low | medium | high | critical` (v1.5+). Vendor-native ladders that publish a distinct `critical` (Azure 5-tier, GCP SCC 5-tier, GitHub `critical`, ServiceNow priority 1, AWS GuardDuty ≥8.0, AuditD identity-destruction events, K8s `cluster-admin` bindings, Tailscale tailnet lockdown failures) MUST map to `critical` in their `normalize()` and NOT be collapsed into `high`. Confidence (`alert.confidence`, int 0–100 with band `low | medium | high`) is independent of severity and is emitted by `services/fusion` `ConfidenceScorer`.
- Every connector ships a marketplace manifest at `plugins/<connector-id>/plugin.yaml` mirroring its `schema()`. Run `pnpm marketplace:sync` after adding one.
- Per-connector setup walkthroughs live under `apps/docs/docs/connectors/<connector-id>.md` and are indexed by `apps/docs/sidebars.ts` under the `Connectors` category. The vault threat model + rotation procedure live in `apps/docs/docs/operations/credentials.md`.
- v1.4 eval harness conventions:
diff --git a/apps/web/src/components/dashboard/DashboardView.tsx b/apps/web/src/components/dashboard/DashboardView.tsx
index 7511827fb..eec6f9b99 100644
--- a/apps/web/src/components/dashboard/DashboardView.tsx
+++ b/apps/web/src/components/dashboard/DashboardView.tsx
@@ -391,6 +391,7 @@ export function DashboardView() {
{ name: 'High', value: metrics.alerts.high, color: '#f97316' },
{ name: 'Medium', value: metrics.alerts.medium, color: '#eab308' },
{ name: 'Low', value: metrics.alerts.low, color: '#3b82f6' },
+ { name: 'Info', value: metrics.alerts.info ?? 0, color: '#64748b' },
];
// WS-F3: drag-and-drop widget reordering
diff --git a/apps/web/src/components/detections/ConfidenceTrends.tsx b/apps/web/src/components/detections/ConfidenceTrends.tsx
index e6756efa0..e791451cf 100644
--- a/apps/web/src/components/detections/ConfidenceTrends.tsx
+++ b/apps/web/src/components/detections/ConfidenceTrends.tsx
@@ -78,6 +78,7 @@ const SEVERITY_BADGE: Record<string, string> = {
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',
+ info: 'bg-slate-500/10 text-slate-300 ring-slate-500/40',
};
// ─── Component ───────────────────────────────────────────────────────────────
diff --git a/apps/web/src/components/detections/DetectionsView.tsx b/apps/web/src/components/detections/DetectionsView.tsx
index b0af39d2d..8a6450147 100644
--- a/apps/web/src/components/detections/DetectionsView.tsx
+++ b/apps/web/src/components/detections/DetectionsView.tsx
@@ -135,6 +135,7 @@ const SEVERITY_BADGE: Record<string, string> = {
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',
+ info: 'bg-slate-500/10 text-slate-300 ring-slate-500/40',
};
// ─── Tabs ────────────────────────────────────────────────────────────────────
diff --git a/apps/web/src/components/marketplace/MarketplaceView.tsx b/apps/web/src/components/marketplace/MarketplaceView.tsx
index dbb04a8fa..4ce6e9406 100644
--- a/apps/web/src/components/marketplace/MarketplaceView.tsx
+++ b/apps/web/src/components/marketplace/MarketplaceView.tsx
@@ -115,6 +115,7 @@ const SEVERITY_COLORS: Record<string, string> = {
high: 'bg-orange-900/40 text-orange-300 border-orange-700/60',
medium: 'bg-yellow-900/40 text-yellow-300 border-yellow-700/60',
low: 'bg-blue-900/40 text-blue-300 border-blue-700/60',
+ info: 'bg-slate-900/40 text-slate-300 border-slate-700/60',
};
const TYPE_COLORS: Record<string, string> = {
diff --git a/apps/web/src/components/sla/SLADashboard.tsx b/apps/web/src/components/sla/SLADashboard.tsx
index 5f117ad1e..63c3c970a 100644
--- a/apps/web/src/components/sla/SLADashboard.tsx
+++ b/apps/web/src/components/sla/SLADashboard.tsx
@@ -74,13 +74,14 @@ interface SLAConfig {
mttc_target: number;
}
-const SEVERITIES = ['critical', 'high', 'medium', 'low'] as const;
+const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'] as const;
const SEVERITY_COLORS: Record<string, string> = {
critical: 'text-red-400',
high: 'text-orange-400',
medium: 'text-yellow-400',
low: 'text-blue-400',
+ info: 'text-slate-400',
};
const SEVERITY_BG: Record<string, string> = {
@@ -88,6 +89,7 @@ const SEVERITY_BG: Record<string, string> = {
high: 'bg-orange-900/30 border-orange-700',
medium: 'bg-yellow-900/30 border-yellow-700',
low: 'bg-blue-900/30 border-blue-700',
+ info: 'bg-slate-900/30 border-slate-700',
};
function fmtMinutes(min: number | null): string {
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index ae853b737..e882a904b 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1178,6 +1178,7 @@ export interface DashboardMetrics {
high: number;
medium: number;
low: number;
+ info?: number;
resolvedToday: number;
mttr: number;
};
diff --git a/apps/web/src/lib/responder/format.test.ts b/apps/web/src/lib/responder/format.test.ts
new file mode 100644
index 000000000..f06f850e3
--- /dev/null
+++ b/apps/web/src/lib/responder/format.test.ts
@@ -0,0 +1,77 @@
+/**
+ * format — unit tests
+ * ===================
+ *
+ * The mobile responder UI leans on these formatters to keep severity, status
+ * and time strings consistent across the alert/case surface. They're pure
+ * functions, so we test them directly without a DOM.
+ *
+ * Coverage map:
+ * - severityTone: every tier in the v1.5 five-tier ladder
+ * (`critical | high | medium | low | info`) has a tone entry, ranks are
+ * strictly monotonic, fallback path returns `info` rather than throwing,
+ * and case-insensitive matching works (some upstreams emit `"Critical"`).
+ *
+ * If a refactor accidentally drops a tier — e.g. squashes `critical` back into
+ * `high` like the pre-v1.5 four-tier ladder — these tests catch it before the
+ * mobile UI starts rendering blanks for P1 incidents.
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import { severityTone } from './format';
+
+describe('severityTone', () => {
+ const tiers = ['critical', 'high', 'medium', 'low', 'info'] as const;
+
+ it.each(tiers)('returns a tone for %s', (tier) => {
+ const tone = severityTone(tier);
+ expect(tone.bg).toMatch(/^bg-/);
+ expect(tone.fg).toMatch(/^text-/);
+ expect(tone.border).toMatch(/^border-l-/);
+ expect(tone.glyph).toHaveLength(1);
+ expect(typeof tone.rank).toBe('number');
+ });
+
+ it('assigns strictly monotonic ranks across the five-tier ladder', () => {
+ const ranks = tiers.map((t) => severityTone(t).rank);
+ // critical = 4, high = 3, medium = 2, low = 1, info = 0 — so the list as
+ // ordered should be strictly descending.
+ expect(ranks).toEqual([4, 3, 2, 1, 0]);
+ });
+
+ it('falls back to the info tone for unknown severities', () => {
+ const info = severityTone('info');
+ const unknown = severityTone('not-a-real-severity');
+ expect(unknown).toEqual(info);
+ });
+
+ it('falls back to the info tone for nullish severities', () => {
+ const info = severityTone('info');
+ expect(severityTone(null)).toEqual(info);
+ expect(severityTone(undefined)).toEqual(info);
+ expect(severityTone('')).toEqual(info);
+ });
+
+ it('is case-insensitive (some upstreams emit Title-Case)', () => {
+ expect(severityTone('Critical')).toEqual(severityTone('critical'));
+ expect(severityTone('HIGH')).toEqual(severityTone('high'));
+ expect(severityTone('Medium')).toEqual(severityTone('medium'));
+ });
+
+ it('uses distinct background colors for each tier', () => {
+ // Catches a refactor where someone copy-pastes a row but forgets to
+ // update the color — easy to miss in code review.
+ const bgs = new Set(tiers.map((t) => severityTone(t).bg));
+ expect(bgs.size).toBe(tiers.length);
+ });
+
+ it('uses the red palette for critical (P1 wallboard contract)', () => {
+ // The wallboard relies on `red` being the unambiguous P1 signal. If a
+ // theme refactor recolors `critical` to e.g. magenta, this catches it.
+ const crit = severityTone('critical');
+ expect(crit.bg).toContain('red');
+ expect(crit.fg).toContain('red');
+ expect(crit.border).toContain('red');
+ });
+});
diff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.py
index 4021de004..3b7cb9d4c 100644
--- a/services/api/app/api/v1/endpoints/alerts.py
+++ b/services/api/app/api/v1/endpoints/alerts.py
@@ -30,6 +30,13 @@ class AlertResponse(BaseModel):
ai_score: float | None
ai_summary: str | None
ai_recommendations: list
+ # Fusion confidence (W3). `confidence` is an integer 0-100; the band is
+ # carried in `confidence_label` (high/medium/low) and the contributing
+ # factors in `confidence_rationale`. All three can be NULL for legacy
+ # alerts created before the fusion service emitted confidence.
+ confidence: int | None = None
+ confidence_label: str | None = None
+ confidence_rationale: list | None = None
disposition: str | None = None
affected_ips: list
affected_hosts: list
@@ -90,8 +97,17 @@ async def list_alerts(
category: str | None = Query(default=None),
assigned_to_me: bool = Query(default=False),
search: str | None = Query(default=None),
+ min_confidence: int | None = Query(default=None, ge=0, le=100),
+ confidence_label: str | None = Query(default=None),
) -> AlertListResponse:
- """List alerts for the current tenant with filtering and pagination."""
+ """List alerts for the current tenant with filtering and pagination.
+
+ `min_confidence` / `confidence_label` let the queue workbench (PR-5) and
+ /alerts page filter on the fusion-emitted confidence signal (W3). Alerts
+ that pre-date the confidence column will have NULL and therefore won't
+ match either filter — that's intentional; analysts who care about
+ confidence should only see alerts that actually carry the signal.
+ """
filters = [Alert.tenant_id == current_user.tenant_id]
if severity:
@@ -102,6 +118,17 @@ async def list_alerts(
filters.append(Alert.category == category)
if assigned_to_me:
filters.append(Alert.assigned_to_id == current_user.user_id)
+ if min_confidence is not None:
+ filters.append(Alert.confidence >= min_confidence)
+ if confidence_label is not None:
+ if confidence_label not in {"high", "medium", "low"}:
+ # NOTE: the local `status` query parameter shadows the
+ # `fastapi.status` module here, so use the literal 400.
+ raise HTTPException(
+ status_code=400,
+ detail="confidence_label must be one of: high, medium, low",
+ )
+ filters.append(Alert.confidence_label == confidence_label)
# Count
count_result = await db.execute(select(func.count()).select_from(Alert).where(and_(*filters)))
diff --git a/services/api/app/api/v1/endpoints/sla.py b/services/api/app/api/v1/endpoints/sla.py
index 697396fe8..609331a62 100644
--- a/services/api/app/api/v1/endpoints/sla.py
+++ b/services/api/app/api/v1/endpoints/sla.py
@@ -26,7 +26,10 @@ from app.services import sla as sla_service
router = APIRouter(prefix="/sla", tags=["sla"])
-VALID_SEVERITIES = {"critical", "high", "medium", "low"}
+# Five-tier severity ladder (matches `tenant_sla_config.severity` CHECK
+# constraint installed by migration 040 and the AGENTS.md project-wide
+# convention `info | low | medium | high | critical`).
+VALID_SEVERITIES = {"critical", "high", "medium", "low", "info"}
VALID_EVENT_TYPES = {"detected", "acknowledged", "resolved", "closed"}
diff --git a/services/api/app/models/alert.py b/services/api/app/models/alert.py
index d3bd582b6..3b82477d2 100644
--- a/services/api/app/models/alert.py
+++ b/services/api/app/models/alert.py
@@ -45,6 +45,16 @@ class Alert(Base):
ai_recommendations: Mapped[list] = mapped_column(JSONB, default=list)
false_positive_score: Mapped[float | None] = mapped_column(Float, nullable=True)
+ # Fusion confidence — populated by services/fusion at correlate-time.
+ # `confidence` is the canonical 0-100 integer the API surfaces (W3 in
+ # the v1.5 SOC Console Parity plan); `confidence_label` is the band
+ # ('high' | 'medium' | 'low') and `confidence_rationale` is the list
+ # of contributing factors so analysts can see why we believe what we
+ # believe.
+ confidence: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ confidence_label: Mapped[str | None] = mapped_column(String(16), nullable=True)
+ confidence_rationale: Mapped[list | None] = mapped_column(JSONB, nullable=True)
+
# Entities (denormalized for fast querying)
affected_ips: Mapped[list] = mapped_column(JSONB, default=list)
affected_hosts: Mapped[list] = mapped_column(JSONB, default=list)
diff --git a/services/api/app/models/sla.py b/services/api/app/models/sla.py
index 1e5c64f4b..18e30ae73 100644
--- a/services/api/app/models/sla.py
+++ b/services/api/app/models/sla.py
@@ -26,8 +26,13 @@ class TenantSLAConfig(Base):
__table_args__ = (
UniqueConstraint("tenant_id", "severity", name="uq_sla_config_tenant_severity"),
+ # Mirrors the constraint we install in migration 040. We keep the
+ # ORM-level name distinct from the live DB constraint name so this
+ # stays drop-in compatible with existing deployments that still have
+ # the original 4-tier `ck_sla_config_severity` constraint until
+ # migration 040 swaps it for `ck_tenant_sla_config_severity_v2`.
CheckConstraint(
- "severity IN ('critical','high','medium','low')",
+ "severity IN ('critical','high','medium','low','info')",
name="ck_sla_config_severity",
),
)
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index 61467e71c..0e470a090 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -46,7 +46,12 @@ _rng = random.Random(42)
# ─── Reference data ────────────────────────────────────────────────────────────
+# Case severities stay on the legacy 4-tier ladder — we don't open cases for
+# pure `info` noise, so leaving `info` off avoids polluting the queue. Alerts
+# use the full 5-tier ladder (`_ALERT_SEVERITIES` below) so the seed exercises
+# every band defined by the v1.5 SOC Console Parity plan (W2).
_SEVERITIES = ["critical", "high", "medium", "low"]
+_ALERT_SEVERITIES = ["critical", "high", "medium", "low", "info"]
_STATUSES = ["new", "triaged", "investigating", "resolved", "false_positive"]
_SOURCES = [
@@ -1243,8 +1248,206 @@ def _pick_techniques(k: int = 2) -> list[dict]:
return [{"tactic": t[1], "tactic_id": t[0], "technique": t[3], "technique_id": t[2]} for t in chosen]
+# ---------------------------------------------------------------------------
+# Confidence synthesis
+# ---------------------------------------------------------------------------
+#
+# In a real deployment, services/fusion runs ConfidenceScorer over every fused
+# alert and writes `confidence_score` (0.0-1.0), `confidence_label`, and
+# `confidence_rationale` to Kafka, which the API persists onto the Alert row.
+# The demo seeder never goes through that pipeline, so we mirror the exact
+# scoring contract here. The constants below MUST stay aligned with
+# services/fusion/app/services/confidence.py — if the real scorer rebalances
+# weights, this helper should follow.
+
+# Score → label thresholds (mirror services/fusion).
+_CONFIDENCE_HIGH_THRESHOLD = 0.70
+_CONFIDENCE_LOW_THRESHOLD = 0.40
+
+# Factor weights — keep summing to 1.0 if you tweak (mirror services/fusion).
+_WEIGHT_SEVERITY = 0.20
+_WEIGHT_ML_ANOMALY = 0.18
+_WEIGHT_ML_PRIORITY = 0.18
+_WEIGHT_MITRE = 0.14
+_WEIGHT_THREAT_INTEL = 0.16
+_WEIGHT_UPSTREAM = 0.08
+_WEIGHT_IOC_DENSITY = 0.06
+
+_SEVERITY_CONTRIBUTION = {
+ "critical": 1.0,
+ "high": 0.6,
+ "medium": 0.0,
+ "low": -0.5,
+ "info": -1.0,
+}
+
+
+def _confidence_label_from_score(score: float) -> str:
+ if score >= _CONFIDENCE_HIGH_THRESHOLD:
+ return "high"
+ if score < _CONFIDENCE_LOW_THRESHOLD:
+ return "low"
+ return "medium"
+
+
+def _synthesise_confidence(
+ *,
+ severity: str,
+ ai_score: float,
+ n_techniques: int,
+ n_iocs: int,
+ has_threat_intel: bool,
+) -> tuple[int, str, list[dict]]:
+ """Mirror services/fusion ConfidenceScorer for the demo seeder.
+
+ Returns ``(confidence_int_0_100, label, rationale_list)`` so the seeded
+ Alert rows look identical to what a live fusion service would write.
+ The rationale is a list of dicts in ConfidenceFactor shape (factor / label
+ / value / contribution / weight) sorted by impact, so the UI can render
+ "why we believe what we believe" without any code-path divergence.
+
+ Contribution model, factor weights, labels, and value strings are kept in
+ lock-step with ``services/fusion/app/services/confidence.py``. If that
+ scorer is rebalanced, update this helper alongside it.
+ """
+
+ def _ml(value: float) -> float:
+ # ML scores already live in [0, 1]; recentre on 0.5 → [-1, +1].
+ return max(-1.0, min(1.0, (value - 0.5) * 2.0))
+
+ rationale: list[dict] = []
+
+ # 1. Severity
+ sev_c = _SEVERITY_CONTRIBUTION.get(severity, 0.0)
+ rationale.append(
+ {
+ "factor": "severity",
+ "label": "Alert severity",
+ "value": severity,
+ "contribution": sev_c,
+ "weight": _WEIGHT_SEVERITY,
+ }
+ )
+
+ # 2. ML anomaly score (anomaly_score in fusion).
+ anomaly_c = _ml(ai_score)
+ rationale.append(
+ {
+ "factor": "ml_anomaly",
+ "label": "ML anomaly score",
+ "value": f"{ai_score:.2f}",
+ "contribution": anomaly_c,
+ "weight": _WEIGHT_ML_ANOMALY,
+ }
+ )
+
+ # 3. ML priority rank (priority_score in fusion). The seeder only has a
+ # single ``ai_score`` to draw from, so we jitter it slightly to mimic the
+ # second model the real scorer consults — the rank is typically close to,
+ # but not identical to, the anomaly score.
+ priority_proxy = max(0.0, min(1.0, ai_score + _rng.uniform(-0.1, 0.1)))
+ priority_c = _ml(priority_proxy)
+ rationale.append(
+ {
+ "factor": "ml_priority",
+ "label": "ML priority rank",
+ "value": f"{priority_proxy:.2f}",
+ "contribution": priority_c,
+ "weight": _WEIGHT_ML_PRIORITY,
+ }
+ )
+
+ # 4. MITRE coverage — bands match _mitre_contribution() in fusion.
+ if n_techniques == 0:
+ mitre_c = -0.4
+ elif n_techniques == 1:
+ mitre_c = 0.0
+ elif n_techniques == 2:
+ mitre_c = 0.4
+ else:
+ mitre_c = min(1.0, 0.4 + (n_techniques - 2) * 0.2)
+ mitre_value = "1 technique" if n_techniques == 1 else f"{n_techniques} techniques"
+ rationale.append(
+ {
+ "factor": "mitre_coverage",
+ "label": "MITRE technique coverage",
+ "value": mitre_value,
+ "contribution": mitre_c,
+ "weight": _WEIGHT_MITRE,
+ }
+ )
+
+ # 5. Threat-intel — fusion looks at MISP / OTX / TAXII / KEV / VirusTotal
+ # hits. The seeder doesn't run enrichments, so collapse to a binary signal
+ # but keep the contribution and value strings faithful to the single-hit
+ # path of ``_ti_contribution``.
+ if has_threat_intel:
+ ti_c = 0.6
+ ti_value = "MISP"
+ else:
+ ti_c = -0.3
+ ti_value = "no TI match"
+ rationale.append(
+ {
+ "factor": "threat_intel",
+ "label": "Threat-intel match",
+ "value": ti_value,
+ "contribution": ti_c,
+ "weight": _WEIGHT_THREAT_INTEL,
+ }
+ )
+
+ # 6. Upstream vendor risk score. Real fusion uses ``raw_alert.risk_score``;
+ # the seeder doesn't carry one, so we reuse ai_score as a faithful proxy
+ # (same family of [0..1] vendor risk signals).
+ upstream_c = _ml(ai_score)
+ rationale.append(
+ {
+ "factor": "upstream_risk",
+ "label": "Upstream vendor risk score",
+ "value": f"{ai_score:.2f}",
+ "contribution": upstream_c,
+ "weight": _WEIGHT_UPSTREAM,
+ }
+ )
+
+ # 7. IOC density — bands match _ioc_density_contribution() in fusion.
+ if n_iocs == 0:
+ ioc_c = -0.6
+ elif n_iocs <= 2:
+ ioc_c = 0.0
+ elif n_iocs <= 4:
+ ioc_c = 0.5
+ else:
+ ioc_c = 1.0
+ rationale.append(
+ {
+ "factor": "ioc_density",
+ "label": "IOC density",
+ "value": f"{n_iocs} populated fields",
+ "contribution": ioc_c,
+ "weight": _WEIGHT_IOC_DENSITY,
+ }
+ )
+
+ # Combine: score = 0.5 + Σ(w_i * c_i), clamped to [0, 1].
+ delta = sum(f["weight"] * f["contribution"] for f in rationale)
+ score = max(0.0, min(1.0, 0.5 + delta))
+ label = _confidence_label_from_score(score)
+
+ # Sort rationale by absolute impact so the UI shows top drivers first
+ # (matches fusion's ConfidenceScorer.score).
+ rationale.sort(key=lambda f: abs(f["contribution"] * f["weight"]), reverse=True)
+
+ return int(round(score * 100)), label, rationale
+
+
def _make_alert(tenant_id: uuid.UUID, when: datetime) -> Alert:
- severity = _rng.choices(_SEVERITIES, weights=[15, 30, 35, 20])[0]
+ # Sample severity across all five tiers so the demo exercises every
+ # band defined by v1.5 W2 (critical-severity work). Weights bias toward
+ # medium/high noise, with a long tail of info-grade telemetry that lets
+ # operators rehearse min_confidence and severity filtering in /alerts.
+ severity = _rng.choices(_ALERT_SEVERITIES, weights=[10, 25, 35, 20, 10])[0]
status = _rng.choices(_STATUSES, weights=[40, 20, 15, 20, 5])[0]
src_name, src_cat = _rng.choice(_SOURCES)
host = _rng.choice(_HOSTS)
@@ -1253,8 +1456,21 @@ def _make_alert(tenant_id: uuid.UUID, when: datetime) -> Alert:
title = _rng.choice(_TITLES).format(host=host, user=user, ip=ip)
techniques = _pick_techniques(_rng.randint(1, 3))
- priority = {"critical": 90, "high": 75, "medium": 50, "low": 25}[severity]
- priority += _rng.randint(-10, 10)
+ priority_floor = {"critical": 90, "high": 75, "medium": 50, "low": 25, "info": 10}[severity]
+ priority = priority_floor + _rng.randint(-10, 10)
+ ai_score = _rng.uniform(0.3, 0.99)
+
+ # IOC count: 1 IP + 1 host + 1 user = 3 by default. About 1-in-4 alerts
+ # also carry a threat-intel hit, which spikes confidence in the rationale.
+ has_threat_intel = _rng.random() < 0.25
+ n_iocs = 3
+ confidence_int, confidence_label, confidence_rationale = _synthesise_confidence(
+ severity=severity,
+ ai_score=ai_score,
+ n_techniques=len(techniques),
+ n_iocs=n_iocs,
+ has_threat_intel=has_threat_intel,
+ )
return Alert(
tenant_id=tenant_id,
@@ -1267,7 +1483,7 @@ def _make_alert(tenant_id: uuid.UUID, when: datetime) -> Alert:
mitre_tactics=[{"id": t["tactic_id"], "name": t["tactic"]} for t in techniques],
mitre_techniques=[{"id": t["technique_id"], "name": t["technique"]} for t in techniques],
connector_type=src_name.lower().replace(" ", "_"),
- ai_score=_rng.uniform(0.3, 0.99),
+ ai_score=ai_score,
ai_summary=(
f"AI assessed this as a {severity} severity event tied to "
f"{techniques[0]['technique']} ({techniques[0]['technique_id']}). "
@@ -1293,6 +1509,9 @@ def _make_alert(tenant_id: uuid.UUID, when: datetime) -> Alert:
first_seen=when,
last_seen=when,
resolved_at=when + timedelta(hours=4) if status == "resolved" else None,
+ confidence=confidence_int,
+ confidence_label=confidence_label,
+ confidence_rationale=confidence_rationale,
created_at=when,
updated_at=when,
)
@@ -1575,6 +1794,19 @@ def _make_realistic_alert(
extra=alert_spec.get("extra", {}),
)
+ ai_score = alert_spec.get("ai_score", 0.85)
+ # Hand-crafted realistic incidents always carry MITRE techniques and at
+ # least three IOCs (host + user + src_ip). They're modeled on real BOTS
+ # data and the threat-intel signal is typically present, so we always set
+ # has_threat_intel=True for these — that's what makes them showcase-grade.
+ confidence_int, confidence_label, confidence_rationale = _synthesise_confidence(
+ severity=severity,
+ ai_score=ai_score,
+ n_techniques=len(techniques),
+ n_iocs=3,
+ has_threat_intel=True,
+ )
+
return Alert(
tenant_id=tenant_id,
title=alert_spec["title"],
@@ -1586,7 +1818,7 @@ def _make_realistic_alert(
mitre_tactics=tactics,
mitre_techniques=techniques,
connector_type=alert_spec["source"].lower().replace(" ", "_"),
- ai_score=alert_spec.get("ai_score", 0.85),
+ ai_score=ai_score,
ai_summary=(
f"AI assessed this {severity} alert as part of incident "
f"{incident['key']} ({incident['title']}). "
@@ -1606,6 +1838,9 @@ def _make_realistic_alert(
first_seen=when,
last_seen=when,
resolved_at=when + timedelta(hours=2) if case_status in ("resolved", "closed") else None,
+ confidence=confidence_int,
+ confidence_label=confidence_label,
+ confidence_rationale=confidence_rationale,
created_at=when,
updated_at=when,
)
diff --git a/services/api/app/services/sla.py b/services/api/app/services/sla.py
index cbd0ccd20..b779d7c7f 100644
--- a/services/api/app/services/sla.py
+++ b/services/api/app/services/sla.py
@@ -29,6 +29,24 @@ DEFAULT_KPI_BAR_TARGETS: dict[str, float] = {
}
+# Default per-severity SLA targets (minutes). These mirror the seed values
+# in migrations 007 (critical/high/medium/low) and 040 (info) — `critical`
+# carries the v1.5 P1 ≤15 min MTTD promise (W2 in the v1.5 SOC Console
+# Parity plan), and `info` is the widest band because info-tier alerts
+# are background context, not work items the analyst is on the clock for.
+#
+# Lifted to a module-level constant so it can be asserted against in
+# tests; the row is also the source of truth used by ``compute_sla_metrics``
+# when a tenant hasn't overridden it via ``tenant_sla_config``.
+DEFAULT_SLA_TARGETS: dict[str, dict[str, int]] = {
+ "critical": {"mttd_target": 15, "mttr_target": 60, "mttc_target": 120},
+ "high": {"mttd_target": 30, "mttr_target": 120, "mttc_target": 240},
+ "medium": {"mttd_target": 60, "mttr_target": 240, "mttc_target": 480},
+ "low": {"mttd_target": 120, "mttr_target": 480, "mttc_target": 1440},
+ "info": {"mttd_target": 480, "mttr_target": 1440, "mttc_target": 2880},
+}
+
+
def merge_kpi_bar_dict(existing: dict | None, patch: dict[str, float]) -> dict[str, float]:
"""Merge ``patch`` into stored ``kpi_bar`` and coerce to the four known keys + defaults."""
kb = {**(existing or {}), **patch}
@@ -243,16 +261,10 @@ async def compute_sla_metrics(
buckets.setdefault(sev, []).append(d)
per_severity: dict[str, dict[str, Any]] = {}
- default_targets = {
- "critical": {"mttd_target": 15, "mttr_target": 60, "mttc_target": 120},
- "high": {"mttd_target": 30, "mttr_target": 120, "mttc_target": 240},
- "medium": {"mttd_target": 60, "mttr_target": 240, "mttc_target": 480},
- "low": {"mttd_target": 120, "mttr_target": 480, "mttc_target": 1440},
- }
- for sev in ["critical", "high", "medium", "low"]:
+ for sev in ["critical", "high", "medium", "low", "info"]:
items = buckets.get(sev, [])
- targets = configs.get(sev) or default_targets.get(sev, {})
+ targets = configs.get(sev) or DEFAULT_SLA_TARGETS.get(sev, {})
mttd_vals = [i["mttd"] for i in items if i["mttd"] is not None]
mttr_vals = [i["mttr"] for i in items if i["mttr"] is not None]
diff --git a/services/api/migrations/040_critical_severity_alert_confidence.sql b/services/api/migrations/040_critical_severity_alert_confidence.sql
new file mode 100644
index 000000000..6a86e6edb
--- /dev/null
+++ b/services/api/migrations/040_critical_severity_alert_confidence.sql
@@ -0,0 +1,124 @@
+-- Migration 040: SOC console parity — critical severity tier + alert.confidence
+-- Implements W2 (critical severity tier) and W3 (alert-level confidence) from
+-- the v1.5 SOC Console Parity plan.
+--
+-- Changes:
+-- 1. tenant_sla_config: extend severity CHECK constraint to include 'info'
+-- and seed default SLA targets for info-tier alerts. The other tables in
+-- the system (alerts, cases, detection_rules) already accept the full
+-- 5-tier ladder because they use plain VARCHAR(20) without a CHECK
+-- constraint.
+-- 2. alerts: add three new columns to carry the confidence signal that the
+-- fusion service computes:
+-- - confidence (INTEGER 0-100) — the canonical score the API surfaces
+-- - confidence_label (TEXT) — 'high' | 'medium' | 'low' (nullable)
+-- - confidence_rationale (JSONB) — structured contribution list
+-- 3. Backfill: keep existing rows' confidence NULL on purpose — these are
+-- legacy alerts created before the fusion service started emitting
+-- confidence; downstream code already treats NULL as "unknown".
+--
+-- Idempotent — safe to re-run.
+
+BEGIN;
+
+-- ──────────────────────────────────────────────────────────────────────────────
+-- 1. Extend tenant_sla_config to support 'info' tier
+-- ──────────────────────────────────────────────────────────────────────────────
+
+DO $$
+DECLARE
+ legacy_constraint RECORD;
+BEGIN
+ -- Drop any legacy severity CHECK constraint that does not yet include
+ -- 'info'. Migration 007 created the constraint with an auto-generated
+ -- name, so we look it up by table + content rather than guess the name.
+ -- This stays robust across fresh deploys (where 040 is the first chance
+ -- to widen) and re-runs.
+ FOR legacy_constraint IN
+ SELECT c.conname
+ FROM pg_constraint c
+ JOIN pg_class t ON t.oid = c.conrelid
+ WHERE t.relname = 'tenant_sla_config'
+ AND c.contype = 'c'
+ AND pg_get_constraintdef(c.oid) ILIKE '%severity%'
+ AND pg_get_constraintdef(c.oid) NOT ILIKE '%info%'
+ LOOP
+ EXECUTE format(
+ 'ALTER TABLE tenant_sla_config DROP CONSTRAINT IF EXISTS %I',
+ legacy_constraint.conname
+ );
+ END LOOP;
+END
+$$;
+
+-- Add the 5-tier constraint with a stable, explicit name so future migrations
+-- can target it deterministically.
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'ck_tenant_sla_config_severity_v2'
+ ) THEN
+ ALTER TABLE tenant_sla_config
+ ADD CONSTRAINT ck_tenant_sla_config_severity_v2
+ CHECK (severity IN ('critical','high','medium','low','info'));
+ END IF;
+END
+$$;
+
+-- Seed info-tier defaults for every existing tenant. Info alerts get the
+-- loosest SLA (4h detect, 24h respond, 72h close) — they exist for awareness
+-- but never page anyone.
+INSERT INTO tenant_sla_config (tenant_id, severity, mttd_target, mttr_target, mttc_target)
+SELECT t.id, 'info', 240, 1440, 4320
+FROM tenants t
+ON CONFLICT (tenant_id, severity) DO NOTHING;
+
+-- ──────────────────────────────────────────────────────────────────────────────
+-- 2. Add alerts.confidence, alerts.confidence_label, alerts.confidence_rationale
+-- ──────────────────────────────────────────────────────────────────────────────
+
+ALTER TABLE alerts
+ ADD COLUMN IF NOT EXISTS confidence INTEGER,
+ ADD COLUMN IF NOT EXISTS confidence_label TEXT,
+ ADD COLUMN IF NOT EXISTS confidence_rationale JSONB;
+
+-- Constrain confidence to [0, 100] for any non-NULL value. Legacy rows stay
+-- NULL until they're re-fused or re-evaluated.
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'ck_alerts_confidence_range'
+ ) THEN
+ ALTER TABLE alerts
+ ADD CONSTRAINT ck_alerts_confidence_range
+ CHECK (confidence IS NULL OR (confidence >= 0 AND confidence <= 100));
+ END IF;
+END
+$$;
+
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_constraint
+ WHERE conname = 'ck_alerts_confidence_label_enum'
+ ) THEN
+ ALTER TABLE alerts
+ ADD CONSTRAINT ck_alerts_confidence_label_enum
+ CHECK (confidence_label IS NULL OR confidence_label IN ('high','medium','low'));
+ END IF;
+END
+$$;
+
+-- Index for "show me high-confidence critical alerts" and other filter combos
+-- that combine severity + confidence (the bread and butter of the queue
+-- workbench in PR-5).
+CREATE INDEX IF NOT EXISTS idx_alerts_confidence
+ ON alerts(tenant_id, confidence DESC NULLS LAST)
+ WHERE confidence IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS idx_alerts_severity_confidence
+ ON alerts(tenant_id, severity, confidence DESC NULLS LAST);
+
+COMMIT;
diff --git a/services/api/tests/api/v1/endpoints/test_alerts_confidence_contract.py b/services/api/tests/api/v1/endpoints/test_alerts_confidence_contract.py
new file mode 100644
index 000000000..d912a7077
--- /dev/null
+++ b/services/api/tests/api/v1/endpoints/test_alerts_confidence_contract.py
@@ -0,0 +1,237 @@
+"""Schema contract tests for alert.confidence + critical severity.
+
+These tests lock in the AlertResponse Pydantic contract introduced by the
+v1.5 SOC Console Parity plan (W2 critical-severity tier + W3 alert-level
+confidence). They are intentionally pure — no DB, no FastAPI app — so they
+run in milliseconds and stay readable.
+
+The contract we're guarding:
+
+1. The five-tier severity ladder (`info | low | medium | high | critical`)
+ round-trips through ``AlertResponse``.
+2. ``confidence`` (int 0-100), ``confidence_label`` (high|medium|low|None),
+ and ``confidence_rationale`` (list|None) are part of the response model
+ and accept the values the fusion service emits.
+3. Legacy alerts that pre-date fusion-emitted confidence serialise cleanly
+ with ``None`` on all three fields.
+4. ``confidence_label`` mirrors the band enum exposed by
+ ``services/fusion``'s ``ConfidenceLabel`` so the UI doesn't have to
+ translate between services.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+import pytest
+
+from app.api.v1.endpoints.alerts import AlertResponse
+
+
+def _make_alert_payload(**overrides) -> dict:
+ """Build a minimum-viable AlertResponse-shaped dict.
+
+ Mirrors the columns ``AlertResponse`` exposes today. Tests override
+ just the fields they care about so each assertion stays focused.
+ """
+ now = datetime.now(UTC)
+ base = {
+ "id": uuid.uuid4(),
+ "tenant_id": uuid.uuid4(),
+ "title": "Suspicious Login",
+ "description": None,
+ "severity": "medium",
+ "status": "new",
+ "priority": 50,
+ "category": None,
+ "mitre_tactics": [],
+ "mitre_techniques": [],
+ "connector_type": None,
+ "ai_score": None,
+ "ai_summary": None,
+ "ai_recommendations": [],
+ "confidence": None,
+ "confidence_label": None,
+ "confidence_rationale": None,
+ "disposition": None,
+ "affected_ips": [],
+ "affected_hosts": [],
+ "affected_users": [],
+ "case_id": None,
+ "tags": [],
+ "event_time": now,
+ "first_seen": now,
+ "last_seen": now,
+ "created_at": now,
+ "updated_at": now,
+ }
+ base.update(overrides)
+ return base
+
+
+# ─── Severity ladder ──────────────────────────────────────────────────────────
+
+
[email protected]("severity", ["info", "low", "medium", "high", "critical"])
+def test_alert_response_accepts_all_five_severity_tiers(severity: str) -> None:
+ """v1.5+ ladder: every tier must round-trip through ``AlertResponse``.
+
+ Vendor-native ``critical`` (Azure 5-tier, GCP SCC 5-tier, GitHub critical,
+ AWS GuardDuty ≥8.0, AuditD identity-destruction, K8s cluster-admin
+ bindings, ServiceNow P1, Tailscale tailnet lockdown) must NOT collapse
+ into ``high`` at the connector boundary, so we explicitly verify it
+ flows through the API contract.
+ """
+ payload = _make_alert_payload(severity=severity)
+ resp = AlertResponse.model_validate(payload)
+ assert resp.severity == severity
+
+
+# ─── Confidence (W3) ──────────────────────────────────────────────────────────
+
+
+def test_alert_response_accepts_full_confidence_payload() -> None:
+ """A fusion-emitted alert carries score + label + rationale."""
+ rationale = [
+ {
+ "factor": "asset_criticality",
+ "weight": 0.30,
+ "contribution": 25,
+ "description": "Asset prod-db-01 is tier-1 critical",
+ },
+ {
+ "factor": "threat_intel_match",
+ "weight": 0.25,
+ "contribution": 20,
+ "description": "Source IP matched 2 IOCs",
+ },
+ ]
+ resp = AlertResponse.model_validate(
+ _make_alert_payload(
+ severity="critical",
+ confidence=82,
+ confidence_label="high",
+ confidence_rationale=rationale,
+ )
+ )
+
+ assert resp.confidence == 82
+ assert resp.confidence_label == "high"
+ assert resp.confidence_rationale is not None
+ assert len(resp.confidence_rationale) == 2
+ assert resp.confidence_rationale[0]["factor"] == "asset_criticality"
+
+
+def test_alert_response_accepts_null_confidence_for_legacy_alerts() -> None:
+ """Pre-W3 alerts have NULL confidence and must still serialise.
+
+ The fusion service started emitting ``confidence`` in v1.5; alerts
+ created before that boundary have NULL on all three columns. The API
+ contract must keep returning ``None`` rather than coerce to 0 — UIs
+ interpret 0 as "actively low-confidence", which would mis-rank legacy
+ alerts in the queue workbench.
+ """
+ resp = AlertResponse.model_validate(_make_alert_payload(severity="info"))
+ assert resp.confidence is None
+ assert resp.confidence_label is None
+ assert resp.confidence_rationale is None
+
+
[email protected]("label", ["high", "medium", "low"])
+def test_alert_response_accepts_all_confidence_label_bands(label: str) -> None:
+ """Bands mirror services/fusion ConfidenceLabel.{HIGH,MEDIUM,LOW}.
+
+ Keeping the strings identical means the frontend's confidence pill
+ can use the same colour-coding the fusion service intends — no
+ translation layer between services.
+ """
+ resp = AlertResponse.model_validate(
+ _make_alert_payload(confidence=60, confidence_label=label),
+ )
+ assert resp.confidence_label == label
+
+
+def test_alert_response_accepts_empty_rationale_list() -> None:
+ """An empty rationale array is valid (some scorers emit no factors)."""
+ resp = AlertResponse.model_validate(
+ _make_alert_payload(
+ confidence=50,
+ confidence_label="medium",
+ confidence_rationale=[],
+ ),
+ )
+ assert resp.confidence_rationale == []
+
+
+def test_alert_response_serialises_confidence_fields_in_snake_case() -> None:
+ """API uses snake_case on the wire; UI normaliser converts to camelCase.
+
+ This pins the wire format so we don't accidentally swap to ``alias``-
+ based camelCase here without also updating ``apps/web/src/lib/api.ts``.
+ The frontend ``Alert`` interface uses ``confidenceLabel`` /
+ ``confidenceScore``, but the conversion happens in the React layer
+ (or via ``alias`` in a future cleanup), not in this endpoint.
+ """
+ resp = AlertResponse.model_validate(
+ _make_alert_payload(
+ confidence=75,
+ confidence_label="high",
+ confidence_rationale=[{"factor": "x", "contribution": 10}],
+ ),
+ )
+ dumped = resp.model_dump()
+ assert "confidence" in dumped
+ assert "confidence_label" in dumped
+ assert "confidence_rationale" in dumped
+ # We have NOT (yet) introduced camelCase aliases at the API layer; if
+ # someone does, they should also update the frontend normaliser in
+ # ``apps/web/src/lib/api.ts``. This guard makes the migration explicit.
+ assert "confidenceLabel" not in dumped
+ assert "confidenceRationale" not in dumped
+
+
+# ─── SLA contract: critical = P1 ──────────────────────────────────────────────
+
+
+def test_sla_default_targets_treat_critical_as_p1() -> None:
+ """``critical`` must have a 15-minute MTTD target (P1 / Sev1 contract).
+
+ The five-tier ladder split out ``critical`` from ``high`` precisely so
+ that real P1 incidents get a 15-minute detect / 60-minute respond
+ target. If a refactor accidentally drops these back to the ``high``
+ defaults (30 / 120), this test will catch it.
+ """
+ from app.services.sla import DEFAULT_SLA_TARGETS
+
+ assert "critical" in DEFAULT_SLA_TARGETS
+ assert DEFAULT_SLA_TARGETS["critical"]["mttd_target"] == 15
+ assert DEFAULT_SLA_TARGETS["critical"]["mttr_target"] == 60
+ assert DEFAULT_SLA_TARGETS["critical"]["mttc_target"] == 120
+
+
+def test_sla_default_targets_treat_info_as_lowest_priority() -> None:
+ """``info`` exists for awareness only — it must have the loosest SLA."""
+ from app.services.sla import DEFAULT_SLA_TARGETS
+
+ assert "info" in DEFAULT_SLA_TARGETS
+ # Info should never be tighter than ``low`` on any of the three timers.
+ for key in ("mttd_target", "mttr_target", "mttc_target"):
+ assert DEFAULT_SLA_TARGETS["info"][key] >= DEFAULT_SLA_TARGETS["low"][key]
+
+
+def test_sla_default_targets_strict_severity_ordering() -> None:
+ """SLA targets must monotonically widen across the five-tier ladder.
+
+ Each tier should have targets ≥ the next-stricter tier. This prevents a
+ config refactor from accidentally making ``medium`` stricter than
+ ``high``, which would confuse downstream breach reporting.
+ """
+ from app.services.sla import DEFAULT_SLA_TARGETS
+
+ order = ["critical", "high", "medium", "low", "info"]
+ for key in ("mttd_target", "mttr_target", "mttc_target"):
+ values = [DEFAULT_SLA_TARGETS[sev][key] for sev in order]
+ assert values == sorted(values), (
+ f"SLA {key} must widen across {order}: got {values}"
+ )
diff --git a/services/api/tests/test_seed_demo_confidence_synth.py b/services/api/tests/test_seed_demo_confidence_synth.py
new file mode 100644
index 000000000..9614732a9
--- /dev/null
+++ b/services/api/tests/test_seed_demo_confidence_synth.py
@@ -0,0 +1,140 @@
+"""Contract tests for ``_synthesise_confidence`` in the demo seeder.
+
+The demo seeder doesn't run a live fusion service, so it mirrors the
+``services/fusion`` ``ConfidenceScorer`` math inline. These tests pin the
+mirror so it can't drift silently — if someone rebalances the real scorer
+without updating the seeder (or vice versa), the demo would start showing
+confidence values that the API contract rejects.
+
+The contract we're guarding:
+
+1. Output shape: ``(int 0-100, label, list[ConfidenceFactor-shaped dict])``.
+2. ``label`` is one of ``{"low", "medium", "high"}`` — same strings the
+ fusion ``ConfidenceLabel`` enum emits.
+3. Each rationale entry has the keys the UI's confidence pill expects
+ (``factor``, ``label``, ``value``, ``contribution``, ``weight``).
+4. Rationale is sorted by absolute impact descending, so the top driver
+ shows up first in the explainability list.
+5. Severity dominates: a ``critical`` alert with strong signals scores
+ strictly higher than the same alert downgraded to ``info``.
+
+These tests are pure — no DB, no asyncio, no fixtures. They execute the
+helper directly.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from app.scripts.seed_demo import _synthesise_confidence
+
+
+_REQUIRED_KEYS = {"factor", "label", "value", "contribution", "weight"}
+
+
+# ─── Output shape ─────────────────────────────────────────────────────────────
+
+
+def test_synthesise_returns_int_label_list_triple() -> None:
+ """Top-level shape: ``(int 0-100, label, list)``."""
+ score, label, rationale = _synthesise_confidence(
+ severity="high",
+ ai_score=0.75,
+ n_techniques=2,
+ n_iocs=3,
+ has_threat_intel=True,
+ )
+
+ assert isinstance(score, int)
+ assert 0 <= score <= 100
+ assert label in {"low", "medium", "high"}
+ assert isinstance(rationale, list)
+ assert len(rationale) >= 1
+
+
+def test_each_rationale_entry_carries_confidence_factor_keys() -> None:
+ """Every rationale row must be ConfidenceFactor-shaped for the UI."""
+ _, _, rationale = _synthesise_confidence(
+ severity="medium",
+ ai_score=0.6,
+ n_techniques=1,
+ n_iocs=2,
+ has_threat_intel=False,
+ )
+
+ for entry in rationale:
+ missing = _REQUIRED_KEYS - entry.keys()
+ assert not missing, f"missing keys in rationale: {missing}"
+ assert isinstance(entry["contribution"], (int, float))
+ assert isinstance(entry["weight"], (int, float))
+ # Weights are normalised in [0, 1]; contributions in [-1, +1].
+ assert 0 <= entry["weight"] <= 1
+ assert -1.0 <= entry["contribution"] <= 1.0
+
+
+def test_rationale_sorted_by_absolute_impact() -> None:
+ """Top driver shows up first — UI relies on this ordering."""
+ _, _, rationale = _synthesise_confidence(
+ severity="critical",
+ ai_score=0.9,
+ n_techniques=3,
+ n_iocs=5,
+ has_threat_intel=True,
+ )
+
+ impacts = [abs(f["contribution"] * f["weight"]) for f in rationale]
+ assert impacts == sorted(impacts, reverse=True)
+
+
+# ─── Score semantics ──────────────────────────────────────────────────────────
+
+
[email protected]("severity", ["info", "low", "medium", "high", "critical"])
+def test_synthesise_accepts_all_five_severity_tiers(severity: str) -> None:
+ """All v1.5 severity tiers must produce a valid score — including info."""
+ score, label, rationale = _synthesise_confidence(
+ severity=severity,
+ ai_score=0.5,
+ n_techniques=1,
+ n_iocs=1,
+ has_threat_intel=False,
+ )
+
+ assert 0 <= score <= 100
+ assert label in {"low", "medium", "high"}
+ # The severity row must surface in the rationale verbatim.
+ severity_entries = [f for f in rationale if f["factor"] == "severity"]
+ assert len(severity_entries) == 1
+ assert severity_entries[0]["value"] == severity
+
+
+def test_critical_beats_info_when_other_signals_equal() -> None:
+ """A critical alert should out-score the same alert downgraded to info.
+
+ Severity is one of seven factors but it's the largest single driver of
+ confidence at the extremes of the ladder, so this asymmetry must hold.
+ If a refactor flips the sign on ``_SEVERITY_CONTRIBUTION``, this test
+ catches it.
+ """
+ common = {
+ "ai_score": 0.7,
+ "n_techniques": 2,
+ "n_iocs": 3,
+ "has_threat_intel": True,
+ }
+ crit_score, _, _ = _synthesise_confidence(severity="critical", **common)
+ info_score, _, _ = _synthesise_confidence(severity="info", **common)
+ assert crit_score > info_score
+
+
+def test_threat_intel_match_lifts_score_over_no_match() -> None:
+ """TI match must be a positive driver — same alert, different TI signal."""
+ common = {
+ "severity": "high",
+ "ai_score": 0.6,
+ "n_techniques": 2,
+ "n_iocs": 2,
+ }
+ with_ti, _, _ = _synthesise_confidence(has_threat_intel=True, **common)
+ without_ti, _, _ = _synthesise_confidence(has_threat_intel=False, **common)
+ assert with_ti > without_ti
diff --git a/services/connectors/app/connectors/auditd.py b/services/connectors/app/connectors/auditd.py
index eea88574e..74dc0948d 100644
--- a/services/connectors/app/connectors/auditd.py
+++ b/services/connectors/app/connectors/auditd.py
@@ -144,8 +144,8 @@ _MAX_EVENTS_PER_POLL = 50_000
# critical by renaming it.
_KEY_SEVERITY_PREFIXES: tuple[tuple[str, str], ...] = (
- ("aisoc_critical_", "high"),
- ("aisoc_priv_esc_", "medium"),
+ ("aisoc_critical_", "critical"),
+ ("aisoc_priv_esc_", "high"),
("aisoc_persistence_", "medium"),
("aisoc_exec", "medium"),
("aisoc_watch_", "low"),
@@ -175,7 +175,7 @@ _HIGH_RISK_EXEC_DIRS: tuple[str, ...] = (
def _severity_from_event(event: dict[str, Any]) -> str:
- """Bucket a reassembled auditd event into AiSOC's 4-tier ladder.
+ """Bucket a reassembled auditd event into AiSOC's 5-tier ladder.
Priority order:
1. AiSOC-profile key prefix match (``aisoc_critical_*`` etc.).
diff --git a/services/connectors/app/connectors/aws_cloudtrail.py b/services/connectors/app/connectors/aws_cloudtrail.py
index 87c46a425..e19831d0e 100644
--- a/services/connectors/app/connectors/aws_cloudtrail.py
+++ b/services/connectors/app/connectors/aws_cloudtrail.py
@@ -66,23 +66,36 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
-# High-severity events: trail/detection tamper, KMS destruction, root
-# account use, org-level tampering. These are almost always incidents.
-_HIGH_SEVERITY_EVENTS = frozenset(
+# Critical-severity events: irreversible-or-incident-grade actions
+# that almost always represent active tamper / take-over. These map
+# straight to AiSOC's ``critical`` tier so they fire the P1 SLA.
+_CRITICAL_SEVERITY_EVENTS = frozenset(
{
- "ChangeRootMail",
- "DeleteDetector",
- "DeleteFlowLogs",
+ # Visibility kill switches — silencing the audit trail itself.
"DeleteTrail",
- "DisableKey",
+ "DeleteDetector", # GuardDuty detector deletion
"DisableSecurityHub",
+ "StopLogging", # CloudTrail
+ "StopConfigurationRecorder", # AWS Config
+ # Irreversible account / org takeover primitives.
"LeaveOrganization",
- "PutEventSelectors",
"RemoveAccountFromOrganization",
- "ScheduleKeyDeletion",
- "StopConfigurationRecorder",
- "StopLogging",
"TransferDomainToAnotherAwsAccount",
+ # Crypto destruction — pending unrecoverable data loss.
+ "ScheduleKeyDeletion",
+ "DisableKey",
+ }
+)
+
+
+# High-severity events: trail/detection tamper, KMS destruction
+# (recoverable), root account use, and other org-level changes that
+# warrant analyst eyes but aren't standalone P1 incidents on their own.
+_HIGH_SEVERITY_EVENTS = frozenset(
+ {
+ "ChangeRootMail",
+ "DeleteFlowLogs",
+ "PutEventSelectors",
"UpdateTrail",
}
)
@@ -188,11 +201,13 @@ DEFAULT_EVENT_NAMES: tuple[str, ...] = (
def _event_severity(event_name: str, error_code: str | None) -> str:
- """Bucket a CloudTrail event into AiSOC's 4-tier severity ladder.
+ """Bucket a CloudTrail event into AiSOC's 5-tier severity ladder.
Heuristic:
+ - CRITICAL if it's in ``_CRITICAL_SEVERITY_EVENTS`` (visibility
+ kill switches, org take-over, KMS destruction).
- HIGH if it's in ``_HIGH_SEVERITY_EVENTS`` (trail tamper,
- KMS destruction, org-level changes, etc).
+ root mail change, etc).
- LOW if it's a known read-only recon call.
- MEDIUM for everything else (the default for mutating events).
@@ -200,7 +215,9 @@ def _event_severity(event_name: str, error_code: str | None) -> str:
the theory that a denied destructive action is often the loudest
signal we have in the account.
"""
- if event_name in _HIGH_SEVERITY_EVENTS:
+ if event_name in _CRITICAL_SEVERITY_EVENTS:
+ base = "critical"
+ elif event_name in _HIGH_SEVERITY_EVENTS:
base = "high"
elif event_name in _LOW_SEVERITY_EVENTS:
base = "low"
diff --git a/services/connectors/app/connectors/aws_guardduty.py b/services/connectors/app/connectors/aws_guardduty.py
index 1265468a3..84cb6d6ca 100644
--- a/services/connectors/app/connectors/aws_guardduty.py
+++ b/services/connectors/app/connectors/aws_guardduty.py
@@ -17,17 +17,20 @@ Auth model:
- Or supply a static IAM access-key pair scoped to read-only
GuardDuty permissions.
-Severity collapse:
- GuardDuty returns severity as a float in [1.0, 8.9]. AiSOC's
- canonical ladder is ``info | low | medium | high``. We bucket using
- AWS's published thresholds:
+Severity mapping:
+ GuardDuty publishes severity as a float roughly in [0.1, 10.0]. AiSOC's
+ canonical ladder is the 5-tier ``info | low | medium | high | critical``
+ set. We bucket using AWS's own published thresholds, preserving the
+ Critical tier so P1 GuardDuty findings keep their original priority:
+ 0.1–0.9 --> info
1.0–3.9 --> low
4.0–6.9 --> medium
7.0–8.9 --> high
+ 9.0–10.0 --> critical
- Anything < 1.0 (rare but possible for sample/test findings) collapses
- to ``info``.
+ The original float is preserved on ``raw_event.Severity`` for callers
+ that need exact comparisons.
"""
from __future__ import annotations
@@ -43,14 +46,16 @@ logger = structlog.get_logger()
def _severity_label(score: float | int | None) -> str:
- """Collapse GuardDuty's float severity into AiSOC's 4-tier ladder.
+ """Bucket GuardDuty's float severity into AiSOC's 5-tier ladder.
GuardDuty publishes severity as a float roughly in [0.1, 10.0]. AWS's
own console buckets that into Low (1.0-3.9), Medium (4.0-6.9),
- High (7.0-8.9), and Critical (9.0-10.0). AiSOC's canonical ladder
- has no ``critical`` tier, so anything 7.0+ collapses into ``high``
- and the original float is preserved on ``raw_event.Severity`` for
- callers that need exact comparisons.
+ High (7.0-8.9), and Critical (9.0-10.0). AiSOC's 5-tier ladder
+ (info | low | medium | high | critical) preserves the Critical tier
+ end-to-end so P1 findings keep their original priority rather than
+ getting silently downgraded into ``high``. The original float is
+ preserved on ``raw_event.Severity`` for callers that need exact
+ comparisons.
"""
if score is None:
return "medium"
@@ -64,7 +69,9 @@ def _severity_label(score: float | int | None) -> str:
return "low"
if s < 7.0:
return "medium"
- return "high"
+ if s < 9.0:
+ return "high"
+ return "critical"
class AWSGuardDutyConnector(BaseConnector):
diff --git a/services/connectors/app/connectors/azure_activity.py b/services/connectors/app/connectors/azure_activity.py
index a8c84ed50..11756d174 100644
--- a/services/connectors/app/connectors/azure_activity.py
+++ b/services/connectors/app/connectors/azure_activity.py
@@ -212,15 +212,24 @@ class AzureActivityConnector(BaseConnector):
level = (raw.get("level") or "").lower()
caller = raw.get("caller", "")
+ # Azure Activity Log severity heuristic against AiSOC's 5-tier ladder
+ # (info | low | medium | high | critical):
+ # - ``level=critical`` -> ``critical`` (Azure's hardest hint)
+ # - ``level=error`` -> ``high``
+ # - ``level=warning`` -> ``medium``
+ # - failed status -> at least ``medium``
+ # - high-blast-radius IAM/role/policy/firewall ops -> ``high``
op_lower = op_name.lower()
severity = "info"
- if level in ("error", "critical"):
+ if level == "critical":
+ severity = "critical"
+ elif level == "error":
severity = "high"
elif level == "warning":
severity = "medium"
if status.lower() == "failed":
severity = "medium" if severity == "info" else severity
- if any(verb in op_lower for verb in _HIGH_BLAST_RADIUS_VERBS):
+ if any(verb in op_lower for verb in _HIGH_BLAST_RADIUS_VERBS) and severity != "critical":
severity = "high"
resource_id = raw.get("resourceId") or ""
diff --git a/services/connectors/app/connectors/carbon_black.py b/services/connectors/app/connectors/carbon_black.py
index a7f41a3b4..56b5f25ca 100644
--- a/services/connectors/app/connectors/carbon_black.py
+++ b/services/connectors/app/connectors/carbon_black.py
@@ -217,10 +217,16 @@ class CarbonBlackConnector(BaseConnector):
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
stream = raw.get("_aisoc_stream", "alerts")
if stream == "alerts":
+ # Carbon Black Cloud uses a 1-10 severity scale on alerts.
+ # 9-10 corresponds to confirmed/imminent threat activity,
+ # which we surface as ``critical`` rather than collapsing to
+ # ``high``.
sev_score = int(raw.get("severity") or 0)
- if sev_score >= 8:
+ if sev_score >= 9:
+ severity = "critical"
+ elif sev_score >= 7:
severity = "high"
- elif sev_score >= 5:
+ elif sev_score >= 4:
severity = "medium"
elif sev_score >= 1:
severity = "low"
diff --git a/services/connectors/app/connectors/chronicle.py b/services/connectors/app/connectors/chronicle.py
index 4f86a02d8..cdf14f6b3 100644
--- a/services/connectors/app/connectors/chronicle.py
+++ b/services/connectors/app/connectors/chronicle.py
@@ -109,8 +109,12 @@ class ChronicleConnector(BaseConnector):
return []
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Chronicle SecOps detections expose the standard
+ # info/low/medium/high/critical ladder. Accept ``critical`` so
+ # the highest-impact detections survive into AiSOC's
+ # five-tier severity ladder.
sev = (raw.get("severity") or "").lower()
- if sev not in ("info", "low", "medium", "high"):
+ if sev not in ("info", "low", "medium", "high", "critical"):
sev = "medium"
return {
"source": "chronicle",
diff --git a/services/connectors/app/connectors/cortex_xdr.py b/services/connectors/app/connectors/cortex_xdr.py
index 2493eaabc..8dbd39a00 100644
--- a/services/connectors/app/connectors/cortex_xdr.py
+++ b/services/connectors/app/connectors/cortex_xdr.py
@@ -18,12 +18,15 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
+# Cortex XDR natively ships a ``critical`` tier on incidents. AiSOC's
+# 5-tier ladder preserves it end-to-end so P1 EDR detections keep their
+# original priority.
_SEVERITY_MAP: dict[str, str] = {
"informational": "info",
"low": "low",
"medium": "medium",
"high": "high",
- "critical": "high",
+ "critical": "critical",
}
diff --git a/services/connectors/app/connectors/cortex_xsiam.py b/services/connectors/app/connectors/cortex_xsiam.py
index 310692de2..84a39f813 100644
--- a/services/connectors/app/connectors/cortex_xsiam.py
+++ b/services/connectors/app/connectors/cortex_xsiam.py
@@ -124,8 +124,14 @@ class CortexXSIAMConnector(BaseConnector):
return []
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Cortex XSIAM incidents expose the standard Palo Alto severity
+ # ladder: informational / low / medium / high / critical. Mirror
+ # all five tiers (including ``critical``) into AiSOC's ladder
+ # rather than silently collapsing unknown values to ``info``.
sev_raw = (raw.get("severity") or "").lower()
- severity = sev_raw if sev_raw in ("info", "low", "medium", "high") else "info"
+ if sev_raw == "informational":
+ sev_raw = "info"
+ severity = sev_raw if sev_raw in ("info", "low", "medium", "high", "critical") else "info"
return {
"source": "cortex_xsiam",
"category": "edr",
diff --git a/services/connectors/app/connectors/crowdstrike.py b/services/connectors/app/connectors/crowdstrike.py
index df8c3bc72..7f1d84db3 100644
--- a/services/connectors/app/connectors/crowdstrike.py
+++ b/services/connectors/app/connectors/crowdstrike.py
@@ -122,8 +122,46 @@ class CrowdStrikeConnector(BaseConnector):
return [self.normalize(d) for d in detections]
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
- severity_map = {1: "low", 2: "medium", 3: "high", 4: "critical"}
- severity = severity_map.get(raw.get("max_severity", 2), "medium")
+ # CrowdStrike Falcon's `/detects` API exposes severity in three
+ # related forms:
+ # * ``max_severity`` — integer 0-100 (band-scored).
+ # * ``max_severity_displayname`` — the band name itself
+ # ("Informational", "Low", "Medium", "High", "Critical").
+ # * ``severity`` (per-behavior) — same 0-100 scale.
+ # Earlier versions of this connector treated ``max_severity`` as a
+ # 1-4 scale and collapsed everything else to "medium", which
+ # silently downgraded ``Critical`` detections. We now prefer the
+ # explicit display name when present and otherwise bucket the
+ # numeric score along the bands documented by CrowdStrike.
+ severity_bands_displayname = {
+ "informational": "info",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "critical": "critical",
+ }
+
+ display_name = (raw.get("max_severity_displayname") or "").strip().lower()
+ if display_name in severity_bands_displayname:
+ severity = severity_bands_displayname[display_name]
+ else:
+ score = raw.get("max_severity")
+ try:
+ score_int = int(score) if score is not None else None
+ except (TypeError, ValueError):
+ score_int = None
+ if score_int is None:
+ severity = "medium"
+ elif score_int >= 80:
+ severity = "critical"
+ elif score_int >= 60:
+ severity = "high"
+ elif score_int >= 40:
+ severity = "medium"
+ elif score_int >= 20:
+ severity = "low"
+ else:
+ severity = "info"
behaviors = raw.get("behaviors") or [{}]
title = behaviors[0].get("display_name", "CrowdStrike Detection")
diff --git a/services/connectors/app/connectors/datadog_cloud_siem.py b/services/connectors/app/connectors/datadog_cloud_siem.py
index f78f5ecd4..0366848d5 100644
--- a/services/connectors/app/connectors/datadog_cloud_siem.py
+++ b/services/connectors/app/connectors/datadog_cloud_siem.py
@@ -136,11 +136,13 @@ class DatadogCloudSIEMConnector(BaseConnector):
return []
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Datadog Cloud SIEM signal severities cover the standard
+ # info/low/medium/high/critical ladder. Mirror critical directly
+ # so the highest-impact signals survive into AiSOC's ladder
+ # instead of being collapsed to high.
attrs = raw.get("attributes") or {}
sev_raw = (attrs.get("severity") or "").lower()
- sev = sev_raw if sev_raw in ("info", "low", "medium", "high") else "medium"
- if sev_raw == "critical":
- sev = "high"
+ sev = sev_raw if sev_raw in ("info", "low", "medium", "high", "critical") else "medium"
title = attrs.get("title") or attrs.get("message") or "Datadog security signal"
return {
"source": "datadog_cloud_siem",
diff --git a/services/connectors/app/connectors/elastic.py b/services/connectors/app/connectors/elastic.py
index 21807dc9d..01e70bd03 100644
--- a/services/connectors/app/connectors/elastic.py
+++ b/services/connectors/app/connectors/elastic.py
@@ -183,7 +183,18 @@ class ElasticConnector(BaseConnector):
return [dict(zip(columns, row, strict=False)) for row in values]
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
- severity_map = {"low": "low", "medium": "medium", "high": "high", "critical": "high"}
+ # Elastic ships a native ``critical`` tier on detection rules; preserve
+ # it end-to-end so the AiSOC 5-tier ladder (info | low | medium | high
+ # | critical) stays faithful to the source-of-truth severity rather
+ # than silently downgrading P1 rules into ``high``.
+ severity_map = {
+ "info": "info",
+ "informational": "info",
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "critical": "critical",
+ }
severity = str(raw.get("kibana.alert.severity") or raw.get("severity") or "medium").lower()
return {
"source": self.connector_id,
diff --git a/services/connectors/app/connectors/gcp_cloud_audit.py b/services/connectors/app/connectors/gcp_cloud_audit.py
index 15ff9d233..64f26a8ba 100644
--- a/services/connectors/app/connectors/gcp_cloud_audit.py
+++ b/services/connectors/app/connectors/gcp_cloud_audit.py
@@ -287,17 +287,24 @@ class GCPCloudAuditConnector(BaseConnector):
status = proto.get("status", {}) or {}
succeeded = "code" not in status or status.get("code", 0) == 0
- # Severity heuristic: high-blast-radius IAM/KMS operations land at
- # ``high``; failed control-plane writes at ``medium``; everything
- # else at ``info``. SOC analysts will tune this with detections.
+ # Severity heuristic against AiSOC's 5-tier ladder
+ # (info | low | medium | high | critical):
+ # - high-blast-radius IAM/KMS operations -> ``high``
+ # - failed control-plane writes -> ``medium``
+ # - everything else -> ``info``
+ # Cloud Logging ``ALERT``/``EMERGENCY`` upgrade the result to
+ # ``critical`` so paged-out audit anomalies stay on the P1 SLA;
+ # ``ERROR``/``CRITICAL`` raise to ``high``. SOC analysts will tune
+ # this further with detections.
severity = "info"
if any(m in method for m in self._HIGH_BLAST_METHODS):
severity = "high"
elif not succeeded:
severity = "medium"
- # Cloud Logging severity is also a useful hint when present.
log_severity = (raw.get("severity") or "").upper()
- if log_severity in ("ERROR", "CRITICAL", "ALERT", "EMERGENCY"):
+ if log_severity in ("ALERT", "EMERGENCY"):
+ severity = "critical"
+ elif log_severity in ("ERROR", "CRITICAL"):
severity = "high"
elif log_severity == "WARNING" and severity == "info":
severity = "low"
diff --git a/services/connectors/app/connectors/gcp_scc.py b/services/connectors/app/connectors/gcp_scc.py
index a82c163eb..095885d2c 100644
--- a/services/connectors/app/connectors/gcp_scc.py
+++ b/services/connectors/app/connectors/gcp_scc.py
@@ -236,12 +236,12 @@ class GCPSCCConnector(BaseConnector):
resource = raw.get("resource", {}) or {}
# SCC severity comes through as one of CRITICAL / HIGH / MEDIUM /
- # LOW / SEVERITY_UNSPECIFIED. Map directly to AiSOC's lowercase
- # severities — Critical collapses to ``high`` since downstream
- # severity-mapping pipelines expect that vocabulary.
+ # LOW / SEVERITY_UNSPECIFIED. Map directly to AiSOC's 5-tier ladder
+ # (info | low | medium | high | critical) so P1 SCC findings keep
+ # their original priority rather than getting collapsed into ``high``.
scc_sev = (finding.get("severity") or "").upper()
severity = {
- "CRITICAL": "high",
+ "CRITICAL": "critical",
"HIGH": "high",
"MEDIUM": "medium",
"LOW": "low",
diff --git a/services/connectors/app/connectors/github.py b/services/connectors/app/connectors/github.py
index 670638beb..42b44f896 100644
--- a/services/connectors/app/connectors/github.py
+++ b/services/connectors/app/connectors/github.py
@@ -310,8 +310,11 @@ class GitHubConnector(BaseConnector):
# GitHub uses ``security-severity`` (CVSS-style numeric) and a
# categorical ``severity`` (note/warning/error/critical/high/medium/low).
# We honor the categorical first since it's set on every result.
+ # AiSOC's 5-tier ladder (info | low | medium | high | critical) preserves
+ # GitHub's native ``critical`` tier end-to-end so P1 SAST/CodeQL findings
+ # keep their original priority.
_CODE_SEVERITY_MAP = {
- "critical": "high", # collapse into AiSOC's 4-tier ladder
+ "critical": "critical",
"high": "high",
"error": "high",
"medium": "medium",
diff --git a/services/connectors/app/connectors/jira_connector.py b/services/connectors/app/connectors/jira_connector.py
index ce267cd27..9e3272b41 100644
--- a/services/connectors/app/connectors/jira_connector.py
+++ b/services/connectors/app/connectors/jira_connector.py
@@ -16,8 +16,13 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
+# Jira ships a 5-tier priority ladder (Highest / High / Medium / Low /
+# Lowest). AiSOC's 5-tier severity ladder
+# (info | low | medium | high | critical) lines up 1:1 with that, so
+# ``Highest`` maps to ``critical`` and round-trips back to ``Highest``
+# without any collapse — P1 escalations to Jira stay P1.
_PRIORITY_SEVERITY = {
- "Highest": "high",
+ "Highest": "critical",
"High": "high",
"Medium": "medium",
"Low": "low",
@@ -25,9 +30,7 @@ _PRIORITY_SEVERITY = {
}
# WS8: AiSOC severity → Jira priority. We invert ``_PRIORITY_SEVERITY``
-# but map ``critical`` → ``Highest`` because Jira doesn't have a separate
-# critical band and ``Highest`` is the highest tier available out of the
-# box. ``info`` collapses to ``Lowest`` for the same reason.
+# so the round-trip is lossless.
_SEVERITY_TO_PRIORITY = {
"critical": "Highest",
"high": "High",
diff --git a/services/connectors/app/connectors/kubernetes_audit.py b/services/connectors/app/connectors/kubernetes_audit.py
index c75b8cf88..d856f81fe 100644
--- a/services/connectors/app/connectors/kubernetes_audit.py
+++ b/services/connectors/app/connectors/kubernetes_audit.py
@@ -125,11 +125,16 @@ _MAX_TAIL_BYTES_PER_POLL = 8 * 1024 * 1024 # 8 MiB
def _classify_severity(event: dict[str, Any]) -> str:
- """Bucket a single audit event into AiSOC's 4-tier severity ladder.
+ """Bucket a single audit event into AiSOC's 5-tier severity ladder.
Reads the standard ``audit.k8s.io/v1`` Event shape:
objectRef.resource, objectRef.subresource, verb,
responseStatus.code.
+
+ The ``critical`` tier is reserved for the three signals that map
+ directly to standalone P1 SOC incidents on a Kubernetes cluster:
+ interactive shell into a pod, ``impersonate`` privilege escalation,
+ and writes to the RBAC binding graph itself.
"""
verb = (event.get("verb") or "").lower()
obj_ref = event.get("objectRef") or {}
@@ -137,19 +142,22 @@ def _classify_severity(event: dict[str, Any]) -> str:
subresource = (obj_ref.get("subresource") or "").lower()
code = (event.get("responseStatus") or {}).get("code")
- # Interactive shell into a pod is the loudest signal we have.
+ # Interactive shell into a pod is the loudest signal we have —
+ # treat it as a standalone critical incident worthy of the P1 SLA.
if resource == "pods" and subresource in _INTERACTIVE_SUBRESOURCES:
- return "high"
+ return "critical"
- # Privilege-escalation primitives.
+ # Privilege-escalation primitives — direct hand-off of identity.
if verb == "impersonate":
- return "high"
+ return "critical"
- # Writes against the RBAC graph itself.
+ # Writes against the RBAC graph itself — most common cluster
+ # take-over primitive after an initial foothold.
if verb in _WRITE_VERBS and resource in {"clusterrolebindings", "rolebindings"}:
- return "high"
+ return "critical"
- # Writes against any other sensitive resource.
+ # Writes against any other sensitive resource (Secrets,
+ # ServiceAccounts, Roles, etc).
if verb in _WRITE_VERBS and resource in _SENSITIVE_RESOURCES:
return "high"
diff --git a/services/connectors/app/connectors/lacework.py b/services/connectors/app/connectors/lacework.py
index c2473675d..a8ff5048a 100644
--- a/services/connectors/app/connectors/lacework.py
+++ b/services/connectors/app/connectors/lacework.py
@@ -156,10 +156,11 @@ class LaceworkConnector(BaseConnector):
return []
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Lacework alerts expose info/low/medium/high/critical. Mirror
+ # all five tiers (including ``critical``) into AiSOC's ladder
+ # rather than collapsing critical to high.
sev_raw = (raw.get("severity") or "").lower()
- if sev_raw in ("critical",):
- sev = "high"
- elif sev_raw in ("info", "low", "medium", "high"):
+ if sev_raw in ("info", "low", "medium", "high", "critical"):
sev = sev_raw
else:
sev = "medium"
diff --git a/services/connectors/app/connectors/orca.py b/services/connectors/app/connectors/orca.py
index e8034a335..d2392518a 100644
--- a/services/connectors/app/connectors/orca.py
+++ b/services/connectors/app/connectors/orca.py
@@ -12,11 +12,13 @@ Auth model:
Tokens are minted in the Orca console under
Settings → Users & Permissions → API Tokens.
-Severity collapse:
+Severity mapping:
Orca uses a 5-tier ladder (``hazardous, critical, high, medium,
- informational``). AiSOC exposes 4 tiers (``high, medium, low, info``).
- ``hazardous`` and ``critical`` collapse into ``high``. The original
- Orca tier is preserved on ``raw_event.state.severity``.
+ informational``). AiSOC also exposes 5 tiers (``critical, high,
+ medium, low, info``). Both ``hazardous`` (Orca's "actively exploited /
+ active threat" band) and ``critical`` map into AiSOC ``critical`` so
+ P1 cloud findings keep their original priority. The original Orca
+ tier is preserved on ``raw_event.state.severity``.
"""
from __future__ import annotations
@@ -33,15 +35,14 @@ logger = structlog.get_logger()
_DEFAULT_API_URL = "https://api.orcasecurity.io"
-# Orca's 5-tier ladder collapsed into AiSOC's 4-tier canonical set.
+# Orca's 5-tier ladder mapped into AiSOC's 5-tier canonical set.
# ``hazardous`` is Orca-internal terminology for "actively exploited /
-# active threat" and is unambiguously high-impact. ``critical`` likewise
-# collapses into ``high`` because AiSOC does not expose a separate
-# critical band.
+# active threat" and is the most severe band — escalate it to AiSOC
+# ``critical`` so the SOC P1 SLA fires. ``critical`` stays ``critical``.
_SEVERITY_MAP: dict[str, str] = {
- "hazardous": "high",
- "imminent_compromise": "high",
- "critical": "high",
+ "hazardous": "critical",
+ "imminent_compromise": "critical",
+ "critical": "critical",
"high": "high",
"medium": "medium",
"low": "low",
diff --git a/services/connectors/app/connectors/prisma_cloud.py b/services/connectors/app/connectors/prisma_cloud.py
index 3f9bafa80..7649bfc0d 100644
--- a/services/connectors/app/connectors/prisma_cloud.py
+++ b/services/connectors/app/connectors/prisma_cloud.py
@@ -30,12 +30,12 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
-# Prisma Cloud uses a 4-tier severity ladder; map directly into AiSOC's
-# canonical 4-tier set. ``critical`` collapses into ``high`` because AiSOC
-# does not expose a separate critical band — playbooks that need the
-# original tier can read it back from ``raw_event.severity``.
+# Prisma Cloud ships a native ``critical`` tier on alerts. AiSOC's 5-tier
+# ladder (info | low | medium | high | critical) preserves it end-to-end so
+# P1 cloud findings keep their original priority rather than getting
+# downgraded into ``high``.
_SEVERITY_MAP: dict[str, str] = {
- "critical": "high",
+ "critical": "critical",
"high": "high",
"medium": "medium",
"low": "low",
diff --git a/services/connectors/app/connectors/rapid7_insightidr.py b/services/connectors/app/connectors/rapid7_insightidr.py
index 0fabbd64d..7f924131d 100644
--- a/services/connectors/app/connectors/rapid7_insightidr.py
+++ b/services/connectors/app/connectors/rapid7_insightidr.py
@@ -128,8 +128,12 @@ class Rapid7InsightIDRConnector(BaseConnector):
return []
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Rapid7 InsightIDR investigations carry priority
+ # {LOW, MEDIUM, HIGH, CRITICAL, UNSPECIFIED}. Mirror critical
+ # directly into AiSOC's five-tier severity ladder rather than
+ # silently downgrading to ``info``.
prio = (raw.get("priority") or "").lower()
- severity = prio if prio in ("info", "low", "medium", "high") else "info"
+ severity = prio if prio in ("info", "low", "medium", "high", "critical") else "info"
return {
"source": "rapid7_insightidr",
"category": "siem",
diff --git a/services/connectors/app/connectors/sentinelone.py b/services/connectors/app/connectors/sentinelone.py
index c2292ceaf..e6e9db210 100644
--- a/services/connectors/app/connectors/sentinelone.py
+++ b/services/connectors/app/connectors/sentinelone.py
@@ -21,7 +21,10 @@ _SEVERITY_MAP = {
"Low": "low",
"Medium": "medium",
"High": "high",
- "Critical": "high",
+ # SentinelOne natively ships a ``Critical`` severity. Preserve it on the
+ # AiSOC side so P1 EDR detections stay in the dedicated critical band
+ # rather than getting collapsed into ``high``.
+ "Critical": "critical",
}
diff --git a/services/connectors/app/connectors/servicenow.py b/services/connectors/app/connectors/servicenow.py
index 56858b4fa..8bf620c08 100644
--- a/services/connectors/app/connectors/servicenow.py
+++ b/services/connectors/app/connectors/servicenow.py
@@ -19,17 +19,34 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
+# ServiceNow's OOTB incident table exposes a 3-tier ``impact`` field
+# (1=High, 2=Medium, 3=Low) but a 5-tier *computed* ``priority`` field
+# (1=Critical, 2=High, 3=Moderate, 4=Low, 5=Planning). We prefer
+# ``priority`` for inbound normalisation because it round-trips AiSOC's
+# 5-tier ladder (info | low | medium | high | critical) losslessly; we
+# fall back to ``impact`` only when ``priority`` is missing.
+_PRIORITY_SEVERITY = {
+ "1": "critical",
+ "2": "high",
+ "3": "medium",
+ "4": "low",
+ "5": "info",
+}
+
_IMPACT_SEVERITY = {
"1": "high",
"2": "medium",
"3": "low",
}
-# WS8: AiSOC severity → ServiceNow ``impact`` numeric code. ServiceNow
-# uses 1=High, 2=Medium, 3=Low. We collapse ``critical`` and ``high``
-# onto 1 because the OOTB incident table doesn't have a separate
-# critical band, and ``info`` collapses onto 3 (Low) — there's no
-# "informational" tier in the standard schema.
+# WS8: AiSOC severity → ServiceNow ``impact`` numeric code. ServiceNow's
+# ``impact`` field is 3-tier (1=High / 2=Medium / 3=Low), so we set
+# impact=1 + urgency=1 together — ServiceNow's calculated ``priority``
+# matrix turns ``impact=1 + urgency=1`` into priority 1 ("Critical"),
+# which preserves the P1 signal even though ``impact`` itself has no
+# separate critical band. ``info`` collapses to impact=3 / urgency=3,
+# which yields priority 5 ("Planning") — the closest analog ServiceNow
+# ships out of the box.
_SEVERITY_TO_IMPACT = {
"critical": "1",
"high": "1",
@@ -38,6 +55,18 @@ _SEVERITY_TO_IMPACT = {
"info": "3",
}
+# Urgency mirrors impact but pushes ``critical`` to 1 and ``high`` to 2
+# so the resulting priority matrix differentiates them:
+# critical: impact=1 + urgency=1 → priority 1 (Critical)
+# high : impact=1 + urgency=2 → priority 2 (High)
+_SEVERITY_TO_URGENCY = {
+ "critical": "1",
+ "high": "2",
+ "medium": "2",
+ "low": "3",
+ "info": "3",
+}
+
# WS8: AiSOC status → ServiceNow ``state`` numeric code. The default
# ServiceNow incident state field is a numeric choice list:
# 1=New, 2=In Progress, 3=On Hold, 6=Resolved, 7=Closed, 8=Canceled.
@@ -132,16 +161,28 @@ class ServiceNowConnector(BaseConnector):
return [self.normalize(i) for i in incidents]
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
- impact = str(raw.get("impact", "3"))
- if isinstance(impact, dict):
- impact = impact.get("value", "3")
+ # ServiceNow returns these fields as strings under
+ # ``sysparm_display_value=true``, but as nested dicts
+ # (``{"value": "1", "display_value": "Critical"}``) under
+ # ``sysparm_display_value=all``. Defend against both.
+ def _coerce(field: Any) -> str | None:
+ if isinstance(field, dict):
+ return str(field.get("value")) if field.get("value") is not None else None
+ return str(field) if field not in (None, "") else None
+
+ priority = _coerce(raw.get("priority"))
+ impact = _coerce(raw.get("impact")) or "3"
+
+ severity = _PRIORITY_SEVERITY.get(priority) if priority else None
+ if severity is None:
+ severity = _IMPACT_SEVERITY.get(impact, "low")
return {
"source": self.connector_id,
"external_id": raw.get("sys_id", ""),
"title": raw.get("short_description", "ServiceNow Incident"),
"description": raw.get("description", "")[:500],
- "severity": _IMPACT_SEVERITY.get(str(impact), "low"),
+ "severity": severity,
"src_ip": None,
"hostname": raw.get("cmdb_ci", {}).get("display_value") if isinstance(raw.get("cmdb_ci"), dict) else raw.get("cmdb_ci"),
"actor": raw.get("opened_by", {}).get("display_value") if isinstance(raw.get("opened_by"), dict) else raw.get("opened_by"),
@@ -191,7 +232,7 @@ class ServiceNowConnector(BaseConnector):
"short_description": title[:160], # ServiceNow short_description cap.
"description": description,
"impact": _SEVERITY_TO_IMPACT.get(severity, "2"),
- "urgency": _SEVERITY_TO_IMPACT.get(severity, "2"),
+ "urgency": _SEVERITY_TO_URGENCY.get(severity, "2"),
# Round-trip the AiSOC case identifier in ``correlation_id``
# so the inbound webhook can find us without a custom field.
"correlation_id": f"aisoc:{case_id}",
diff --git a/services/connectors/app/connectors/snyk.py b/services/connectors/app/connectors/snyk.py
index 4fdcd6432..2c7e670ff 100644
--- a/services/connectors/app/connectors/snyk.py
+++ b/services/connectors/app/connectors/snyk.py
@@ -15,12 +15,15 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
+# Snyk issues ship a native ``critical`` tier. AiSOC's 5-tier ladder
+# preserves it end-to-end so P1 supply-chain findings keep their original
+# priority.
_SEVERITY_MAP: dict[str, str] = {
"info": "info",
"low": "low",
"medium": "medium",
"high": "high",
- "critical": "high",
+ "critical": "critical",
}
diff --git a/services/connectors/app/connectors/sumo_logic.py b/services/connectors/app/connectors/sumo_logic.py
index 42d7c7ce0..7a0a0e00b 100644
--- a/services/connectors/app/connectors/sumo_logic.py
+++ b/services/connectors/app/connectors/sumo_logic.py
@@ -143,8 +143,11 @@ class SumoLogicConnector(BaseConnector):
return []
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Sumo Logic Cloud SIEM insights carry severity {info, low, medium,
+ # high, critical}. Accept critical so genuine critical insights
+ # survive AiSOC's five-tier severity ladder.
sev_raw = (raw.get("severity") or "").lower()
- sev = sev_raw if sev_raw in ("info", "low", "medium", "high") else "medium"
+ sev = sev_raw if sev_raw in ("info", "low", "medium", "high", "critical") else "medium"
return {
"source": "sumo_logic",
"category": "siem",
diff --git a/services/connectors/app/connectors/tailscale.py b/services/connectors/app/connectors/tailscale.py
index 069460d43..ced423414 100644
--- a/services/connectors/app/connectors/tailscale.py
+++ b/services/connectors/app/connectors/tailscale.py
@@ -42,6 +42,18 @@ logger = structlog.get_logger()
_BASE = "https://api.tailscale.com/api/v2"
+# Critical-severity actions: irreversible / total-takeover events on
+# the tailnet itself. These map to AiSOC's ``critical`` tier so they
+# fire the P1 SLA — losing ownership of a tailnet is functionally
+# equivalent to losing root on the network.
+_CRITICAL_SEVERITY_ACTIONS = frozenset(
+ {
+ "tailnet:transfer_ownership",
+ "tailnet:delete",
+ }
+)
+
+
# Audit event actions that we treat as HIGH severity. These are either
# reversible-but-dangerous changes that could be used for persistence /
# lateral movement, or irreversible destructive operations.
@@ -76,8 +88,6 @@ _HIGH_SEVERITY_ACTIONS = frozenset(
# DNS / MagicDNS
"dns:update",
# Admin
- "tailnet:transfer_ownership",
- "tailnet:delete",
"settings:update",
"logging:set_config",
# Webhooks (could be abused as C2 notification channel)
@@ -293,7 +303,10 @@ class TailscaleConnector(BaseConnector):
action: str = raw.get("action") or raw.get("type") or ""
actor: str = raw.get("actor", {}).get("loginName") or raw.get("actor", {}).get("id") or raw.get("user") or "unknown"
- if action in _HIGH_SEVERITY_ACTIONS:
+ if action in _CRITICAL_SEVERITY_ACTIONS:
+ # Irreversible total-takeover of the tailnet itself — P1.
+ severity = "critical"
+ elif action in _HIGH_SEVERITY_ACTIONS:
severity = "high"
elif action in _MEDIUM_SEVERITY_ACTIONS:
severity = "medium"
diff --git a/services/connectors/app/connectors/tenable.py b/services/connectors/app/connectors/tenable.py
index 524d881e1..7bbac2deb 100644
--- a/services/connectors/app/connectors/tenable.py
+++ b/services/connectors/app/connectors/tenable.py
@@ -111,8 +111,12 @@ class TenableConnector(BaseConnector):
return []
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Tenable.io exposes the CVSSv3 severity ladder (0=Info, 1=Low,
+ # 2=Medium, 3=High, 4=Critical). Mirror it directly into AiSOC's
+ # five-tier ladder so genuine Critical vulnerabilities are not
+ # silently downgraded to High.
sev_int = raw.get("severity")
- sev_map = {0: "info", 1: "low", 2: "medium", 3: "high", 4: "high"}
+ sev_map = {0: "info", 1: "low", 2: "medium", 3: "high", 4: "critical"}
sev = sev_map.get(sev_int, "info")
return {
"source": "tenable_io",
diff --git a/services/connectors/app/connectors/trellix_helix.py b/services/connectors/app/connectors/trellix_helix.py
index b99f99e0f..70f5154bd 100644
--- a/services/connectors/app/connectors/trellix_helix.py
+++ b/services/connectors/app/connectors/trellix_helix.py
@@ -143,8 +143,13 @@ class TrellixHelixConnector(BaseConnector):
return [self.normalize(e) for e in events]
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Trellix Helix alerts expose risk levels {critical, high, medium,
+ # low, info}. Mirror critical directly into AiSOC's five-tier
+ # ladder rather than collapsing it into high.
risk = (raw.get("risk") or "").lower()
- if risk in ("critical", "high"):
+ if risk == "critical":
+ severity = "critical"
+ elif risk == "high":
severity = "high"
elif risk == "medium":
severity = "medium"
diff --git a/services/connectors/app/connectors/trend_vision_one.py b/services/connectors/app/connectors/trend_vision_one.py
index 944d12fca..9236ba441 100644
--- a/services/connectors/app/connectors/trend_vision_one.py
+++ b/services/connectors/app/connectors/trend_vision_one.py
@@ -159,8 +159,14 @@ class TrendVisionOneConnector(BaseConnector):
return [self.normalize(e) for e in events]
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
+ # Trend Vision One workbench alerts and Observed Attack Techniques
+ # expose a 4- or 5-tier severity. Mirror critical → critical so the
+ # highest-impact detections survive into AiSOC's ladder instead of
+ # being downgraded to high.
sev_raw = (raw.get("severity") or raw.get("riskLevel") or "").lower()
- if sev_raw in ("critical", "high"):
+ if sev_raw == "critical":
+ severity = "critical"
+ elif sev_raw == "high":
severity = "high"
elif sev_raw == "medium":
severity = "medium"
diff --git a/services/connectors/app/connectors/wazuh.py b/services/connectors/app/connectors/wazuh.py
index 610cbfd70..b560c36a2 100644
--- a/services/connectors/app/connectors/wazuh.py
+++ b/services/connectors/app/connectors/wazuh.py
@@ -23,10 +23,13 @@ Wazuh rules carry a 0-15 ``level``; the official guidance maps roughly to:
* 0-3 — informational / system noise (login successes, decoder hits)
* 4-7 — low signal (failed sshd, non-malicious anomalies)
* 8-11 — suspicious (privilege change, unusual exec, FIM writes)
-* 12-15 — critical / attack (rootkit, exploit, multi-stage attack)
+* 12-14 — high (rootkit, exploit, IOC hit)
+* 15 — critical / attack (multi-stage attack, severe exploit)
-We collapse that into AiSOC's four-tier ladder (info | low | medium | high)
-the same way the connector platform spec requires for every vendor.
+We map that to AiSOC's 5-tier ladder (info | low | medium | high | critical)
+so Wazuh's hardest P1 alerts (level 15 — the only level Wazuh explicitly
+documents as "critical") keep their original priority rather than getting
+silently downgraded into ``high``.
API references
--------------
@@ -60,14 +63,18 @@ logger = structlog.get_logger()
# ---------------------------------------------------------------------------
# Severity mapping
#
-# Collapse the 0-15 Wazuh ladder into the AiSOC info | low | medium | high
-# tiers exactly as the connector platform spec requires (apps/docs has a
-# matching table in connectors/wazuh.md so operators can predict what they
-# will see). Boundaries are inclusive on the lower end.
+# Map the 0-15 Wazuh ladder into AiSOC's 5-tier
+# ``info | low | medium | high | critical`` ladder. Level 15 is the only
+# tier Wazuh explicitly documents as "critical / attack" so we surface it
+# at the AiSOC ``critical`` band; levels 12-14 stay at ``high``. The
+# matching operator-facing table lives in ``apps/docs/connectors/wazuh.md``
+# so SOC analysts can predict what they will see. Boundaries are inclusive
+# on the lower end.
# ---------------------------------------------------------------------------
_SEVERITY_BANDS: tuple[tuple[int, str], ...] = (
- (12, "high"), # 12-15
+ (15, "critical"), # 15
+ (12, "high"), # 12-14
(8, "medium"), # 8-11
(4, "low"), # 4-7
(0, "info"), # 0-3
diff --git a/services/connectors/app/connectors/wiz.py b/services/connectors/app/connectors/wiz.py
index 8584a3f43..877a6f183 100644
--- a/services/connectors/app/connectors/wiz.py
+++ b/services/connectors/app/connectors/wiz.py
@@ -15,12 +15,14 @@ from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Fiel
logger = structlog.get_logger()
+# Wiz issues ship a native ``CRITICAL`` tier. AiSOC's 5-tier ladder
+# preserves it end-to-end so P1 cloud findings keep their original priority.
_SEVERITY_MAP: dict[str, str] = {
"INFORMATIONAL": "info",
"LOW": "low",
"MEDIUM": "medium",
"HIGH": "high",
- "CRITICAL": "high",
+ "CRITICAL": "critical",
}
_ISSUES_QUERY = """
diff --git a/services/connectors/tests/test_auditd_connector.py b/services/connectors/tests/test_auditd_connector.py
index 47e89add2..f58765c13 100644
--- a/services/connectors/tests/test_auditd_connector.py
+++ b/services/connectors/tests/test_auditd_connector.py
@@ -376,15 +376,22 @@ def test_assemble_event_with_no_paths_has_path_none():
# ---------------------------------------------------------------------------
-def test_severity_critical_key_prefix_is_high():
- assert _severity_from_event({"key": "aisoc_critical_sudoers_write"}) == "high"
- assert _severity_from_event({"key": "aisoc_critical_ssh_config"}) == "high"
- assert _severity_from_event({"key": "aisoc_critical_authorized_keys"}) == "high"
+def test_severity_critical_key_prefix_is_critical():
+ # ``aisoc_critical_*`` keys mark the irreversible-or-equivalent
+ # mutations to host trust (sudoers, ssh keys, sshd config). In
+ # the 5-tier ladder these map directly to ``critical`` — the P1
+ # SLA tier — rather than collapsing to ``high``.
+ assert _severity_from_event({"key": "aisoc_critical_sudoers_write"}) == "critical"
+ assert _severity_from_event({"key": "aisoc_critical_ssh_config"}) == "critical"
+ assert _severity_from_event({"key": "aisoc_critical_authorized_keys"}) == "critical"
-def test_severity_priv_esc_key_prefix_is_medium():
- assert _severity_from_event({"key": "aisoc_priv_esc_module_load"}) == "medium"
- assert _severity_from_event({"key": "aisoc_priv_esc_ptrace"}) == "medium"
+def test_severity_priv_esc_key_prefix_is_high():
+ # Priv-esc primitives (module load, ptrace) are loud-but-survivable
+ # — ``high`` rather than ``critical``, which is reserved for
+ # full host-trust compromise.
+ assert _severity_from_event({"key": "aisoc_priv_esc_module_load"}) == "high"
+ assert _severity_from_event({"key": "aisoc_priv_esc_ptrace"}) == "high"
def test_severity_persistence_key_prefix_is_medium():
@@ -409,7 +416,7 @@ def test_severity_critical_prefix_wins_over_exec():
even though both are AiSOC-prefixed. Order in the prefix table
matters.
"""
- assert _severity_from_event({"key": "aisoc_critical_sudoers_write"}) == "high"
+ assert _severity_from_event({"key": "aisoc_critical_sudoers_write"}) == "critical"
def test_severity_falls_back_to_path_heuristic_when_no_key():
@@ -456,7 +463,7 @@ def test_severity_strips_quotes_around_key():
strips the quotes, but defensively the severity helper also handles
a stray quote prefix/suffix.
"""
- assert _severity_from_event({"key": '"aisoc_critical_sudoers_write"'}) == "high"
+ assert _severity_from_event({"key": '"aisoc_critical_sudoers_write"'}) == "critical"
# ---------------------------------------------------------------------------
@@ -543,7 +550,9 @@ def test_normalize_emits_canonical_endpoint_fields():
def test_normalize_severity_uses_key_prefix_mapping():
conn = _make_connector()
raw = {"key": "aisoc_critical_sudoers_write"}
- assert conn.normalize(raw)["severity"] == "high"
+ # The five-tier ladder mirrors aisoc_critical_* → ``critical`` so
+ # genuine P1 host-trust events fire the 15-minute MTTD SLA.
+ assert conn.normalize(raw)["severity"] == "critical"
def test_normalize_severity_falls_back_to_path_when_no_key():
@@ -945,11 +954,11 @@ async def test_fetch_alerts_ignores_since_seconds(tmp_path: Path):
@pytest.mark.asyncio
-async def test_end_to_end_aisoc_critical_event_surfaces_as_high(tmp_path: Path):
+async def test_end_to_end_aisoc_critical_event_surfaces_as_critical(tmp_path: Path):
"""A sudoers-write event using the AiSOC profile key must come
- out the other side as a high-severity event with auditd_key set,
+ out the other side as a critical-severity event with auditd_key set,
so the new ``linux-auditd-sudoers-tampering`` detection rule can
- fire on it.
+ fire on it. In the 5-tier ladder, sudoers tamper is a P1 incident.
"""
audit_log = tmp_path / "audit.log"
body = (
@@ -966,7 +975,7 @@ async def test_end_to_end_aisoc_critical_event_surfaces_as_high(tmp_path: Path):
result = await conn.fetch_alerts()
assert len(result) == 1
event = result[0]
- assert event["severity"] == "high"
+ assert event["severity"] == "critical"
assert event["auditd_key"] == "aisoc_critical_sudoers_write"
assert event["path"] == "/etc/sudoers"
assert event["host"] == "prod-web-01"
@@ -975,10 +984,11 @@ async def test_end_to_end_aisoc_critical_event_surfaces_as_high(tmp_path: Path):
@pytest.mark.asyncio
-async def test_end_to_end_module_load_event_surfaces_as_medium(tmp_path: Path):
+async def test_end_to_end_module_load_event_surfaces_as_high(tmp_path: Path):
"""Kernel module load via syscall=175 (init_module) tagged with
- ``aisoc_priv_esc_module_load`` should come out as ``medium`` so
- the ``linux-auditd-kernel-module-load`` rule catches it.
+ ``aisoc_priv_esc_module_load`` should come out as ``high`` so
+ the ``linux-auditd-kernel-module-load`` rule catches it. Priv-esc
+ primitives are high (analyst-eyes) rather than critical (P1).
"""
audit_log = tmp_path / "audit.log"
body = (
@@ -994,7 +1004,7 @@ async def test_end_to_end_module_load_event_surfaces_as_medium(tmp_path: Path):
result = await conn.fetch_alerts()
assert len(result) == 1
event = result[0]
- assert event["severity"] == "medium"
+ assert event["severity"] == "high"
assert event["syscall"] == "init_module"
assert event["auditd_key"] == "aisoc_priv_esc_module_load"
assert event["exe"] == "/sbin/insmod"
diff --git a/services/connectors/tests/test_aws_cloudtrail.py b/services/connectors/tests/test_aws_cloudtrail.py
index bb151332a..808998e5b 100644
--- a/services/connectors/tests/test_aws_cloudtrail.py
+++ b/services/connectors/tests/test_aws_cloudtrail.py
@@ -4,7 +4,7 @@ Unit tests for ``AWSCloudTrailConnector``.
Coverage:
* schema sanity (region defaulted, optional creds, secret marking,
``event_names`` field present and optional)
- * ``_event_severity()`` bucketing (high / medium / low + errorCode bump)
+ * ``_event_severity()`` bucketing (critical / high / medium / low + errorCode bump)
* ``_parse_event_names()`` tri-state parsing (default / wildcard / list)
* ``normalize()`` field extraction (CloudTrailEvent JSON unpack,
src_ip suppression for AWS-internal callers, severity flow)
@@ -96,11 +96,15 @@ def test_parse_event_names_strips_empty_segments():
@pytest.mark.parametrize(
"event_name,expected",
[
- # Trail/detection tamper → high
- ("DeleteTrail", "high"),
- ("StopLogging", "high"),
- ("DisableSecurityHub", "high"),
- ("ScheduleKeyDeletion", "high"),
+ # Visibility kill switches / irreversible takeover → critical (P1)
+ ("DeleteTrail", "critical"),
+ ("StopLogging", "critical"),
+ ("DisableSecurityHub", "critical"),
+ ("ScheduleKeyDeletion", "critical"),
+ # Trail/detection tamper, root mail change, org-level changes → high
+ ("UpdateTrail", "high"),
+ ("DeleteFlowLogs", "high"),
+ ("ChangeRootMail", "high"),
# Mutating but not catastrophic → medium
("CreateAccessKey", "medium"),
("AttachUserPolicy", "medium"),
@@ -121,8 +125,10 @@ def test_event_severity_bumps_on_error_code():
# — bump the severity one tier when ``errorCode`` is present.
assert _event_severity("CreateAccessKey", "AccessDenied") == "high"
assert _event_severity("ListAccessKeys", "AccessDenied") == "medium"
- # Already-high stays high — no overflow tier.
- assert _event_severity("DeleteTrail", "AccessDenied") == "high"
+ # Already-high stays high (no overflow tier on the high baseline).
+ assert _event_severity("UpdateTrail", "AccessDenied") == "high"
+ # Already-critical stays critical — no escalation past P1.
+ assert _event_severity("DeleteTrail", "AccessDenied") == "critical"
def test_event_severity_unknown_event_defaults_to_medium():
@@ -246,7 +252,8 @@ def test_normalize_handles_missing_cloudtrail_event_payload():
out = connector.normalize(raw)
assert out["external_id"] == "stripped-1"
assert out["event_name"] == "DeleteTrail"
- assert out["severity"] == "high"
+ # DeleteTrail silences the audit trail itself — classified as P1 critical.
+ assert out["severity"] == "critical"
# Fallback region from the connector instance config when the
# detail payload is absent.
assert out["aws_region"] == "us-east-1"
@@ -368,7 +375,8 @@ async def test_fetch_alerts_iterates_allow_list_one_call_per_event_name():
severities = {r["external_id"]: r["severity"] for r in results}
assert severities["console-1"] == "medium"
assert severities["key-1"] == "medium"
- assert severities["trail-1"] == "high"
+ # DeleteTrail is a visibility kill switch — P1 critical.
+ assert severities["trail-1"] == "critical"
@pytest.mark.asyncio
diff --git a/services/connectors/tests/test_aws_guardduty.py b/services/connectors/tests/test_aws_guardduty.py
index ef110288a..5c8da5619 100644
--- a/services/connectors/tests/test_aws_guardduty.py
+++ b/services/connectors/tests/test_aws_guardduty.py
@@ -52,7 +52,13 @@ def test_guardduty_schema_category_is_cloud():
@pytest.mark.parametrize(
"score,expected",
[
- (9.5, "high"), # GuardDuty's "critical" tier collapses to high
+ # GuardDuty's 9.0-10.0 band maps to AiSOC's ``critical`` tier
+ # (P1 SLA) — these are the highest-confidence active-threat
+ # findings and warrant the 15-minute MTTD target.
+ (10.0, "critical"),
+ (9.5, "critical"),
+ (9.0, "critical"),
+ (8.9, "high"),
(8.0, "high"),
(7.0, "high"),
(6.9, "medium"),
diff --git a/services/connectors/tests/test_gcp_connectors.py b/services/connectors/tests/test_gcp_connectors.py
index 9376737b6..a5f604401 100644
--- a/services/connectors/tests/test_gcp_connectors.py
+++ b/services/connectors/tests/test_gcp_connectors.py
@@ -189,7 +189,10 @@ def test_cloud_audit_normalize_critical_log_severity_is_high(fake_sa_json):
# ---------------------------------------------------------------------------
-def test_scc_normalize_critical_collapses_to_high(fake_sa_json):
+def test_scc_normalize_critical_preserves_critical(fake_sa_json):
+ # SCC CRITICAL findings mirror directly into AiSOC's ``critical``
+ # tier (P1, 15-minute MTTD SLA) — the highest-impact GCP findings
+ # must not be silently downgraded.
connector = GCPSCCConnector(_ORG, fake_sa_json)
raw = {
"finding": {
@@ -207,7 +210,7 @@ def test_scc_normalize_critical_collapses_to_high(fake_sa_json):
}
out = connector.normalize(raw)
assert out["source"] == "gcp_scc"
- assert out["severity"] == "high", "SCC CRITICAL collapses to AiSOC 'high' since downstream pipelines expect that vocabulary"
+ assert out["severity"] == "critical"
assert out["title"] == "MALWARE_BAD_DOMAIN"
assert out["actor_email"] == "[email protected]"
assert out["resource_type"] == "google.compute.Instance"
diff --git a/services/connectors/tests/test_kubernetes_audit.py b/services/connectors/tests/test_kubernetes_audit.py
index 5033ecf2b..65e6e296b 100644
--- a/services/connectors/tests/test_kubernetes_audit.py
+++ b/services/connectors/tests/test_kubernetes_audit.py
@@ -88,45 +88,55 @@ def test_capabilities_advertises_pull_audit_and_alerts():
# ---------------------------------------------------------------------------
-def test_severity_pod_exec_is_high():
+def test_severity_pod_exec_is_critical():
+ # Interactive shell into a pod is functionally equivalent to a
+ # P1 incident on that pod — map to AiSOC's ``critical`` tier.
event = {
"verb": "create",
"objectRef": {"resource": "pods", "subresource": "exec"},
"responseStatus": {"code": 101},
}
- assert _classify_severity(event) == "high"
+ assert _classify_severity(event) == "critical"
-def test_severity_pod_attach_is_high():
+def test_severity_pod_attach_is_critical():
+ # ``attach`` is the streaming-IO sibling of ``exec`` — same blast
+ # radius, same P1 critical tier.
event = {
"verb": "create",
"objectRef": {"resource": "pods", "subresource": "attach"},
}
- assert _classify_severity(event) == "high"
+ assert _classify_severity(event) == "critical"
-def test_severity_pod_portforward_is_high():
+def test_severity_pod_portforward_is_critical():
+ # ``portforward`` punches a tunnel to a pod-local port — same
+ # P1 blast radius as ``exec`` / ``attach``.
event = {
"verb": "create",
"objectRef": {"resource": "pods", "subresource": "portforward"},
}
- assert _classify_severity(event) == "high"
+ assert _classify_severity(event) == "critical"
-def test_severity_impersonate_is_high():
+def test_severity_impersonate_is_critical():
+ # ``impersonate`` is direct identity hand-off — anyone who can
+ # impersonate cluster-admin owns the cluster. Critical / P1.
event = {
"verb": "impersonate",
"objectRef": {"resource": "users"},
}
- assert _classify_severity(event) == "high"
+ assert _classify_severity(event) == "critical"
-def test_severity_clusterrolebinding_create_is_high():
+def test_severity_clusterrolebinding_create_is_critical():
+ # Writes against the RBAC graph itself are the most common
+ # post-foothold takeover primitive — P1 critical.
event = {
"verb": "create",
"objectRef": {"resource": "clusterrolebindings"},
}
- assert _classify_severity(event) == "high"
+ assert _classify_severity(event) == "critical"
def test_severity_secret_create_is_high():
@@ -260,7 +270,9 @@ def test_normalize_extracts_canonical_fields():
assert norm["severity"] == "low"
-def test_normalize_pod_exec_routes_to_high_severity_and_clear_title():
+def test_normalize_pod_exec_routes_to_critical_severity_and_clear_title():
+ # End-to-end: a pod ``exec`` event must surface as ``critical`` so
+ # it lands in the P1 lane (15-minute MTTD SLA).
conn = _make_connector()
raw = {
"auditID": "exec-1",
@@ -277,7 +289,7 @@ def test_normalize_pod_exec_routes_to_high_severity_and_clear_title():
"stageTimestamp": "2026-05-10T11:00:00Z",
}
norm = conn.normalize(raw)
- assert norm["severity"] == "high"
+ assert norm["severity"] == "critical"
assert norm["k8s_subresource"] == "exec"
# The title should be obviously parseable by a human eyeballing
# the inbox — verb, resource, subresource, target.
diff --git a/services/connectors/tests/test_orca.py b/services/connectors/tests/test_orca.py
index f1cec0a1b..cf9c45ce1 100644
--- a/services/connectors/tests/test_orca.py
+++ b/services/connectors/tests/test_orca.py
@@ -29,8 +29,10 @@ def test_capabilities():
assert Capability.PULL_ALERTS in caps
-def test_normalize_severity_collapse_hazardous():
- """Orca's hazardous tier collapses into AiSOC high."""
+def test_normalize_severity_hazardous_is_critical():
+ """Orca's ``hazardous`` tier (also known as ``imminent_compromise``)
+ represents active exploitation and maps to AiSOC's P1 ``critical`` tier
+ so it lands in the 15-minute MTTD lane."""
conn = OrcaConnector(api_token="t")
raw = {
"alert_id": "alert-1",
@@ -48,17 +50,19 @@ def test_normalize_severity_collapse_hazardous():
assert norm["source"] == "orca"
assert norm["category"] == "cloud"
assert norm["external_id"] == "alert-1"
- assert norm["severity"] == "high"
+ assert norm["severity"] == "critical"
assert norm["hostname"] == "my-bucket"
assert norm["cloud_platform"] == "aws"
assert norm["cloud_region"] == "us-east-1"
assert norm["raw_event"] is raw
-def test_normalize_severity_collapse_critical():
+def test_normalize_severity_critical_preserves_critical():
+ # Orca's ``critical`` tier mirrors directly into AiSOC's ``critical`` —
+ # never silently downgrade a P1 finding.
conn = OrcaConnector(api_token="t")
raw = {"alert_id": "c1", "state": {"severity": "critical"}}
- assert conn.normalize(raw)["severity"] == "high"
+ assert conn.normalize(raw)["severity"] == "critical"
def test_normalize_severity_informational():
@@ -156,7 +160,9 @@ async def test_fetch_alerts_data_envelope():
alerts = await conn.fetch_alerts(since_seconds=300)
assert len(alerts) == 2
assert alerts[0]["external_id"] == "a1"
- assert alerts[0]["severity"] == "high"
+ # Orca's ``critical`` flows straight through to AiSOC's ``critical`` —
+ # no collapse to ``high``.
+ assert alerts[0]["severity"] == "critical"
assert alerts[1]["severity"] == "medium"
diff --git a/services/connectors/tests/test_prisma_cloud.py b/services/connectors/tests/test_prisma_cloud.py
index 13ee6b5fe..06d98d80a 100644
--- a/services/connectors/tests/test_prisma_cloud.py
+++ b/services/connectors/tests/test_prisma_cloud.py
@@ -53,7 +53,10 @@ def test_prisma_cloud_compute_url_is_optional():
# ---------------------------------------------------------------------------
-def test_normalize_collapses_critical_into_high():
+def test_normalize_critical_preserves_critical():
+ # Prisma Cloud's ``critical`` policy severity must surface as AiSOC
+ # ``critical`` (P1, 15-minute MTTD SLA) — never silently downgrade to
+ # ``high``, since AiSOC now exposes a dedicated 5th tier for P1 work.
connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)
raw = {
"id": "alert-1",
@@ -72,8 +75,8 @@ def test_normalize_collapses_critical_into_high():
}
out = connector.normalize(raw)
assert out["source"] == "prisma_cloud"
- assert out["severity"] == "high", (
- "Prisma Cloud 'critical' must collapse into AiSOC 'high'; AiSOC does not expose a separate critical band"
+ assert out["severity"] == "critical", (
+ "Prisma Cloud 'critical' must map directly to AiSOC 'critical' so P1 SLAs apply"
)
assert out["external_id"] == "alert-1"
assert out["title"] == "Public S3 bucket"
diff --git a/services/connectors/tests/test_saas_connectors.py b/services/connectors/tests/test_saas_connectors.py
index 13f0e4bd0..8188cdb5f 100644
--- a/services/connectors/tests/test_saas_connectors.py
+++ b/services/connectors/tests/test_saas_connectors.py
@@ -670,7 +670,11 @@ def test_github_normalize_routine_action_is_info():
assert out["severity"] == "info"
-def test_github_normalize_code_scanning_critical_collapses_to_high():
+def test_github_normalize_code_scanning_critical_preserves_critical():
+ # GitHub Code Scanning ``critical`` security_severity_level represents
+ # the highest severity findings (e.g. SQL injection, RCE) and maps
+ # directly to AiSOC's ``critical`` (P1, 15-minute MTTD SLA) — never
+ # collapse to ``high`` since AiSOC exposes a dedicated P1 tier.
connector = GitHubConnector(_ORG, _TOKEN)
raw = {
"_aisoc_stream": "code_scanning",
@@ -687,7 +691,7 @@ def test_github_normalize_code_scanning_critical_collapses_to_high():
"most_recent_instance": {"location": {"path": "src/db.py"}},
}
out = connector.normalize(raw)
- assert out["severity"] == "high"
+ assert out["severity"] == "critical"
assert out["external_id"] == "code-scanning-42"
assert out["title"].startswith("Code Scanning:")
assert out["event_type"] == "github.code_scanning.py/sql-injection"
diff --git a/services/connectors/tests/test_wazuh_connector.py b/services/connectors/tests/test_wazuh_connector.py
index f4e3f3ded..3c7e46d86 100644
--- a/services/connectors/tests/test_wazuh_connector.py
+++ b/services/connectors/tests/test_wazuh_connector.py
@@ -65,13 +65,18 @@ def test_wazuh_capabilities_cover_pull_query_search_pivot():
(8, "medium"),
(11, "medium"),
(12, "high"),
- (15, "high"),
+ (14, "high"),
+ # Wazuh level 15 is the maximum band and represents the most
+ # severe attack signatures — it now maps to AiSOC's ``critical``
+ # (P1, 15-minute MTTD SLA) so it lands in the top lane.
+ (15, "critical"),
# Out-of-band / weird inputs — must not raise.
(None, "info"),
("not-a-number", "info"),
("9", "medium"),
(-3, "info"),
- (99, "high"),
+ # Values above 15 are clamped to the top tier (``critical``).
+ (99, "critical"),
],
)
def test_severity_band_collapse(level, expected):