mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-11-24 08:35:46 +08:00
feat: T3.5 business-context rule engine + Monaco editor (wip)
YAML rule definitions parsed into an in-memory DAG and evaluated post-fusion / pre-triage. CRUD endpoints under /v1/business-context/rules. Settings UI uses Monaco YAML editor with live preview against the last 100 alerts. Feature flagged behind AISOC_BUSINESS_CONTEXT_ENABLED. Refs: AiSOC v8.0 wave-2 (4hr parallel session, 2026-05-14) Signed-off-by: Prince Sinha <prince.sinha@cyble.com>
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Business Context settings — composed view.
|
||||
*
|
||||
* Owns the Monaco YAML editor + rule-builder side-panel + live preview.
|
||||
* Talks to the API directly via ``fetch`` (rather than a typed client
|
||||
* helper) so this whole feature lives in one directory and we can ship
|
||||
* the explicit-paths-only commit cleanly.
|
||||
*/
|
||||
import dynamic from "next/dynamic";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
type PreviewResponse,
|
||||
type PreviewRow,
|
||||
type RulesEnvelope,
|
||||
loadRules,
|
||||
previewRules,
|
||||
saveRules,
|
||||
} from "./client";
|
||||
import { RuleBuilder } from "./RuleBuilder";
|
||||
import { PreviewTable } from "./PreviewTable";
|
||||
|
||||
const MonacoEditor = dynamic(() => import("@monaco-editor/react"), {
|
||||
ssr: false,
|
||||
loading: () => (
|
||||
<div className="flex h-full items-center justify-center text-sm text-slate-500">
|
||||
Loading editor...
|
||||
</div>
|
||||
),
|
||||
});
|
||||
|
||||
const STARTER_YAML = `# Business context rules — YAML.
|
||||
# Each rule mutates a fused alert before it reaches the triage agent.
|
||||
# Supported actions: set_severity, route_to, tag, suppress.
|
||||
#
|
||||
# Hit "Save" to apply; the live preview re-runs automatically on every
|
||||
# keystroke (debounced) so you can see the impact on your last 50
|
||||
# alerts before committing.
|
||||
rules:
|
||||
- id: prod-iam-during-business-hours
|
||||
description: Wake tier-2 for any prod IAM touch during business hours.
|
||||
priority: 10
|
||||
when:
|
||||
all:
|
||||
- field: alert.target.tag
|
||||
op: eq
|
||||
value: prod
|
||||
- field: alert.time.is_business_hours
|
||||
op: eq
|
||||
value: true
|
||||
then:
|
||||
set_severity: critical
|
||||
route_to: tier2
|
||||
tag: business-hours-prod
|
||||
`;
|
||||
|
||||
export function BusinessContextSettings() {
|
||||
const [yaml, setYaml] = useState<string>(STARTER_YAML);
|
||||
const [envelope, setEnvelope] = useState<RulesEnvelope | null>(null);
|
||||
const [preview, setPreview] = useState<PreviewResponse | null>(null);
|
||||
const [previewError, setPreviewError] = useState<string | null>(null);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [previewing, setPreviewing] = useState(false);
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Initial load — pull whatever the tenant currently has saved.
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
void (async () => {
|
||||
try {
|
||||
const env = await loadRules();
|
||||
if (cancelled) return;
|
||||
setEnvelope(env);
|
||||
if (env.yaml.trim().length > 0) {
|
||||
setYaml(env.yaml);
|
||||
}
|
||||
} catch (err) {
|
||||
if (cancelled) return;
|
||||
setSaveError((err as Error).message);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Debounced preview — fires 300ms after the editor stops changing.
|
||||
useEffect(() => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
debounceRef.current = setTimeout(() => {
|
||||
void runPreview(yaml);
|
||||
}, 300);
|
||||
return () => {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current);
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [yaml]);
|
||||
|
||||
const runPreview = useCallback(async (currentYaml: string) => {
|
||||
setPreviewing(true);
|
||||
setPreviewError(null);
|
||||
try {
|
||||
const resp = await previewRules(currentYaml);
|
||||
setPreview(resp);
|
||||
} catch (err) {
|
||||
setPreviewError((err as Error).message);
|
||||
setPreview(null);
|
||||
} finally {
|
||||
setPreviewing(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
try {
|
||||
const env = await saveRules(yaml);
|
||||
setEnvelope(env);
|
||||
setDirty(false);
|
||||
} catch (err) {
|
||||
setSaveError((err as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [yaml]);
|
||||
|
||||
const handleAppendRule = useCallback((snippet: string) => {
|
||||
setYaml((prev) => {
|
||||
const trimmed = prev.replace(/\s+$/, "");
|
||||
// If the document already has a `rules:` list, append under it;
|
||||
// otherwise wrap the snippet in a `rules:` list of its own so the
|
||||
// resulting YAML stays a single document the parser accepts.
|
||||
if (/^\s*rules:/m.test(trimmed)) {
|
||||
return `${trimmed}\n${snippet}\n`;
|
||||
}
|
||||
return `rules:\n${snippet}\n`;
|
||||
});
|
||||
setDirty(true);
|
||||
}, []);
|
||||
|
||||
const summaryLine = useMemo(() => {
|
||||
if (!preview) return null;
|
||||
const { sample_size, changed_count, suppressed_count, elapsed_ms } = preview;
|
||||
if (sample_size === 0) {
|
||||
return "No alerts available for the dry-run preview yet.";
|
||||
}
|
||||
return (
|
||||
`${changed_count} of ${sample_size} sample alerts would be mutated` +
|
||||
(suppressed_count > 0 ? ` (${suppressed_count} suppressed)` : "") +
|
||||
` — preview ran in ${elapsed_ms.toFixed(1)} ms.`
|
||||
);
|
||||
}, [preview]);
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col gap-4 p-6">
|
||||
<header className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-slate-100">
|
||||
Business Context Rules
|
||||
</h1>
|
||||
<p className="max-w-2xl text-sm text-slate-400">
|
||||
Encode your operational reality between fusion and the triage
|
||||
agent — bump severity for prod, route AWS alerts to the cloud
|
||||
team, suppress alerts during a known maintenance window. Rules
|
||||
run in priority order; the last matching action wins.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{envelope ? (
|
||||
<span className="text-xs text-slate-500">
|
||||
version {envelope.version} · saved{" "}
|
||||
{new Date(envelope.updated_at).toLocaleTimeString()}
|
||||
</span>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSave}
|
||||
disabled={saving}
|
||||
className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-indigo-500 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
{saving ? "Saving..." : dirty ? "Save changes" : "Save"}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{saveError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="rounded-md border border-rose-500/40 bg-rose-950/40 p-3 text-sm text-rose-200"
|
||||
>
|
||||
{saveError}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="grid flex-1 grid-cols-1 gap-4 lg:grid-cols-3">
|
||||
<section className="col-span-2 flex min-h-[420px] flex-col rounded-md border border-slate-700 bg-slate-950">
|
||||
<div className="border-b border-slate-800 px-3 py-2 text-xs font-medium uppercase tracking-wide text-slate-500">
|
||||
YAML editor
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<MonacoEditor
|
||||
language="yaml"
|
||||
theme="vs-dark"
|
||||
value={yaml}
|
||||
options={{
|
||||
fontSize: 13,
|
||||
minimap: { enabled: false },
|
||||
automaticLayout: true,
|
||||
tabSize: 2,
|
||||
}}
|
||||
onChange={(value) => {
|
||||
setYaml(value ?? "");
|
||||
setDirty(true);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="flex min-h-[420px] flex-col rounded-md border border-slate-700 bg-slate-950">
|
||||
<div className="border-b border-slate-800 px-3 py-2 text-xs font-medium uppercase tracking-wide text-slate-500">
|
||||
Rule builder
|
||||
</div>
|
||||
<div className="flex-1 overflow-auto p-3">
|
||||
<RuleBuilder onAppend={handleAppendRule} />
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section className="rounded-md border border-slate-700 bg-slate-950">
|
||||
<header className="flex items-center justify-between border-b border-slate-800 px-3 py-2">
|
||||
<div className="text-xs font-medium uppercase tracking-wide text-slate-500">
|
||||
Live preview
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-xs text-slate-400">
|
||||
{previewing ? "Recomputing..." : summaryLine}
|
||||
</div>
|
||||
</header>
|
||||
<div className="max-h-[360px] overflow-auto">
|
||||
{previewError ? (
|
||||
<div className="p-3 text-sm text-rose-300">{previewError}</div>
|
||||
) : preview ? (
|
||||
<PreviewTable rows={preview.rows} />
|
||||
) : (
|
||||
<div className="p-3 text-sm text-slate-500">
|
||||
Edit the YAML above to see a before/after diff against your last
|
||||
50 alerts.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type { PreviewRow };
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* /settings/business-context — Track 3, T3.5.
|
||||
*
|
||||
* Operator-facing editor for the YAML rule set that runs between the
|
||||
* fusion pipeline and the triage agent. Three panels:
|
||||
*
|
||||
* 1. Monaco YAML editor on the left (the source of truth).
|
||||
* 2. Rule-builder side-panel on the right (helper UI for analysts
|
||||
* who don't speak YAML; lets them assemble a rule and have it
|
||||
* appended to the editor).
|
||||
* 3. Live preview row at the bottom (POSTs the current YAML +
|
||||
* either supplied alerts or "fetch the last 50" to /preview and
|
||||
* renders before/after).
|
||||
*
|
||||
* The editor is debounced 300ms before it triggers a preview re-run
|
||||
* so an analyst typing a long predicate doesn't spam the API.
|
||||
*/
|
||||
import type { Metadata } from "next";
|
||||
|
||||
import { BusinessContextSettings } from "./BusinessContextSettings";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Business Context Rules | Settings | AiSOC",
|
||||
};
|
||||
|
||||
export default function BusinessContextSettingsPage() {
|
||||
return <BusinessContextSettings />;
|
||||
}
|
||||
@@ -0,0 +1,639 @@
|
||||
"""Business Context Rules CRUD + dry-run preview — Track 3, T3.5.
|
||||
|
||||
A *business context rule* is a YAML predicate the operator authors on
|
||||
``/settings/business-context``. It runs between the fusion pipeline
|
||||
and the triage agent, mutating an alert (severity bump, route to a
|
||||
specific tier, suppress, tag) based on customer-supplied context like
|
||||
"prod tag during business hours".
|
||||
|
||||
Endpoints
|
||||
---------
|
||||
|
||||
* ``GET /v1/business-context/rules`` — return the tenant's
|
||||
rule set (YAML source + parsed view + engine version).
|
||||
* ``POST /v1/business-context/rules`` — replace the tenant's
|
||||
whole rule set with a new YAML document. Returns the parsed result so
|
||||
the editor can render the engine's view of what it just persisted.
|
||||
* ``PUT /v1/business-context/rules/{rule_id}`` — patch a single rule
|
||||
in-place; convenience for the side-panel rule builder which edits one
|
||||
rule at a time.
|
||||
* ``DELETE /v1/business-context/rules/{rule_id}`` — delete one rule.
|
||||
* ``POST /v1/business-context/rules/preview`` — dry-run a candidate
|
||||
YAML against an alert sample (or the last-100 demo set) without
|
||||
persisting anything. Returns one before/after row per alert.
|
||||
|
||||
Persistence story
|
||||
-----------------
|
||||
|
||||
v1 of T3.5 keeps the parsed rule set in the
|
||||
:class:`BusinessContextEngine` process singleton. A
|
||||
``# TODO(T3.5-followup)`` is wired in :func:`_persist_for` for the
|
||||
``aisoc_business_context_rule_sets`` migration that adds JSONB +
|
||||
versioning. Keeping persistence to a single helper means swapping in
|
||||
the DB-backed store is a one-file change.
|
||||
|
||||
Feature flag
|
||||
------------
|
||||
|
||||
The hot-path hook (post-fusion → pre-triage) is gated by
|
||||
``AISOC_BUSINESS_CONTEXT_ENABLED`` (default on, tenant-overridable
|
||||
via the ``business_context_enabled`` column on ``tenants``). The CRUD
|
||||
endpoints themselves are *always* enabled — operators need to be able
|
||||
to author rules even on a tenant where the hook is disabled.
|
||||
|
||||
Authorisation
|
||||
-------------
|
||||
|
||||
Read = ``settings:read``; mutating endpoints require ``settings:write``,
|
||||
matching the autonomy-policy admin surface. Tier-1 analysts cannot edit
|
||||
rules; the rule set governs how their alerts are routed, which is a
|
||||
tenant-admin concern.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
import structlog
|
||||
import yaml
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.api.v1.deps import AuthUser, DBSession
|
||||
from app.services.business_context import (
|
||||
BusinessContextRule,
|
||||
RuleParseError,
|
||||
load_rules_from_yaml,
|
||||
)
|
||||
from app.services.business_context.engine import (
|
||||
BusinessContextEngine,
|
||||
EngineSnapshot,
|
||||
get_engine,
|
||||
)
|
||||
|
||||
logger = structlog.get_logger()
|
||||
|
||||
router = APIRouter(prefix="/business-context", tags=["business-context"])
|
||||
|
||||
# Reasonable upper bounds — a tenant with > 200 rules has bigger
|
||||
# problems than a server-side cap, but the limit keeps a runaway YAML
|
||||
# blob from quietly degrading the dry-run preview latency.
|
||||
_MAX_YAML_BYTES = 256 * 1024 # 256 KB of YAML is plenty for hundreds of rules.
|
||||
_MAX_PREVIEW_ALERTS = 200
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Pydantic wire shapes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class RuleConditionWire(BaseModel):
|
||||
"""Mirror of :class:`RuleCondition` for the wire / OpenAPI shape."""
|
||||
|
||||
field: str | None = None
|
||||
op: str | None = None
|
||||
value: Any = None
|
||||
logical: str | None = None
|
||||
children: list["RuleConditionWire"] = Field(default_factory=list)
|
||||
|
||||
|
||||
class RuleActionWire(BaseModel):
|
||||
set_severity: str | None = None
|
||||
route_to: str | None = None
|
||||
tag: str | None = None
|
||||
suppress: bool = False
|
||||
|
||||
|
||||
class RuleWire(BaseModel):
|
||||
id: str
|
||||
description: str = ""
|
||||
enabled: bool = True
|
||||
priority: int = 100
|
||||
when: RuleConditionWire
|
||||
then: RuleActionWire
|
||||
|
||||
|
||||
class RulesEnvelope(BaseModel):
|
||||
"""Response payload for ``GET /rules``.
|
||||
|
||||
The editor needs *both* the YAML source (so Monaco can show
|
||||
formatting + comments) and the parsed view (so the rule-builder
|
||||
side-panel can render structured forms). ``version`` is the
|
||||
engine snapshot version the parsed view came from — a monotonic
|
||||
integer the UI uses to detect "someone else saved while I was
|
||||
editing".
|
||||
"""
|
||||
|
||||
tenant_id: str
|
||||
version: int
|
||||
yaml: str
|
||||
rules: list[RuleWire]
|
||||
enabled: bool
|
||||
updated_at: str
|
||||
|
||||
|
||||
class ReplaceRulesRequest(BaseModel):
|
||||
yaml: str = Field(..., max_length=_MAX_YAML_BYTES)
|
||||
|
||||
|
||||
class UpdateRuleRequest(BaseModel):
|
||||
yaml: str = Field(..., max_length=_MAX_YAML_BYTES)
|
||||
|
||||
|
||||
class PreviewRequest(BaseModel):
|
||||
yaml: str = Field(..., max_length=_MAX_YAML_BYTES)
|
||||
alerts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
"""Optional alert sample. When empty, the endpoint pulls the last
|
||||
50 alerts off ``aisoc_alerts``; when non-empty, the supplied
|
||||
alerts are used verbatim (useful for the editor's "preview against
|
||||
these three illustrative alerts" power-user flow).
|
||||
"""
|
||||
|
||||
|
||||
class PreviewRow(BaseModel):
|
||||
alert_id: str
|
||||
matched_rule_ids: list[str]
|
||||
before: dict[str, Any]
|
||||
after: dict[str, Any]
|
||||
suppressed: bool
|
||||
changed: bool
|
||||
|
||||
|
||||
class PreviewResponse(BaseModel):
|
||||
sample_size: int
|
||||
changed_count: int
|
||||
suppressed_count: int
|
||||
elapsed_ms: float
|
||||
rows: list[PreviewRow]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _wire_condition(cond: Any) -> RuleConditionWire:
|
||||
return RuleConditionWire(
|
||||
field=cond.field,
|
||||
op=cond.op,
|
||||
value=cond.value,
|
||||
logical=cond.logical,
|
||||
children=[_wire_condition(c) for c in cond.children],
|
||||
)
|
||||
|
||||
|
||||
def _wire_rule(rule: BusinessContextRule) -> RuleWire:
|
||||
return RuleWire(
|
||||
id=rule.id,
|
||||
description=rule.description,
|
||||
enabled=rule.enabled,
|
||||
priority=rule.priority,
|
||||
when=_wire_condition(rule.when),
|
||||
then=RuleActionWire(
|
||||
set_severity=rule.then.set_severity,
|
||||
route_to=rule.then.route_to,
|
||||
tag=rule.then.tag,
|
||||
suppress=rule.then.suppress,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _envelope(
|
||||
tenant_id: UUID,
|
||||
snapshot: EngineSnapshot,
|
||||
*,
|
||||
yaml_text: str,
|
||||
enabled: bool,
|
||||
updated_at: datetime,
|
||||
) -> RulesEnvelope:
|
||||
return RulesEnvelope(
|
||||
tenant_id=str(tenant_id),
|
||||
version=snapshot.version,
|
||||
yaml=yaml_text,
|
||||
rules=[_wire_rule(r) for r in snapshot.rules],
|
||||
enabled=enabled,
|
||||
updated_at=updated_at.isoformat(),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# In-memory persistence shim
|
||||
# ---------------------------------------------------------------------------
|
||||
#
|
||||
# v1 keeps the YAML source + the "engine enabled?" boolean in a
|
||||
# per-process dict. Swapping this out for the JSONB-backed
|
||||
# ``aisoc_business_context_rule_sets`` table is the
|
||||
# T3.5-followup migration; isolating the read/write here means the
|
||||
# call sites in the endpoint don't need to change when that lands.
|
||||
|
||||
|
||||
_RuleStoreEntry = dict[str, Any]
|
||||
_rule_store: dict[UUID, _RuleStoreEntry] = {}
|
||||
|
||||
|
||||
def _persist_for(tenant_id: UUID, *, yaml_text: str, enabled: bool) -> datetime:
|
||||
now = datetime.now(UTC)
|
||||
_rule_store[tenant_id] = {
|
||||
"yaml": yaml_text,
|
||||
"enabled": enabled,
|
||||
"updated_at": now,
|
||||
}
|
||||
return now
|
||||
|
||||
|
||||
def _load_for(tenant_id: UUID) -> _RuleStoreEntry:
|
||||
entry = _rule_store.get(tenant_id)
|
||||
if entry is None:
|
||||
return {
|
||||
"yaml": "",
|
||||
"enabled": True, # default-on per spec
|
||||
"updated_at": datetime.now(UTC),
|
||||
}
|
||||
return entry
|
||||
|
||||
|
||||
def _reset_store_for_tests() -> None:
|
||||
"""Clear in-process state — only safe in test code."""
|
||||
_rule_store.clear()
|
||||
|
||||
|
||||
def _engine() -> BusinessContextEngine:
|
||||
return get_engine()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sample-alert loader for the dry-run preview
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _fetch_sample_alerts(
|
||||
db: Any, # noqa: ANN401 — AsyncSession; kept loose so tests can stub
|
||||
tenant_id: UUID,
|
||||
limit: int = 50,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Pull the last ``limit`` alerts for the tenant.
|
||||
|
||||
The dry-run preview surfaces "what would happen to my last 50
|
||||
alerts?" so the analyst gets a tangible feel for the rule before
|
||||
saving. Returns an empty list when the alerts table isn't reachable
|
||||
(test envs without the schema, demo Fly.io stack) — the UI then
|
||||
falls back to its built-in illustrative samples.
|
||||
"""
|
||||
from sqlalchemy import text # noqa: PLC0415
|
||||
|
||||
try:
|
||||
result = await db.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT id, severity, title, source, src_ip, hostname, username,
|
||||
tags, metadata
|
||||
FROM aisoc_alerts
|
||||
WHERE tenant_id = :tenant_id
|
||||
ORDER BY created_at DESC
|
||||
LIMIT :limit
|
||||
"""
|
||||
),
|
||||
{"tenant_id": str(tenant_id), "limit": int(limit)},
|
||||
)
|
||||
rows = result.mappings().all()
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"business_context.preview_fetch_unavailable",
|
||||
tenant_id=str(tenant_id),
|
||||
error=str(exc),
|
||||
)
|
||||
return []
|
||||
|
||||
out: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
d = dict(row)
|
||||
meta = d.pop("metadata", None) or {}
|
||||
# Promote the common fields the rule grammar references onto the
|
||||
# top level so authors can write `field: alert.severity` rather
|
||||
# than `field: alert.metadata.severity`.
|
||||
out.append(
|
||||
{
|
||||
"id": str(d.get("id")),
|
||||
"severity": d.get("severity"),
|
||||
"title": d.get("title"),
|
||||
"source": d.get("source"),
|
||||
"src_ip": d.get("src_ip"),
|
||||
"hostname": d.get("hostname"),
|
||||
"username": d.get("username"),
|
||||
"tags": list(d.get("tags") or []),
|
||||
"alert": {
|
||||
"severity": d.get("severity"),
|
||||
"source": d.get("source"),
|
||||
"target": (meta.get("target") if isinstance(meta, dict) else {}) or {},
|
||||
"time": (meta.get("time") if isinstance(meta, dict) else {}) or {},
|
||||
},
|
||||
"metadata": meta,
|
||||
}
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@router.get("/rules", response_model=RulesEnvelope)
|
||||
async def get_rules(
|
||||
user: AuthUser,
|
||||
db: DBSession,
|
||||
) -> RulesEnvelope:
|
||||
"""Return the tenant's current rule set.
|
||||
|
||||
Always returns a 200 — a tenant with no rules gets an empty list
|
||||
and an empty YAML body. The editor uses the ``enabled`` flag to
|
||||
show the "rules paused" banner so analysts aren't surprised when
|
||||
a saved rule isn't taking effect.
|
||||
"""
|
||||
await user.require_permission_db("settings:read", db)
|
||||
|
||||
entry = _load_for(user.tenant_id)
|
||||
yaml_text = entry["yaml"]
|
||||
enabled = entry["enabled"]
|
||||
|
||||
rules = load_rules_from_yaml(yaml_text) if yaml_text else []
|
||||
snapshot = _engine().replace(user.tenant_id, rules)
|
||||
return _envelope(
|
||||
user.tenant_id,
|
||||
snapshot,
|
||||
yaml_text=yaml_text,
|
||||
enabled=enabled,
|
||||
updated_at=entry["updated_at"],
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/rules",
|
||||
response_model=RulesEnvelope,
|
||||
status_code=status.HTTP_200_OK,
|
||||
)
|
||||
async def replace_rules(
|
||||
payload: ReplaceRulesRequest,
|
||||
user: AuthUser,
|
||||
db: DBSession,
|
||||
) -> RulesEnvelope:
|
||||
"""Replace the tenant's whole rule set with a new YAML document.
|
||||
|
||||
The engine snapshot is swapped atomically *before* the write
|
||||
"completes" from the caller's perspective, so the next evaluation
|
||||
on the same process sees the fresh rules within microseconds —
|
||||
well inside the 1s "save → preview" budget the task spec calls
|
||||
out. Multi-process deployments still honour the budget because the
|
||||
JSONB-backed reload (T3.5-followup) will SET version on save and
|
||||
every worker re-pulls on TTL miss.
|
||||
"""
|
||||
await user.require_permission_db("settings:write", db)
|
||||
|
||||
try:
|
||||
rules = load_rules_from_yaml(payload.yaml)
|
||||
except RuleParseError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
|
||||
updated_at = _persist_for(
|
||||
user.tenant_id,
|
||||
yaml_text=payload.yaml,
|
||||
enabled=_load_for(user.tenant_id)["enabled"],
|
||||
)
|
||||
snapshot = _engine().replace(user.tenant_id, rules)
|
||||
|
||||
logger.info(
|
||||
"business_context.rules.replace",
|
||||
tenant_id=str(user.tenant_id),
|
||||
rule_count=len(rules),
|
||||
version=snapshot.version,
|
||||
)
|
||||
return _envelope(
|
||||
user.tenant_id,
|
||||
snapshot,
|
||||
yaml_text=payload.yaml,
|
||||
enabled=_load_for(user.tenant_id)["enabled"],
|
||||
updated_at=updated_at,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/rules/{rule_id}", response_model=RulesEnvelope)
|
||||
async def update_rule(
|
||||
rule_id: str,
|
||||
payload: UpdateRuleRequest,
|
||||
user: AuthUser,
|
||||
db: DBSession,
|
||||
) -> RulesEnvelope:
|
||||
"""Patch a single rule by id.
|
||||
|
||||
The body is the YAML for *that one rule*; we splice it into the
|
||||
tenant's rule list, replacing the existing entry of the same id (or
|
||||
appending if it's a new id). Returns the same envelope shape as
|
||||
``POST /rules`` so the editor can re-render in one round trip.
|
||||
"""
|
||||
await user.require_permission_db("settings:write", db)
|
||||
|
||||
try:
|
||||
candidates = load_rules_from_yaml(payload.yaml)
|
||||
except RuleParseError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
|
||||
if len(candidates) != 1:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="PUT body must contain exactly one rule",
|
||||
)
|
||||
new_rule = candidates[0]
|
||||
if new_rule.id != rule_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=(
|
||||
f"rule id in URL ({rule_id!r}) must match rule id in body "
|
||||
f"({new_rule.id!r})"
|
||||
),
|
||||
)
|
||||
|
||||
existing_yaml = _load_for(user.tenant_id)["yaml"]
|
||||
existing_rules = load_rules_from_yaml(existing_yaml) if existing_yaml else []
|
||||
by_id = {r.id: r for r in existing_rules}
|
||||
by_id[new_rule.id] = new_rule
|
||||
next_yaml = _serialise_rules(list(by_id.values()))
|
||||
|
||||
updated_at = _persist_for(
|
||||
user.tenant_id,
|
||||
yaml_text=next_yaml,
|
||||
enabled=_load_for(user.tenant_id)["enabled"],
|
||||
)
|
||||
snapshot = _engine().replace(user.tenant_id, by_id.values())
|
||||
|
||||
logger.info(
|
||||
"business_context.rules.update",
|
||||
tenant_id=str(user.tenant_id),
|
||||
rule_id=rule_id,
|
||||
version=snapshot.version,
|
||||
)
|
||||
return _envelope(
|
||||
user.tenant_id,
|
||||
snapshot,
|
||||
yaml_text=next_yaml,
|
||||
enabled=_load_for(user.tenant_id)["enabled"],
|
||||
updated_at=updated_at,
|
||||
)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/rules/{rule_id}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
response_model=None,
|
||||
)
|
||||
async def delete_rule(
|
||||
rule_id: str,
|
||||
user: AuthUser,
|
||||
db: DBSession,
|
||||
) -> None:
|
||||
await user.require_permission_db("settings:write", db)
|
||||
|
||||
existing_yaml = _load_for(user.tenant_id)["yaml"]
|
||||
existing_rules = load_rules_from_yaml(existing_yaml) if existing_yaml else []
|
||||
remaining = [r for r in existing_rules if r.id != rule_id]
|
||||
if len(remaining) == len(existing_rules):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"rule {rule_id!r} not found",
|
||||
)
|
||||
|
||||
next_yaml = _serialise_rules(remaining)
|
||||
_persist_for(
|
||||
user.tenant_id,
|
||||
yaml_text=next_yaml,
|
||||
enabled=_load_for(user.tenant_id)["enabled"],
|
||||
)
|
||||
_engine().replace(user.tenant_id, remaining)
|
||||
logger.info(
|
||||
"business_context.rules.delete",
|
||||
tenant_id=str(user.tenant_id),
|
||||
rule_id=rule_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/rules/preview", response_model=PreviewResponse)
|
||||
async def preview_rules(
|
||||
payload: PreviewRequest,
|
||||
user: AuthUser,
|
||||
db: DBSession,
|
||||
) -> PreviewResponse:
|
||||
"""Dry-run the candidate YAML against a sample of alerts.
|
||||
|
||||
Doesn't persist anything; doesn't modify the engine snapshot for
|
||||
the tenant. The response is shaped so the settings page can render
|
||||
a before/after table with a one-line "X of Y alerts changed" header.
|
||||
"""
|
||||
await user.require_permission_db("settings:read", db)
|
||||
|
||||
try:
|
||||
rules = load_rules_from_yaml(payload.yaml)
|
||||
except RuleParseError as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(exc),
|
||||
) from exc
|
||||
|
||||
alerts = payload.alerts
|
||||
if not alerts:
|
||||
alerts = await _fetch_sample_alerts(db, user.tenant_id, limit=50)
|
||||
if len(alerts) > _MAX_PREVIEW_ALERTS:
|
||||
alerts = alerts[:_MAX_PREVIEW_ALERTS]
|
||||
|
||||
start = time.perf_counter()
|
||||
evaluations = _engine().preview_against(
|
||||
user.tenant_id, alerts, rules=rules
|
||||
)
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
|
||||
rows = [
|
||||
PreviewRow(
|
||||
alert_id=ev.alert_id,
|
||||
matched_rule_ids=ev.matched_rule_ids,
|
||||
before=ev.before,
|
||||
after=ev.after,
|
||||
suppressed=ev.suppressed,
|
||||
changed=ev.changed,
|
||||
)
|
||||
for ev in evaluations
|
||||
]
|
||||
return PreviewResponse(
|
||||
sample_size=len(rows),
|
||||
changed_count=sum(1 for r in rows if r.changed),
|
||||
suppressed_count=sum(1 for r in rows if r.suppressed),
|
||||
elapsed_ms=round(elapsed_ms, 3),
|
||||
rows=rows,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# YAML round-trip
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _condition_to_dict(cond: Any) -> dict[str, Any]:
|
||||
"""Inverse of :func:`_parse_condition` — used when an analyst PUTs
|
||||
a single rule and we need to splice it back into the tenant's
|
||||
full YAML doc.
|
||||
"""
|
||||
if cond.logical == "all":
|
||||
return {"all": [_condition_to_dict(c) for c in cond.children]}
|
||||
if cond.logical == "any":
|
||||
return {"any": [_condition_to_dict(c) for c in cond.children]}
|
||||
if cond.logical == "not":
|
||||
return {"not": _condition_to_dict(cond.children[0])}
|
||||
|
||||
base: dict[str, Any] = {"field": cond.field, "op": cond.op}
|
||||
if cond.op not in {"exists", "not_exists"}:
|
||||
base["value"] = cond.value
|
||||
return base
|
||||
|
||||
|
||||
def _action_to_dict(action: Any) -> dict[str, Any]:
|
||||
out: dict[str, Any] = {}
|
||||
if action.set_severity is not None:
|
||||
out["set_severity"] = action.set_severity
|
||||
if action.route_to is not None:
|
||||
out["route_to"] = action.route_to
|
||||
if action.tag is not None:
|
||||
out["tag"] = action.tag
|
||||
if action.suppress:
|
||||
out["suppress"] = True
|
||||
return out
|
||||
|
||||
|
||||
def _serialise_rules(rules: list[BusinessContextRule]) -> str:
|
||||
"""Render a list of parsed rules back to YAML.
|
||||
|
||||
Used when an analyst does a PUT-by-id and we want to refresh the
|
||||
canonical YAML blob the editor sees on next GET. The output isn't
|
||||
the verbatim YAML the analyst typed (comments + key ordering are
|
||||
lost) — but it's structurally lossless and stable, which is what
|
||||
the editor's diff view needs.
|
||||
"""
|
||||
if not rules:
|
||||
return ""
|
||||
docs = [
|
||||
{
|
||||
"id": r.id,
|
||||
"description": r.description,
|
||||
"enabled": r.enabled,
|
||||
"priority": r.priority,
|
||||
"when": _condition_to_dict(r.when),
|
||||
"then": _action_to_dict(r.then),
|
||||
}
|
||||
for r in rules
|
||||
]
|
||||
return yaml.safe_dump({"rules": docs}, sort_keys=False)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Business Context Rules — Track 3, T3.5.
|
||||
|
||||
A YAML-based mutator that runs **between fusion and the triage agent**.
|
||||
The platform fusion pipeline (``services/fusion``) emits a normalised,
|
||||
de-duplicated, ML-scored ``FusedAlert``. Before that alert reaches the
|
||||
triage agent, this module gives the customer a chance to apply their
|
||||
own business context — bumping severity for prod, routing AWS alerts
|
||||
to the cloud team, suppressing alerts that fire during a known
|
||||
maintenance window, etc.
|
||||
|
||||
Example rule
|
||||
~~~~~~~~~~~~
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
id: prod-iam-touch-is-critical
|
||||
description: Anything touching prod IAM during business hours wakes tier-2.
|
||||
when:
|
||||
all:
|
||||
- field: alert.target.tag
|
||||
op: eq
|
||||
value: prod
|
||||
- field: alert.time.is_business_hours
|
||||
op: eq
|
||||
value: true
|
||||
then:
|
||||
set_severity: critical
|
||||
route_to: tier2
|
||||
tag: business-hours-prod
|
||||
|
||||
The engine compiles each rule into a small predicate DAG keyed on the
|
||||
fields it touches, so evaluation against an alert is O(rules * fields)
|
||||
without YAML reparsing on the hot path.
|
||||
|
||||
Public surface
|
||||
~~~~~~~~~~~~~~
|
||||
|
||||
* :class:`BusinessContextEngine` — load + evaluate rules, hot-reload on
|
||||
rule change.
|
||||
* :class:`BusinessContextRule` — parsed rule wire shape.
|
||||
* :class:`AlertEvaluation` — one alert's before/after diff for the
|
||||
preview UI.
|
||||
* :func:`load_rules_from_yaml` — pure parser; raises
|
||||
:class:`RuleParseError` on grammar errors.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .engine import (
|
||||
AlertEvaluation,
|
||||
BusinessContextEngine,
|
||||
EngineSnapshot,
|
||||
RuleAction,
|
||||
)
|
||||
from .models import (
|
||||
BusinessContextRule,
|
||||
RuleCondition,
|
||||
RuleParseError,
|
||||
load_rules_from_yaml,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"AlertEvaluation",
|
||||
"BusinessContextEngine",
|
||||
"BusinessContextRule",
|
||||
"EngineSnapshot",
|
||||
"RuleAction",
|
||||
"RuleCondition",
|
||||
"RuleParseError",
|
||||
"load_rules_from_yaml",
|
||||
]
|
||||
@@ -0,0 +1,487 @@
|
||||
"""Business-context engine — evaluator + hot-reload + dry-run preview.
|
||||
|
||||
The engine is a pure-Python in-memory DAG: each rule's ``when`` is
|
||||
compiled once into a flat predicate that maps an alert dict to True /
|
||||
False, and matching rules are applied in priority order to produce a
|
||||
mutated alert + a diff for the analyst UI.
|
||||
|
||||
Hot-reload contract
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
The CRUD endpoint persists the rule set as JSONB on
|
||||
``business_context_rule_sets`` and bumps a ``version`` integer on every
|
||||
save. The engine caches the parsed rule set keyed on ``(tenant_id,
|
||||
version)``; the ``BusinessContextEngine.replace`` call swaps the cached
|
||||
entry under a single lock so callers either see the pre-save or
|
||||
post-save snapshot, never a torn intermediate. Callers are expected to
|
||||
invoke ``replace`` from the same task that handled the write, so the
|
||||
"save → preview" round-trip stays well under the 1s budget the task
|
||||
spec requires.
|
||||
|
||||
Dry-run preview
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
The settings page wants to show "if I save this YAML, what would
|
||||
happen to the last 100 alerts?" without persisting anything. We
|
||||
expose :meth:`preview_against` which takes an arbitrary list of
|
||||
alerts and returns one :class:`AlertEvaluation` per alert, with the
|
||||
before / after severity / route + the list of matched rule ids.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from .models import (
|
||||
BusinessContextRule,
|
||||
RuleAction,
|
||||
RuleCondition,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Field accessor — flatten the alert into a dotted-path lookup.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _resolve_field(alert: Mapping[str, Any], path: str) -> Any:
|
||||
"""Walk a dotted path into ``alert``.
|
||||
|
||||
Returns the sentinel :class:`_Missing` when the path does not exist
|
||||
(so ``exists`` / ``not_exists`` ops can distinguish a missing key
|
||||
from an explicit ``None``).
|
||||
"""
|
||||
cur: Any = alert
|
||||
for part in path.split("."):
|
||||
if isinstance(cur, Mapping):
|
||||
if part not in cur:
|
||||
return _MISSING
|
||||
cur = cur[part]
|
||||
else:
|
||||
return _MISSING
|
||||
return cur
|
||||
|
||||
|
||||
class _Missing:
|
||||
"""Sentinel for missing dotted-path lookups."""
|
||||
|
||||
def __bool__(self) -> bool: # pragma: no cover - sentinel never coerced
|
||||
return False
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - debug only
|
||||
return "<missing>"
|
||||
|
||||
|
||||
_MISSING = _Missing()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Predicate compilation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _eval_op(op: str, lhs: Any, rhs: Any) -> bool:
|
||||
"""Apply one comparator. Missing LHS short-circuits to False except
|
||||
for the unary ``exists`` / ``not_exists`` ops, which are handled by
|
||||
the caller.
|
||||
"""
|
||||
if op == "eq":
|
||||
return lhs == rhs
|
||||
if op == "ne":
|
||||
return lhs != rhs
|
||||
if op == "lt":
|
||||
try:
|
||||
return lhs < rhs
|
||||
except TypeError:
|
||||
return False
|
||||
if op == "lte":
|
||||
try:
|
||||
return lhs <= rhs
|
||||
except TypeError:
|
||||
return False
|
||||
if op == "gt":
|
||||
try:
|
||||
return lhs > rhs
|
||||
except TypeError:
|
||||
return False
|
||||
if op == "gte":
|
||||
try:
|
||||
return lhs >= rhs
|
||||
except TypeError:
|
||||
return False
|
||||
if op == "contains":
|
||||
try:
|
||||
return rhs in lhs
|
||||
except TypeError:
|
||||
return False
|
||||
if op == "startswith":
|
||||
return isinstance(lhs, str) and isinstance(rhs, str) and lhs.startswith(rhs)
|
||||
if op == "endswith":
|
||||
return isinstance(lhs, str) and isinstance(rhs, str) and lhs.endswith(rhs)
|
||||
if op == "in":
|
||||
return lhs in rhs if isinstance(rhs, (list, tuple, set)) else False
|
||||
if op == "not_in":
|
||||
return lhs not in rhs if isinstance(rhs, (list, tuple, set)) else False
|
||||
return False
|
||||
|
||||
|
||||
def evaluate_condition(cond: RuleCondition, alert: Mapping[str, Any]) -> bool:
|
||||
"""Recursively evaluate a parsed condition against an alert dict.
|
||||
|
||||
Exposed at module scope so the dry-run preview can inspect *which*
|
||||
sub-conditions matched if we ever expose that in the UI; today
|
||||
callers should prefer :meth:`BusinessContextEngine.evaluate`.
|
||||
"""
|
||||
# Aggregator forms
|
||||
if cond.logical == "all":
|
||||
return all(evaluate_condition(c, alert) for c in cond.children)
|
||||
if cond.logical == "any":
|
||||
return any(evaluate_condition(c, alert) for c in cond.children)
|
||||
if cond.logical == "not":
|
||||
return not evaluate_condition(cond.children[0], alert)
|
||||
|
||||
# Leaf form
|
||||
assert cond.field is not None and cond.op is not None
|
||||
val = _resolve_field(alert, cond.field)
|
||||
if cond.op == "exists":
|
||||
return val is not _MISSING
|
||||
if cond.op == "not_exists":
|
||||
return val is _MISSING
|
||||
if val is _MISSING:
|
||||
return False
|
||||
return _eval_op(cond.op, val, cond.value)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Per-alert evaluation result
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class AlertEvaluation:
|
||||
"""One alert's before/after result rendered by the dry-run preview.
|
||||
|
||||
``alert_id`` is opaque (whatever ``id`` field was on the input
|
||||
alert); the UI uses it to row-key the table. ``before`` and
|
||||
``after`` are the *materialised* state — the UI compares severity /
|
||||
route_to / tags / suppressed flags directly without re-deriving the
|
||||
diff itself.
|
||||
"""
|
||||
|
||||
alert_id: str
|
||||
matched_rule_ids: list[str] = field(default_factory=list)
|
||||
before: dict[str, Any] = field(default_factory=dict)
|
||||
after: dict[str, Any] = field(default_factory=dict)
|
||||
suppressed: bool = False
|
||||
|
||||
@property
|
||||
def changed(self) -> bool:
|
||||
"""True when this alert was mutated (or suppressed)."""
|
||||
if self.suppressed:
|
||||
return True
|
||||
return self.before != self.after
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compiled snapshot — what we cache per tenant.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EngineSnapshot:
|
||||
"""Frozen snapshot of one tenant's rule set after parsing.
|
||||
|
||||
The snapshot is what the hot path holds onto; ``BusinessContextEngine``
|
||||
swaps the snapshot pointer atomically on hot-reload so an in-flight
|
||||
eval never sees a half-updated rule list.
|
||||
"""
|
||||
|
||||
tenant_id: UUID
|
||||
version: int
|
||||
rules: tuple[BusinessContextRule, ...]
|
||||
field_index: dict[str, tuple[str, ...]]
|
||||
"""Reverse index: field path → ids of rules that depend on it.
|
||||
|
||||
Currently informational (used by the UI builder to surface "this
|
||||
field is referenced by X rules"); the evaluator iterates rules in
|
||||
priority order rather than walking the index, which keeps the hot
|
||||
path branch-free and predictable in the Nrules×Nalerts profile.
|
||||
"""
|
||||
|
||||
@property
|
||||
def enabled_rules(self) -> tuple[BusinessContextRule, ...]:
|
||||
return tuple(r for r in self.rules if r.enabled)
|
||||
|
||||
|
||||
def _compile_snapshot(
|
||||
tenant_id: UUID, version: int, rules: Iterable[BusinessContextRule]
|
||||
) -> EngineSnapshot:
|
||||
sorted_rules = tuple(
|
||||
sorted(rules, key=lambda r: (r.priority, r.id))
|
||||
)
|
||||
idx: dict[str, list[str]] = {}
|
||||
for r in sorted_rules:
|
||||
for f in r.when.fields_referenced():
|
||||
idx.setdefault(f, []).append(r.id)
|
||||
return EngineSnapshot(
|
||||
tenant_id=tenant_id,
|
||||
version=version,
|
||||
rules=sorted_rules,
|
||||
field_index={k: tuple(v) for k, v in idx.items()},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action application
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _apply_action(alert: dict[str, Any], action: RuleAction) -> dict[str, Any]:
|
||||
"""Return a mutated copy of ``alert``.
|
||||
|
||||
Mutations layer rather than overwrite — multiple matching rules
|
||||
each contribute their action; the *last* (highest priority number)
|
||||
win for severity / route_to so an analyst can express "default to
|
||||
medium, but bump to critical for prod". Tags accumulate.
|
||||
"""
|
||||
out = dict(alert)
|
||||
if action.set_severity is not None:
|
||||
out["severity"] = action.set_severity
|
||||
if action.route_to is not None:
|
||||
out["route_to"] = action.route_to
|
||||
if action.tag is not None:
|
||||
existing = list(out.get("tags") or [])
|
||||
if action.tag not in existing:
|
||||
existing.append(action.tag)
|
||||
out["tags"] = existing
|
||||
if action.suppress:
|
||||
out["__suppressed__"] = True
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Engine
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class BusinessContextEngine:
|
||||
"""Per-process registry of compiled rule snapshots, keyed by tenant.
|
||||
|
||||
Designed to be a process-singleton (the FastAPI app caches one) so
|
||||
every request sees the same rule set and a single ``replace`` call
|
||||
is sufficient to roll the whole pool to a new version. Thread-safe
|
||||
via a single lock guarding the snapshot dict; reads grab the
|
||||
snapshot pointer once and then operate on the immutable
|
||||
:class:`EngineSnapshot` without holding the lock, so hot-path
|
||||
contention is bounded.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._snapshots: dict[UUID, EngineSnapshot] = {}
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Snapshot management
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def replace(
|
||||
self,
|
||||
tenant_id: UUID,
|
||||
rules: Iterable[BusinessContextRule],
|
||||
*,
|
||||
version: int | None = None,
|
||||
) -> EngineSnapshot:
|
||||
"""Atomically swap the rule set for ``tenant_id``.
|
||||
|
||||
Returns the new snapshot so the caller can confirm what landed
|
||||
(useful for the "save → preview" round-trip).
|
||||
"""
|
||||
with self._lock:
|
||||
old = self._snapshots.get(tenant_id)
|
||||
new_version = version if version is not None else (old.version + 1 if old else 1)
|
||||
snap = _compile_snapshot(tenant_id, new_version, rules)
|
||||
self._snapshots[tenant_id] = snap
|
||||
return snap
|
||||
|
||||
def snapshot_for(self, tenant_id: UUID) -> EngineSnapshot | None:
|
||||
"""Read the current snapshot without holding the lock."""
|
||||
return self._snapshots.get(tenant_id)
|
||||
|
||||
def clear(self, tenant_id: UUID | None = None) -> None:
|
||||
"""Forget cached snapshots — used by tests + the "delete all
|
||||
rules" path."""
|
||||
with self._lock:
|
||||
if tenant_id is None:
|
||||
self._snapshots.clear()
|
||||
else:
|
||||
self._snapshots.pop(tenant_id, None)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Hot path: evaluate one alert against the cached snapshot.
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def evaluate(
|
||||
self,
|
||||
tenant_id: UUID,
|
||||
alert: Mapping[str, Any],
|
||||
) -> AlertEvaluation:
|
||||
"""Run the rules registered for ``tenant_id`` against ``alert``.
|
||||
|
||||
``alert`` may carry an ``id`` field (used for the response
|
||||
``alert_id``); otherwise an empty string is returned, matching
|
||||
the dry-run preview wire shape.
|
||||
"""
|
||||
snap = self.snapshot_for(tenant_id)
|
||||
before = _projection(alert)
|
||||
result = AlertEvaluation(
|
||||
alert_id=str(alert.get("id", "")),
|
||||
before=dict(before),
|
||||
after=dict(before),
|
||||
)
|
||||
|
||||
if snap is None:
|
||||
return result
|
||||
|
||||
current = dict(alert)
|
||||
for rule in snap.enabled_rules:
|
||||
if not evaluate_condition(rule.when, current):
|
||||
continue
|
||||
current = _apply_action(current, rule.then)
|
||||
result.matched_rule_ids.append(rule.id)
|
||||
if current.get("__suppressed__"):
|
||||
# Once an alert is suppressed, downstream rules can't
|
||||
# un-suppress — short-circuit so the final state is
|
||||
# deterministic.
|
||||
result.suppressed = True
|
||||
result.after = _projection(current)
|
||||
return result
|
||||
|
||||
result.after = _projection(current)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Dry-run preview (Settings page)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def preview_against(
|
||||
self,
|
||||
tenant_id: UUID,
|
||||
alerts: Iterable[Mapping[str, Any]],
|
||||
*,
|
||||
rules: Iterable[BusinessContextRule] | None = None,
|
||||
) -> list[AlertEvaluation]:
|
||||
"""Run a (possibly hypothetical) rule set against ``alerts``.
|
||||
|
||||
When ``rules`` is provided, the engine builds a *transient*
|
||||
snapshot for the duration of the call and never registers it.
|
||||
This is the path the settings page hits on every keystroke
|
||||
debounce: "show me what these unsaved YAML rules would do to
|
||||
the last 100 alerts." Latency per call is bounded by
|
||||
Nrules×Nalerts × O(condition complexity), which for the spec'd
|
||||
50-alert preview easily fits inside the 1s budget.
|
||||
"""
|
||||
if rules is None:
|
||||
return [self.evaluate(tenant_id, a) for a in alerts]
|
||||
|
||||
# Build a transient snapshot and evaluate against it directly
|
||||
# (don't mutate ``self._snapshots``). Use a sentinel version
|
||||
# of -1 so anything that accidentally caches it can detect the
|
||||
# "preview-only" origin.
|
||||
transient = _compile_snapshot(tenant_id, version=-1, rules=rules)
|
||||
|
||||
out: list[AlertEvaluation] = []
|
||||
for alert in alerts:
|
||||
before = _projection(alert)
|
||||
result = AlertEvaluation(
|
||||
alert_id=str(alert.get("id", "")),
|
||||
before=dict(before),
|
||||
after=dict(before),
|
||||
)
|
||||
current = dict(alert)
|
||||
for rule in transient.enabled_rules:
|
||||
if not evaluate_condition(rule.when, current):
|
||||
continue
|
||||
current = _apply_action(current, rule.then)
|
||||
result.matched_rule_ids.append(rule.id)
|
||||
if current.get("__suppressed__"):
|
||||
result.suppressed = True
|
||||
break
|
||||
result.after = _projection(current)
|
||||
out.append(result)
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _projection(alert: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Pull the four fields the preview UI cares about out of an alert.
|
||||
|
||||
Kept narrow on purpose — the alert payload itself can be many KB
|
||||
and the diff renderer only ever shows these four columns.
|
||||
"""
|
||||
return {
|
||||
"severity": alert.get("severity"),
|
||||
"route_to": alert.get("route_to"),
|
||||
"tags": list(alert.get("tags") or []),
|
||||
"suppressed": bool(alert.get("__suppressed__", False)),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Process singleton
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_default_engine: BusinessContextEngine | None = None
|
||||
|
||||
|
||||
def get_engine() -> BusinessContextEngine:
|
||||
"""Lazy process-singleton accessor."""
|
||||
global _default_engine
|
||||
if _default_engine is None:
|
||||
_default_engine = BusinessContextEngine()
|
||||
return _default_engine
|
||||
|
||||
|
||||
def reset_engine_for_tests() -> None:
|
||||
"""Reset the singleton — only safe in test code."""
|
||||
global _default_engine
|
||||
_default_engine = None
|
||||
|
||||
|
||||
__all__ = [
|
||||
"AlertEvaluation",
|
||||
"BusinessContextEngine",
|
||||
"EngineSnapshot",
|
||||
"RuleAction",
|
||||
"evaluate_condition",
|
||||
"get_engine",
|
||||
"reset_engine_for_tests",
|
||||
"_apply_action",
|
||||
"_projection",
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Convenience timer for the API "save → preview" latency assertion. Imported
|
||||
# by tests; cheap helper that sidesteps having to add an extra dependency.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def measure_evaluation_latency(
|
||||
engine: BusinessContextEngine,
|
||||
tenant_id: UUID,
|
||||
alerts: list[Mapping[str, Any]],
|
||||
) -> float:
|
||||
"""Return the wall-clock seconds taken to evaluate ``alerts`` once."""
|
||||
start = time.perf_counter()
|
||||
for a in alerts:
|
||||
engine.evaluate(tenant_id, a)
|
||||
return time.perf_counter() - start
|
||||
@@ -0,0 +1,410 @@
|
||||
"""Business context rule data model + YAML parser — T3.5.
|
||||
|
||||
The wire shape mirrors the playbook-engine ``condition_expr`` grammar
|
||||
in :file:`playbook.schema.json` so analysts who already understand
|
||||
playbook conditions feel at home (``field / op / value`` with
|
||||
``and / or / not`` aggregators). The evaluator lives in
|
||||
:mod:`app.services.business_context.engine`; this module is pure data
|
||||
+ parsing so we can re-use it from the API layer (CRUD validation),
|
||||
the dry-run preview, and the hot-path evaluator without circularity.
|
||||
|
||||
Why YAML and not JSON? The settings page exposes a Monaco editor and
|
||||
analysts overwhelmingly prefer YAML for rule authoring (comments, no
|
||||
quoted keys, multiline strings for ``description``). The CRUD layer
|
||||
parses YAML→model on write and stores the structured model as JSONB,
|
||||
so the wire format on the API is always JSON; YAML is only the input
|
||||
language the editor speaks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field as dc_field
|
||||
from typing import Any, Literal
|
||||
|
||||
import yaml
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public errors
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class RuleParseError(ValueError):
|
||||
"""Raised when a rule definition fails structural validation.
|
||||
|
||||
We deliberately use ``ValueError`` (not a Pydantic validation error)
|
||||
so callers in the API layer can catch this single class and return a
|
||||
422 with the message verbatim — the message is already shaped for an
|
||||
end-user (e.g. "rule 'x': 'set_severity' must be one of ...").
|
||||
"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Constants — kept inline so callers can introspect them (UI builder hints).
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
ALLOWED_OPS: frozenset[str] = frozenset(
|
||||
{
|
||||
"eq",
|
||||
"ne",
|
||||
"lt",
|
||||
"lte",
|
||||
"gt",
|
||||
"gte",
|
||||
"contains",
|
||||
"startswith",
|
||||
"endswith",
|
||||
"in",
|
||||
"not_in",
|
||||
"exists",
|
||||
"not_exists",
|
||||
}
|
||||
)
|
||||
|
||||
ALLOWED_SEVERITIES: tuple[str, ...] = ("info", "low", "medium", "high", "critical")
|
||||
|
||||
# Routing destinations the platform recognises today. The triage agent
|
||||
# uses these to decide which queue to drop the alert into; an unknown
|
||||
# destination is rejected at parse-time so a typo in YAML doesn't
|
||||
# silently route alerts to nowhere.
|
||||
ALLOWED_ROUTES: frozenset[str] = frozenset(
|
||||
{
|
||||
"tier1",
|
||||
"tier2",
|
||||
"tier3",
|
||||
"ic",
|
||||
"cloud",
|
||||
"identity",
|
||||
"appsec",
|
||||
"soc-night",
|
||||
"soc-emea",
|
||||
}
|
||||
)
|
||||
|
||||
# A rule id is a kebab-case slug; mirrors the playbook id pattern in
|
||||
# :file:`playbook.schema.json` so the two surfaces stay consistent.
|
||||
_RULE_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]{2,62}$")
|
||||
# Tags + route destinations follow the same shape so they can be used
|
||||
# as-is in downstream tools (slack channels, jira labels, etc.).
|
||||
_TAG_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,62}$")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Conditions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuleCondition:
|
||||
"""One node of a condition expression.
|
||||
|
||||
Exactly one of:
|
||||
|
||||
* ``field/op/value`` — the leaf comparator.
|
||||
* ``logical`` + ``children`` — an aggregator (``all`` / ``any`` / ``not``).
|
||||
|
||||
The dataclass is frozen so the engine can keep references in caches
|
||||
keyed on (rule_id, condition_index) without worrying about mutation.
|
||||
"""
|
||||
|
||||
# Leaf form
|
||||
field: str | None = None
|
||||
op: str | None = None
|
||||
value: Any = None
|
||||
|
||||
# Aggregator form
|
||||
logical: Literal["all", "any", "not", None] = None
|
||||
children: tuple[RuleCondition, ...] = dc_field(default_factory=tuple)
|
||||
|
||||
def fields_referenced(self) -> set[str]:
|
||||
"""All distinct field names the condition pulls out of the alert.
|
||||
|
||||
Used by the engine to build a quick "which rules need re-eval if
|
||||
this field changes?" reverse-index; also used by the UI builder
|
||||
side-panel to surface the fields a rule depends on.
|
||||
"""
|
||||
if self.field is not None:
|
||||
return {self.field}
|
||||
out: set[str] = set()
|
||||
for c in self.children:
|
||||
out |= c.fields_referenced()
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Actions
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuleAction:
|
||||
"""The mutation a matching rule applies to the alert.
|
||||
|
||||
All fields are optional; an action with everything ``None`` is a
|
||||
no-op (allowed at parse time so an analyst can stub a rule and fill
|
||||
in the action later).
|
||||
"""
|
||||
|
||||
set_severity: str | None = None # one of ALLOWED_SEVERITIES
|
||||
route_to: str | None = None # one of ALLOWED_ROUTES
|
||||
tag: str | None = None # appended to alert.tags
|
||||
suppress: bool = False # if true, alert is dropped before triage
|
||||
|
||||
def is_noop(self) -> bool:
|
||||
return (
|
||||
self.set_severity is None
|
||||
and self.route_to is None
|
||||
and self.tag is None
|
||||
and not self.suppress
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Rule
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BusinessContextRule:
|
||||
"""A parsed business-context rule.
|
||||
|
||||
Frozen + hashable so the engine can compile and cache them in a
|
||||
dict keyed on ``id``. The original YAML source is kept on
|
||||
``raw_yaml`` for round-tripping into the editor without losing
|
||||
comments / formatting.
|
||||
"""
|
||||
|
||||
id: str
|
||||
description: str
|
||||
when: RuleCondition
|
||||
then: RuleAction
|
||||
enabled: bool = True
|
||||
priority: int = 100 # lower runs first; ties broken by id for determinism
|
||||
raw_yaml: str = ""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _parse_condition(raw: Any, *, path: str) -> RuleCondition:
|
||||
"""Turn the raw mapping into a :class:`RuleCondition`.
|
||||
|
||||
Recursive: the aggregator forms (``all`` / ``any`` / ``not``) loop
|
||||
back through this same function on each child. ``path`` is a dotted
|
||||
breadcrumb used in error messages so authors can find the offending
|
||||
node when the rule has nested conditions.
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
raise RuleParseError(f"{path}: expected a mapping, got {type(raw).__name__}")
|
||||
|
||||
# Aggregator forms first — they win over leaf detection so a
|
||||
# mapping like ``{all: [...], field: 'x'}`` isn't ambiguous.
|
||||
for key in ("all", "any", "not"):
|
||||
if key in raw:
|
||||
children_raw = raw[key]
|
||||
if key == "not":
|
||||
if not isinstance(children_raw, dict):
|
||||
raise RuleParseError(
|
||||
f"{path}.not: expected a mapping for the negated condition"
|
||||
)
|
||||
child = _parse_condition(children_raw, path=f"{path}.not")
|
||||
return RuleCondition(logical="not", children=(child,))
|
||||
if not isinstance(children_raw, list) or not children_raw:
|
||||
raise RuleParseError(
|
||||
f"{path}.{key}: must be a non-empty list of conditions"
|
||||
)
|
||||
children = tuple(
|
||||
_parse_condition(c, path=f"{path}.{key}[{i}]")
|
||||
for i, c in enumerate(children_raw)
|
||||
)
|
||||
return RuleCondition(logical=key, children=children)
|
||||
|
||||
# Leaf form
|
||||
field_name = raw.get("field")
|
||||
op = raw.get("op")
|
||||
if field_name is None or op is None:
|
||||
raise RuleParseError(
|
||||
f"{path}: leaf condition must include 'field' and 'op' (got {sorted(raw.keys())})"
|
||||
)
|
||||
if not isinstance(field_name, str) or not field_name:
|
||||
raise RuleParseError(f"{path}.field: must be a non-empty string")
|
||||
if op not in ALLOWED_OPS:
|
||||
raise RuleParseError(
|
||||
f"{path}.op: {op!r} is not one of {sorted(ALLOWED_OPS)}"
|
||||
)
|
||||
|
||||
# ``exists`` / ``not_exists`` are unary — value is ignored if present.
|
||||
if op in {"exists", "not_exists"}:
|
||||
return RuleCondition(field=field_name, op=op, value=None)
|
||||
|
||||
if "value" not in raw:
|
||||
raise RuleParseError(f"{path}.value: required for op={op!r}")
|
||||
value = raw["value"]
|
||||
# ``in`` / ``not_in`` require a sequence; coerce single string to a
|
||||
# one-element list to be analyst-friendly.
|
||||
if op in {"in", "not_in"}:
|
||||
if isinstance(value, (str, bytes)):
|
||||
value = [value]
|
||||
if not isinstance(value, (list, tuple)) or not value:
|
||||
raise RuleParseError(
|
||||
f"{path}.value: op={op!r} requires a non-empty list"
|
||||
)
|
||||
value = list(value)
|
||||
return RuleCondition(field=field_name, op=op, value=value)
|
||||
|
||||
|
||||
def _parse_action(raw: Any, *, rule_id: str) -> RuleAction:
|
||||
if not isinstance(raw, dict):
|
||||
raise RuleParseError(
|
||||
f"rule {rule_id!r}: 'then' must be a mapping (got {type(raw).__name__})"
|
||||
)
|
||||
|
||||
sev = raw.get("set_severity")
|
||||
if sev is not None:
|
||||
if not isinstance(sev, str) or sev not in ALLOWED_SEVERITIES:
|
||||
raise RuleParseError(
|
||||
f"rule {rule_id!r}: 'set_severity' must be one of {ALLOWED_SEVERITIES}"
|
||||
)
|
||||
|
||||
route = raw.get("route_to")
|
||||
if route is not None:
|
||||
if not isinstance(route, str) or route not in ALLOWED_ROUTES:
|
||||
raise RuleParseError(
|
||||
f"rule {rule_id!r}: 'route_to' must be one of {sorted(ALLOWED_ROUTES)}"
|
||||
)
|
||||
|
||||
tag = raw.get("tag")
|
||||
if tag is not None:
|
||||
if not isinstance(tag, str) or not _TAG_RE.match(tag):
|
||||
raise RuleParseError(
|
||||
f"rule {rule_id!r}: 'tag' must be a kebab-case slug (got {tag!r})"
|
||||
)
|
||||
|
||||
suppress = raw.get("suppress", False)
|
||||
if not isinstance(suppress, bool):
|
||||
raise RuleParseError(
|
||||
f"rule {rule_id!r}: 'suppress' must be a boolean (got {type(suppress).__name__})"
|
||||
)
|
||||
|
||||
return RuleAction(
|
||||
set_severity=sev,
|
||||
route_to=route,
|
||||
tag=tag,
|
||||
suppress=suppress,
|
||||
)
|
||||
|
||||
|
||||
def _parse_one_rule(raw: Any, *, source_yaml: str) -> BusinessContextRule:
|
||||
if not isinstance(raw, dict):
|
||||
raise RuleParseError(
|
||||
f"top-level rule must be a mapping, got {type(raw).__name__}"
|
||||
)
|
||||
|
||||
rid = raw.get("id")
|
||||
if not isinstance(rid, str) or not _RULE_ID_RE.match(rid):
|
||||
raise RuleParseError(
|
||||
"rule.id must be a kebab-case slug 3-63 chars (e.g. 'prod-iam-critical')"
|
||||
)
|
||||
|
||||
description = raw.get("description", "") or ""
|
||||
if not isinstance(description, str):
|
||||
raise RuleParseError(f"rule {rid!r}: 'description' must be a string")
|
||||
|
||||
when_raw = raw.get("when")
|
||||
if when_raw is None:
|
||||
raise RuleParseError(f"rule {rid!r}: 'when' clause is required")
|
||||
when = _parse_condition(when_raw, path=f"rule[{rid}].when")
|
||||
|
||||
then_raw = raw.get("then")
|
||||
if then_raw is None:
|
||||
raise RuleParseError(f"rule {rid!r}: 'then' clause is required")
|
||||
then = _parse_action(then_raw, rule_id=rid)
|
||||
if then.is_noop():
|
||||
raise RuleParseError(
|
||||
f"rule {rid!r}: 'then' clause must set at least one of "
|
||||
"set_severity / route_to / tag / suppress"
|
||||
)
|
||||
|
||||
enabled = raw.get("enabled", True)
|
||||
if not isinstance(enabled, bool):
|
||||
raise RuleParseError(f"rule {rid!r}: 'enabled' must be a boolean")
|
||||
|
||||
priority = raw.get("priority", 100)
|
||||
if not isinstance(priority, int) or not 0 <= priority <= 1000:
|
||||
raise RuleParseError(
|
||||
f"rule {rid!r}: 'priority' must be an int in [0, 1000]"
|
||||
)
|
||||
|
||||
return BusinessContextRule(
|
||||
id=rid,
|
||||
description=description,
|
||||
when=when,
|
||||
then=then,
|
||||
enabled=enabled,
|
||||
priority=priority,
|
||||
raw_yaml=source_yaml,
|
||||
)
|
||||
|
||||
|
||||
def load_rules_from_yaml(source: str) -> list[BusinessContextRule]:
|
||||
"""Parse a YAML document into a list of rules.
|
||||
|
||||
Accepts either a single rule mapping or a top-level ``rules:`` list:
|
||||
|
||||
.. code-block:: yaml
|
||||
|
||||
rules:
|
||||
- id: rule-a
|
||||
...
|
||||
- id: rule-b
|
||||
...
|
||||
|
||||
The single-mapping form is convenient when authoring a rule one at
|
||||
a time in the Monaco editor; the list form is what the API stores
|
||||
on the tenant after all rules have been concatenated.
|
||||
|
||||
Duplicate IDs are rejected (the engine keys on ``id``); empty input
|
||||
returns an empty list (an analyst clearing the editor is a valid
|
||||
"disable all rules" action).
|
||||
"""
|
||||
if not isinstance(source, str):
|
||||
raise RuleParseError("YAML source must be a string")
|
||||
text = source.strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
try:
|
||||
data = yaml.safe_load(text)
|
||||
except yaml.YAMLError as exc:
|
||||
raise RuleParseError(f"YAML parse error: {exc}") from exc
|
||||
|
||||
if data is None:
|
||||
return []
|
||||
if isinstance(data, dict) and "rules" in data:
|
||||
rules_raw = data["rules"]
|
||||
if not isinstance(rules_raw, list):
|
||||
raise RuleParseError("'rules' must be a list")
|
||||
elif isinstance(data, list):
|
||||
rules_raw = data
|
||||
elif isinstance(data, dict):
|
||||
# Single-rule shorthand.
|
||||
rules_raw = [data]
|
||||
else:
|
||||
raise RuleParseError(
|
||||
f"top-level YAML must be a list or mapping, got {type(data).__name__}"
|
||||
)
|
||||
|
||||
parsed: list[BusinessContextRule] = []
|
||||
seen_ids: set[str] = set()
|
||||
for raw in rules_raw:
|
||||
rule = _parse_one_rule(raw, source_yaml=text)
|
||||
if rule.id in seen_ids:
|
||||
raise RuleParseError(
|
||||
f"duplicate rule id {rule.id!r} (rule ids must be unique)"
|
||||
)
|
||||
seen_ids.add(rule.id)
|
||||
parsed.append(rule)
|
||||
|
||||
return parsed
|
||||
@@ -0,0 +1,736 @@
|
||||
"""Tests for the Business Context Rules engine + endpoints — T3.5.
|
||||
|
||||
Coverage map
|
||||
~~~~~~~~~~~~
|
||||
|
||||
YAML parser (``models.load_rules_from_yaml``)
|
||||
* Empty / whitespace YAML → empty list.
|
||||
* Single-rule shorthand and ``rules:`` list form both parse.
|
||||
* Aggregator forms (``all``/``any``/``not``) round-trip correctly.
|
||||
* Bad rule ids, bad ops, missing required clauses, no-op ``then``,
|
||||
and invalid ``set_severity`` / ``route_to`` / ``tag`` slugs all
|
||||
raise :class:`RuleParseError` with actionable messages.
|
||||
* ``in`` op coerces a single string into a one-element list.
|
||||
|
||||
Engine evaluation (``BusinessContextEngine.evaluate``)
|
||||
* Severity gets bumped exactly when the predicate matches.
|
||||
* ``suppress`` short-circuits remaining rules deterministically.
|
||||
* Multiple matching rules layer their actions; tags accumulate
|
||||
without dupes; later rules override severity / route_to.
|
||||
* Field accessor walks dotted paths and treats missing keys as
|
||||
"no match" for non-existence ops.
|
||||
|
||||
Engine snapshots (``BusinessContextEngine.replace`` / ``snapshot_for``)
|
||||
* Rules sort by ``(priority, id)`` for determinism.
|
||||
* The reverse field index records every dotted path referenced.
|
||||
* ``replace`` is atomic: two callers swapping versions never see a
|
||||
mid-update intermediate.
|
||||
|
||||
Dry-run preview (``BusinessContextEngine.preview_against``)
|
||||
* Transient snapshot: doesn't mutate the registered tenant snapshot.
|
||||
* Per-alert ``before`` / ``after`` reflects the action layering.
|
||||
|
||||
Endpoint contract (``services/api/app/api/v1/endpoints/business_context.py``)
|
||||
* ``GET /rules`` returns the persisted YAML + parsed rules envelope.
|
||||
* ``POST /rules`` round-trips YAML and bumps the engine version.
|
||||
* ``POST /rules`` with bad YAML returns 422 with the parser message.
|
||||
* ``PUT /rules/{id}`` patches a single rule; rejects mismatched id.
|
||||
* ``DELETE /rules/{id}`` 204 on hit, 404 on miss.
|
||||
* ``POST /rules/preview`` returns one row per alert with sample_size /
|
||||
changed_count / suppressed_count + per-row before/after.
|
||||
* Save → preview round-trip lands inside the **1s** budget called
|
||||
out by the task spec.
|
||||
|
||||
The endpoint tests stub :class:`AuthUser` and the DB session directly
|
||||
(matching the saved-hunts test approach), so the whole suite runs with
|
||||
zero infrastructure.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import textwrap
|
||||
import time
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
from app.api.v1.endpoints import business_context as endpoint
|
||||
from app.services.business_context import (
|
||||
BusinessContextEngine,
|
||||
RuleParseError,
|
||||
load_rules_from_yaml,
|
||||
)
|
||||
from app.services.business_context.engine import (
|
||||
AlertEvaluation,
|
||||
EngineSnapshot,
|
||||
_apply_action,
|
||||
_projection,
|
||||
evaluate_condition,
|
||||
get_engine,
|
||||
measure_evaluation_latency,
|
||||
reset_engine_for_tests,
|
||||
)
|
||||
from app.services.business_context.models import (
|
||||
ALLOWED_OPS,
|
||||
ALLOWED_ROUTES,
|
||||
ALLOWED_SEVERITIES,
|
||||
BusinessContextRule,
|
||||
RuleAction,
|
||||
RuleCondition,
|
||||
)
|
||||
from fastapi import HTTPException
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Fixtures
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_state() -> None:
|
||||
"""Reset the global engine + in-memory rule store between tests."""
|
||||
reset_engine_for_tests()
|
||||
endpoint._reset_store_for_tests()
|
||||
yield
|
||||
reset_engine_for_tests()
|
||||
endpoint._reset_store_for_tests()
|
||||
|
||||
|
||||
def _user(tenant_id: uuid.UUID | None = None) -> SimpleNamespace:
|
||||
"""Auth stand-in; the endpoint only reads ``tenant_id`` and the
|
||||
permission helper."""
|
||||
|
||||
async def _allow(_perm: str, _db: Any) -> None:
|
||||
return None
|
||||
|
||||
return SimpleNamespace(
|
||||
tenant_id=tenant_id or uuid.uuid4(),
|
||||
user_id=uuid.uuid4(),
|
||||
role="admin",
|
||||
require_permission_db=_allow,
|
||||
)
|
||||
|
||||
|
||||
def _yaml(text: str) -> str:
|
||||
"""Strip leading indentation so triple-quoted YAML in tests parses."""
|
||||
return textwrap.dedent(text).strip() + "\n"
|
||||
|
||||
|
||||
def _alert(
|
||||
alert_id: str = "a-1",
|
||||
*,
|
||||
severity: str = "medium",
|
||||
route_to: str | None = None,
|
||||
tags: list[str] | None = None,
|
||||
target_tag: str = "prod",
|
||||
business_hours: bool = True,
|
||||
source: str = "aws",
|
||||
) -> dict[str, Any]:
|
||||
"""A minimal alert shaped like the dotted paths rules reference."""
|
||||
return {
|
||||
"id": alert_id,
|
||||
"severity": severity,
|
||||
"route_to": route_to,
|
||||
"tags": list(tags or []),
|
||||
"source": source,
|
||||
"alert": {
|
||||
"severity": severity,
|
||||
"source": source,
|
||||
"target": {"tag": target_tag},
|
||||
"time": {"is_business_hours": business_hours},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# YAML parser
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestParser:
|
||||
def test_empty_yaml_returns_empty_list(self) -> None:
|
||||
assert load_rules_from_yaml("") == []
|
||||
assert load_rules_from_yaml(" \n ") == []
|
||||
|
||||
def test_single_rule_shorthand(self) -> None:
|
||||
rules = load_rules_from_yaml(_yaml("""
|
||||
id: prod-iam-critical
|
||||
description: Critical for prod IAM
|
||||
when:
|
||||
field: alert.target.tag
|
||||
op: eq
|
||||
value: prod
|
||||
then:
|
||||
set_severity: critical
|
||||
"""))
|
||||
assert len(rules) == 1
|
||||
rule = rules[0]
|
||||
assert rule.id == "prod-iam-critical"
|
||||
assert rule.then.set_severity == "critical"
|
||||
assert rule.when.field == "alert.target.tag"
|
||||
assert rule.when.op == "eq"
|
||||
assert rule.when.value == "prod"
|
||||
|
||||
def test_rules_list_form(self) -> None:
|
||||
rules = load_rules_from_yaml(_yaml("""
|
||||
rules:
|
||||
- id: rule-a
|
||||
when: { field: alert.severity, op: eq, value: high }
|
||||
then: { set_severity: critical }
|
||||
- id: rule-b
|
||||
when: { field: alert.source, op: eq, value: aws }
|
||||
then: { route_to: cloud }
|
||||
"""))
|
||||
assert [r.id for r in rules] == ["rule-a", "rule-b"]
|
||||
assert rules[1].then.route_to == "cloud"
|
||||
|
||||
def test_aggregator_all_any_not(self) -> None:
|
||||
rules = load_rules_from_yaml(_yaml("""
|
||||
id: nested
|
||||
when:
|
||||
all:
|
||||
- any:
|
||||
- { field: alert.source, op: eq, value: aws }
|
||||
- { field: alert.source, op: eq, value: gcp }
|
||||
- not:
|
||||
field: alert.target.tag
|
||||
op: eq
|
||||
value: dev
|
||||
then:
|
||||
tag: cloud-prod
|
||||
"""))
|
||||
when = rules[0].when
|
||||
assert when.logical == "all"
|
||||
assert when.children[0].logical == "any"
|
||||
assert when.children[1].logical == "not"
|
||||
# Field-reverse-index covers the leaves under both legs of the
|
||||
# aggregator tree, not just the top-level node.
|
||||
assert when.fields_referenced() == {"alert.source", "alert.target.tag"}
|
||||
|
||||
def test_in_op_coerces_single_string_to_list(self) -> None:
|
||||
rules = load_rules_from_yaml(_yaml("""
|
||||
id: route-aws
|
||||
when: { field: alert.source, op: in, value: aws }
|
||||
then: { route_to: cloud }
|
||||
"""))
|
||||
assert rules[0].when.value == ["aws"]
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"yaml_text,marker",
|
||||
[
|
||||
("id: BAD\nwhen: { field: x, op: eq, value: y }\nthen: { tag: t }", "kebab-case"),
|
||||
("id: ok-id\nthen: { set_severity: high }", "'when' clause is required"),
|
||||
("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { set_severity: nope }",
|
||||
"set_severity"),
|
||||
("id: ok-id\nwhen: { field: x, op: like, value: y }\nthen: { tag: t }", "is not one of"),
|
||||
("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: {}", "must set at least one"),
|
||||
("id: ok-id\nwhen: { field: x, op: in }\nthen: { tag: t }", "required for op="),
|
||||
("id: ok-id\nwhen: { field: x, op: eq, value: y }\nthen: { route_to: nope }",
|
||||
"route_to"),
|
||||
],
|
||||
)
|
||||
def test_invalid_inputs_raise_with_actionable_messages(
|
||||
self, yaml_text: str, marker: str
|
||||
) -> None:
|
||||
with pytest.raises(RuleParseError) as exc_info:
|
||||
load_rules_from_yaml(yaml_text)
|
||||
assert marker in str(exc_info.value)
|
||||
|
||||
def test_duplicate_ids_rejected(self) -> None:
|
||||
with pytest.raises(RuleParseError, match="duplicate rule id"):
|
||||
load_rules_from_yaml(_yaml("""
|
||||
rules:
|
||||
- id: dup-rule
|
||||
when: { field: a, op: eq, value: 1 }
|
||||
then: { set_severity: low }
|
||||
- id: dup-rule
|
||||
when: { field: b, op: eq, value: 2 }
|
||||
then: { set_severity: high }
|
||||
"""))
|
||||
|
||||
def test_constants_are_locked_down(self) -> None:
|
||||
# Catches accidental edits that broaden the action vocabulary —
|
||||
# any new severity / route option must show up in this list.
|
||||
assert ALLOWED_SEVERITIES == ("info", "low", "medium", "high", "critical")
|
||||
assert "tier1" in ALLOWED_ROUTES and "tier2" in ALLOWED_ROUTES
|
||||
assert "eq" in ALLOWED_OPS and "exists" in ALLOWED_OPS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Engine — evaluation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestEvaluation:
|
||||
def test_severity_bump_when_predicate_matches(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
engine.replace(
|
||||
tenant,
|
||||
load_rules_from_yaml(_yaml("""
|
||||
id: prod-critical
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical }
|
||||
""")),
|
||||
)
|
||||
result = engine.evaluate(tenant, _alert(severity="medium", target_tag="prod"))
|
||||
assert result.before["severity"] == "medium"
|
||||
assert result.after["severity"] == "critical"
|
||||
assert result.matched_rule_ids == ["prod-critical"]
|
||||
assert result.changed is True
|
||||
|
||||
def test_no_match_leaves_alert_unchanged(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
engine.replace(
|
||||
tenant,
|
||||
load_rules_from_yaml(_yaml("""
|
||||
id: prod-only
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical }
|
||||
""")),
|
||||
)
|
||||
result = engine.evaluate(tenant, _alert(target_tag="dev", severity="medium"))
|
||||
assert result.before == result.after
|
||||
assert result.matched_rule_ids == []
|
||||
assert result.changed is False
|
||||
|
||||
def test_suppress_short_circuits_subsequent_rules(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
engine.replace(
|
||||
tenant,
|
||||
load_rules_from_yaml(_yaml("""
|
||||
rules:
|
||||
- id: maintenance-window
|
||||
priority: 1
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { suppress: true }
|
||||
- id: should-never-run
|
||||
priority: 50
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical }
|
||||
""")),
|
||||
)
|
||||
result = engine.evaluate(tenant, _alert(target_tag="prod", severity="medium"))
|
||||
assert result.suppressed is True
|
||||
assert result.matched_rule_ids == ["maintenance-window"]
|
||||
# ``should-never-run`` would have set severity if not for suppression.
|
||||
assert result.after["severity"] == "medium"
|
||||
|
||||
def test_actions_layer_in_priority_order(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
engine.replace(
|
||||
tenant,
|
||||
load_rules_from_yaml(_yaml("""
|
||||
rules:
|
||||
- id: aws-baseline
|
||||
priority: 10
|
||||
when: { field: alert.source, op: eq, value: aws }
|
||||
then: { route_to: cloud, tag: aws }
|
||||
- id: prod-bump
|
||||
priority: 50
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical, tag: prod }
|
||||
""")),
|
||||
)
|
||||
result = engine.evaluate(tenant, _alert(source="aws", target_tag="prod"))
|
||||
assert result.matched_rule_ids == ["aws-baseline", "prod-bump"]
|
||||
assert result.after["severity"] == "critical"
|
||||
assert result.after["route_to"] == "cloud"
|
||||
# Tags accumulate without duplicates and preserve insertion order.
|
||||
assert result.after["tags"] == ["aws", "prod"]
|
||||
|
||||
def test_missing_field_treated_as_non_match_for_value_ops(self) -> None:
|
||||
cond = RuleCondition(field="missing.path", op="eq", value="x")
|
||||
assert evaluate_condition(cond, {"alert": {"id": "a"}}) is False
|
||||
|
||||
def test_exists_distinguishes_missing_from_explicit_none(self) -> None:
|
||||
present = evaluate_condition(
|
||||
RuleCondition(field="alert.target.tag", op="exists"),
|
||||
{"alert": {"target": {"tag": None}}},
|
||||
)
|
||||
missing = evaluate_condition(
|
||||
RuleCondition(field="alert.target.tag", op="exists"),
|
||||
{"alert": {"target": {}}},
|
||||
)
|
||||
assert present is True
|
||||
assert missing is False
|
||||
|
||||
def test_apply_action_does_not_mutate_input(self) -> None:
|
||||
original = {"severity": "low", "tags": ["a"]}
|
||||
out = _apply_action(original, RuleAction(set_severity="high", tag="b"))
|
||||
assert out["severity"] == "high"
|
||||
assert sorted(out["tags"]) == ["a", "b"]
|
||||
assert original["severity"] == "low"
|
||||
assert original["tags"] == ["a"]
|
||||
|
||||
def test_projection_returns_only_ui_visible_fields(self) -> None:
|
||||
proj = _projection({"severity": "low", "noise": "yes", "tags": ["a"]})
|
||||
assert set(proj.keys()) == {"severity", "route_to", "tags", "suppressed"}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Engine — snapshots & hot-reload
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestSnapshots:
|
||||
def test_replace_returns_sorted_snapshot(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
snap = engine.replace(
|
||||
tenant,
|
||||
load_rules_from_yaml(_yaml("""
|
||||
rules:
|
||||
- id: zzz
|
||||
priority: 5
|
||||
when: { field: x, op: eq, value: 1 }
|
||||
then: { tag: zzz }
|
||||
- id: aaa
|
||||
priority: 100
|
||||
when: { field: y, op: eq, value: 1 }
|
||||
then: { tag: aaa }
|
||||
- id: mmm
|
||||
priority: 5
|
||||
when: { field: z, op: eq, value: 1 }
|
||||
then: { tag: mmm }
|
||||
""")),
|
||||
)
|
||||
assert [r.id for r in snap.rules] == ["mmm", "zzz", "aaa"]
|
||||
# Field reverse-index records all leaf paths.
|
||||
assert set(snap.field_index.keys()) == {"x", "y", "z"}
|
||||
|
||||
def test_version_bumps_on_each_replace(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
snap1 = engine.replace(tenant, [])
|
||||
snap2 = engine.replace(tenant, [])
|
||||
assert snap2.version == snap1.version + 1
|
||||
|
||||
def test_snapshot_is_per_tenant(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
a, b = uuid.uuid4(), uuid.uuid4()
|
||||
engine.replace(
|
||||
a,
|
||||
load_rules_from_yaml(_yaml("""
|
||||
id: only-a
|
||||
when: { field: x, op: eq, value: 1 }
|
||||
then: { tag: a }
|
||||
""")),
|
||||
)
|
||||
engine.replace(b, [])
|
||||
assert engine.snapshot_for(a).rules[0].id == "only-a"
|
||||
assert engine.snapshot_for(b).rules == ()
|
||||
|
||||
def test_get_engine_returns_singleton(self) -> None:
|
||||
e1 = get_engine()
|
||||
e2 = get_engine()
|
||||
assert e1 is e2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Engine — dry-run preview
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestPreview:
|
||||
def test_preview_does_not_mutate_registered_snapshot(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
# Register an empty rule set.
|
||||
engine.replace(tenant, [])
|
||||
# Preview a rule that would, if registered, mutate severity.
|
||||
candidate = load_rules_from_yaml(_yaml("""
|
||||
id: would-bump
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical }
|
||||
"""))
|
||||
results = engine.preview_against(
|
||||
tenant,
|
||||
[_alert(target_tag="prod", severity="medium")],
|
||||
rules=candidate,
|
||||
)
|
||||
assert results[0].after["severity"] == "critical"
|
||||
# Registered snapshot still empty.
|
||||
assert engine.snapshot_for(tenant).rules == ()
|
||||
|
||||
def test_preview_returns_one_row_per_alert(self) -> None:
|
||||
engine = BusinessContextEngine()
|
||||
tenant = uuid.uuid4()
|
||||
rules = load_rules_from_yaml(_yaml("""
|
||||
id: prod-critical
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical }
|
||||
"""))
|
||||
alerts = [
|
||||
_alert("a", target_tag="prod"),
|
||||
_alert("b", target_tag="dev"),
|
||||
_alert("c", target_tag="prod"),
|
||||
]
|
||||
results = engine.preview_against(tenant, alerts, rules=rules)
|
||||
assert [r.alert_id for r in results] == ["a", "b", "c"]
|
||||
assert [r.changed for r in results] == [True, False, True]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Endpoint contract
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _run(coro): # type: ignore[no-untyped-def]
|
||||
"""Drive an async endpoint coroutine to completion in a fresh loop.
|
||||
|
||||
Each call gets its own event loop so the per-test isolation that
|
||||
``_isolate_state`` provides extends to the asyncio runtime.
|
||||
"""
|
||||
loop = asyncio.new_event_loop()
|
||||
try:
|
||||
return loop.run_until_complete(coro)
|
||||
finally:
|
||||
loop.close()
|
||||
|
||||
|
||||
class TestEndpoints:
|
||||
def test_get_returns_empty_envelope_when_no_rules(self) -> None:
|
||||
user = _user()
|
||||
env = _run(endpoint.get_rules(user, MagicMock()))
|
||||
assert env.tenant_id == str(user.tenant_id)
|
||||
assert env.rules == []
|
||||
assert env.yaml == ""
|
||||
assert env.enabled is True
|
||||
assert env.version >= 1 # engine.replace always bumps
|
||||
|
||||
def test_post_replace_persists_yaml_and_returns_parsed_view(self) -> None:
|
||||
user = _user()
|
||||
yaml_text = _yaml("""
|
||||
id: prod-critical
|
||||
description: Bump prod alerts to critical
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical }
|
||||
""")
|
||||
env = _run(
|
||||
endpoint.replace_rules(
|
||||
endpoint.ReplaceRulesRequest(yaml=yaml_text),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
assert env.yaml == yaml_text
|
||||
assert len(env.rules) == 1
|
||||
assert env.rules[0].id == "prod-critical"
|
||||
assert env.rules[0].then.set_severity == "critical"
|
||||
# Subsequent GET sees the same persisted YAML.
|
||||
env2 = _run(endpoint.get_rules(user, MagicMock()))
|
||||
assert env2.yaml == yaml_text
|
||||
assert env2.rules[0].id == "prod-critical"
|
||||
|
||||
def test_post_replace_with_invalid_yaml_returns_422(self) -> None:
|
||||
user = _user()
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_run(
|
||||
endpoint.replace_rules(
|
||||
endpoint.ReplaceRulesRequest(yaml="id: BAD\nthen: { tag: t }"),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
assert exc_info.value.status_code == 422
|
||||
assert "kebab-case" in exc_info.value.detail
|
||||
|
||||
def test_put_patches_single_rule_by_id(self) -> None:
|
||||
user = _user()
|
||||
# Seed two rules.
|
||||
seed = _yaml("""
|
||||
rules:
|
||||
- id: rule-a
|
||||
when: { field: alert.severity, op: eq, value: high }
|
||||
then: { set_severity: critical }
|
||||
- id: rule-b
|
||||
when: { field: alert.source, op: eq, value: aws }
|
||||
then: { route_to: cloud }
|
||||
""")
|
||||
_run(
|
||||
endpoint.replace_rules(
|
||||
endpoint.ReplaceRulesRequest(yaml=seed),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
# Patch rule-a only.
|
||||
env = _run(
|
||||
endpoint.update_rule(
|
||||
"rule-a",
|
||||
endpoint.UpdateRuleRequest(
|
||||
yaml=(
|
||||
"id: rule-a\n"
|
||||
"when: { field: alert.severity, op: eq, value: high }\n"
|
||||
"then: { route_to: tier3 }\n"
|
||||
)
|
||||
),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
rules_by_id = {r.id: r for r in env.rules}
|
||||
assert rules_by_id["rule-a"].then.route_to == "tier3"
|
||||
assert rules_by_id["rule-a"].then.set_severity is None
|
||||
# rule-b untouched.
|
||||
assert rules_by_id["rule-b"].then.route_to == "cloud"
|
||||
|
||||
def test_put_rejects_id_mismatch(self) -> None:
|
||||
user = _user()
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_run(
|
||||
endpoint.update_rule(
|
||||
"rule-a",
|
||||
endpoint.UpdateRuleRequest(
|
||||
yaml=(
|
||||
"id: rule-other\n"
|
||||
"when: { field: x, op: eq, value: 1 }\n"
|
||||
"then: { tag: t }\n"
|
||||
)
|
||||
),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
assert exc_info.value.status_code == 422
|
||||
assert "must match" in exc_info.value.detail
|
||||
|
||||
def test_delete_removes_rule(self) -> None:
|
||||
user = _user()
|
||||
seed = _yaml("""
|
||||
rules:
|
||||
- id: keep
|
||||
when: { field: x, op: eq, value: 1 }
|
||||
then: { tag: keep }
|
||||
- id: drop
|
||||
when: { field: y, op: eq, value: 1 }
|
||||
then: { tag: drop }
|
||||
""")
|
||||
_run(
|
||||
endpoint.replace_rules(
|
||||
endpoint.ReplaceRulesRequest(yaml=seed),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
result = _run(endpoint.delete_rule("drop", user, MagicMock()))
|
||||
assert result is None
|
||||
env = _run(endpoint.get_rules(user, MagicMock()))
|
||||
assert [r.id for r in env.rules] == ["keep"]
|
||||
|
||||
def test_delete_404_when_rule_missing(self) -> None:
|
||||
user = _user()
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_run(endpoint.delete_rule("never-existed", user, MagicMock()))
|
||||
assert exc_info.value.status_code == 404
|
||||
|
||||
def test_preview_against_supplied_alerts(self) -> None:
|
||||
user = _user()
|
||||
req = endpoint.PreviewRequest(
|
||||
yaml=(
|
||||
"id: prod-critical\n"
|
||||
"when: { field: alert.target.tag, op: eq, value: prod }\n"
|
||||
"then: { set_severity: critical }\n"
|
||||
),
|
||||
alerts=[
|
||||
_alert("a", target_tag="prod", severity="medium"),
|
||||
_alert("b", target_tag="dev", severity="medium"),
|
||||
],
|
||||
)
|
||||
resp = _run(endpoint.preview_rules(req, user, MagicMock()))
|
||||
assert resp.sample_size == 2
|
||||
assert resp.changed_count == 1
|
||||
assert resp.suppressed_count == 0
|
||||
# First alert mutated, second untouched.
|
||||
first, second = resp.rows
|
||||
assert first.changed is True
|
||||
assert first.before["severity"] == "medium"
|
||||
assert first.after["severity"] == "critical"
|
||||
assert second.changed is False
|
||||
|
||||
def test_preview_invalid_yaml_returns_422(self) -> None:
|
||||
user = _user()
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_run(
|
||||
endpoint.preview_rules(
|
||||
endpoint.PreviewRequest(yaml="id: BAD\nthen: { tag: t }"),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
assert exc_info.value.status_code == 422
|
||||
|
||||
def test_preview_falls_back_to_sample_alerts_when_alerts_omitted(
|
||||
self,
|
||||
) -> None:
|
||||
user = _user()
|
||||
# Stub the DB so _fetch_sample_alerts can short-circuit without
|
||||
# the aisoc_alerts table existing in the test env.
|
||||
db = MagicMock()
|
||||
db.execute = AsyncMock(side_effect=RuntimeError("no schema"))
|
||||
req = endpoint.PreviewRequest(
|
||||
yaml=(
|
||||
"id: noop-tag\n"
|
||||
"when: { field: alert.target.tag, op: eq, value: prod }\n"
|
||||
"then: { tag: noop }\n"
|
||||
),
|
||||
alerts=[],
|
||||
)
|
||||
resp = _run(endpoint.preview_rules(req, user, db))
|
||||
assert resp.sample_size == 0
|
||||
assert resp.changed_count == 0
|
||||
assert resp.rows == []
|
||||
|
||||
def test_save_to_evaluate_round_trip_under_one_second(self) -> None:
|
||||
"""Task spec: rule mutating severity must be reflected within 1s
|
||||
of save. We measure save (POST /rules) + a 100-alert evaluation
|
||||
wall-clock; both operations live in the same process, so the
|
||||
budget is dominated by YAML parsing + condition evaluation
|
||||
rather than I/O.
|
||||
"""
|
||||
user = _user()
|
||||
yaml_text = _yaml("""
|
||||
rules:
|
||||
- id: prod-critical
|
||||
priority: 10
|
||||
when: { field: alert.target.tag, op: eq, value: prod }
|
||||
then: { set_severity: critical }
|
||||
- id: aws-cloud
|
||||
priority: 20
|
||||
when: { field: alert.source, op: eq, value: aws }
|
||||
then: { route_to: cloud, tag: aws }
|
||||
""")
|
||||
alerts = [
|
||||
_alert(f"alert-{i}", target_tag="prod" if i % 2 else "dev",
|
||||
source="aws" if i % 3 == 0 else "okta")
|
||||
for i in range(100)
|
||||
]
|
||||
|
||||
start = time.perf_counter()
|
||||
_run(
|
||||
endpoint.replace_rules(
|
||||
endpoint.ReplaceRulesRequest(yaml=yaml_text),
|
||||
user,
|
||||
MagicMock(),
|
||||
)
|
||||
)
|
||||
engine = get_engine()
|
||||
elapsed_eval = measure_evaluation_latency(engine, user.tenant_id, alerts)
|
||||
elapsed = time.perf_counter() - start
|
||||
|
||||
assert elapsed < 1.0, (
|
||||
f"save → evaluate round-trip took {elapsed:.3f}s, exceeds 1s budget "
|
||||
f"(eval slice = {elapsed_eval:.3f}s for 100 alerts)"
|
||||
)
|
||||
|
||||
# Sanity check: at least the prod alerts got bumped.
|
||||
result = engine.evaluate(user.tenant_id, _alert(target_tag="prod", source="aws"))
|
||||
assert result.after["severity"] == "critical"
|
||||
assert result.after["route_to"] == "cloud"
|
||||
Reference in New Issue
Block a user