Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(agents): Phase 1.5 cost-DoS governor (budgets, circuit breaker, dedup) (#421)
Beenu Arora04fff84a8140
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 00eea83f8..addab0394 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -325,6 +325,7 @@ jobs:tests/test_prompt_sanitizer.py \tests/test_prompt_envelope.py \tests/test_privacy_redactor.py \+ tests/test_cost_governor.py \-v --tb=short# ──────────────────────────────────────────────diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8974fe6af..aef465cd7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **Phase 1.5 — cost-DoS enforcement.** New `services/agents/app/core/cost_governor.py`: a per-tenant `CostGovernor` that turns the existing `aisoc_run_costs` telemetry into enforcement — rolling-window soft/hard USD budgets, a circuit breaker that drops investigations to deterministic-only mode once the hard cap is hit (instead of billing unboundedly), a per-alert token ceiling (`cap_tokens`), and an evidence-hash dedup cache so a flood of identical alerts costs one investigation, not N. Gated by `services/agents/tests/test_cost_governor.py` (10 tests incl. the headline 10 000-identical-alert flood asserting spend stays at exactly one run, and a distinct-alert flood asserting the circuit breaker bounds spend near the hard cap). Live-orchestrator wiring of `get_governor().check(...)` before the LLM call is the tracked continuation.+- **Phase 1.4 — evidence redaction pipeline (honest no-exfiltration).** New `services/agents/app/privacy/redactor.py`: a per-run, per-tenant, in-memory reversible `Pseudonymizer` that replaces the customer's identifying data (internal IPs, emails, file paths, secrets, internal hostnames, usernames) with opaque tokens (`USER_1`, `HOST_2`, `IP_3`) before evidence leaves the process, while preserving public threat indicators so the agent can still reason. `RedactionConfig` defaults every category on. Gated by `services/agents/tests/test_privacy_redactor.py` (golden-corpus assertion: zero raw customer PII survives; round-trip re-hydration; public IOCs preserved). Rewrote the README "no data exfiltration" differentiator to be precise per mode and added `docs/trust/data-flows.md` documenting exactly what leaves the perimeter (local air-gapped / hosted-with-redaction / hosted-raw). Contract-egress enforcement + air-gapped CI job + Helm egress NetworkPolicy are the tracked 1.4 continuation.- **Phase 1.3 — cross-store tenant isolation (Qdrant + harness).** Closed the Qdrant leak the reality audit flagged: `services/threatintel/app/storage/qdrant.py` had no tenant scoping at all (global collections, no filter, no `tenant_id` in payloads). Added `tenant_scope_filter` + tenant-stamped payloads + tenant-scoped point ids so a search as tenant A can never surface tenant B's private vectors, while global feed intel stays shared under a `SHARED_TENANT` sentinel (backward-compatible with the feed pipeline). Stood up a table-driven `tests/isolation/` suite (registry in `stores.py` so a new store cannot ship without an isolation entry) and a new `.github/workflows/isolation.yml` gate running the offline layer on every PR. Neo4j/Redis/ClickHouse/Kafka live-container replay is registered as `container_pending` for Phase 3's integration tier.diff --git a/services/agents/app/core/cost_governor.py b/services/agents/app/core/cost_governor.pynew file mode 100644index 000000000..235b131e4--- /dev/null+++ b/services/agents/app/core/cost_governor.py@@ -0,0 +1,235 @@+"""Per-tenant cost governor: enforcement layer over cost telemetry.++Phase 1.5 of the world-class program. Anyone who can generate alerts can+generate LLM spend. `cost_telemetry.py` *tracks* spend into `aisoc_run_costs`+but nothing enforces against it. This module adds the enforcement the plan+requires:++- **Per-tenant token/USD budgets** with a soft cap (warn) and a hard cap.+- **Circuit breaker**: once a tenant crosses the hard cap in the rolling+ window, investigations drop to deterministic-only mode (no LLM) instead of+ billing unboundedly.+- **Per-alert token ceiling**: a single alert can never request more than+ `max_tokens_per_alert`.+- **Dedup / caching of identical investigations** keyed by an evidence hash,+ so a flood of identical alerts costs one investigation, not N.++The governor is pure and deterministic (injectable clock, in-memory store by+default) so the 10k-identical-alert DoS bound can be unit-tested offline with+no DB or LLM. Production wires a DB-backed spend window; the enforcement logic+is identical.+"""++from __future__ import annotations++import hashlib+import json+import os+import time+from collections import deque+from collections.abc import Callable+from dataclasses import dataclass, field+from enum import Enum+from typing import Any++__all__ = [+ "BudgetConfig",+ "Decision",+ "GovernorDecision",+ "CostGovernor",+ "get_governor",+]+++@dataclass(frozen=True)+class BudgetConfig:+ """Per-tenant budget policy. All caps apply to a rolling window."""++ soft_usd: float = 50.0+ hard_usd: float = 100.0+ max_tokens_per_alert: int = 20_000+ window_seconds: int = 24 * 3600+ cache_ttl_seconds: int = 3600++ @classmethod+ def from_env(cls) -> BudgetConfig:+ def _f(name: str, default: float) -> float:+ try:+ return float(os.environ.get(name, "").strip() or default)+ except ValueError:+ return default++ def _i(name: str, default: int) -> int:+ try:+ return int(os.environ.get(name, "").strip() or default)+ except ValueError:+ return default++ return cls(+ soft_usd=_f("AISOC_BUDGET_SOFT_USD", 50.0),+ hard_usd=_f("AISOC_BUDGET_HARD_USD", 100.0),+ max_tokens_per_alert=_i("AISOC_MAX_TOKENS_PER_ALERT", 20_000),+ window_seconds=_i("AISOC_BUDGET_WINDOW_SECONDS", 24 * 3600),+ cache_ttl_seconds=_i("AISOC_INVESTIGATION_CACHE_TTL", 3600),+ )+++class Decision(str, Enum):+ ALLOW = "allow" # run the full (LLM) investigation+ DEDUPLICATED = "deduplicated" # identical investigation served from cache+ CIRCUIT_OPEN = "circuit_open" # budget exhausted -> deterministic-only+++@dataclass+class GovernorDecision:+ decision: Decision+ reason: str+ remaining_usd: float+ soft_breached: bool = False+ cached_verdict: dict[str, Any] | None = None++ @property+ def use_llm(self) -> bool:+ """Only a plain ALLOW may spend on the LLM."""+ return self.decision is Decision.ALLOW+++@dataclass+class _SpendEvent:+ ts: float+ usd: float+ tokens: int+++@dataclass+class _CacheEntry:+ verdict: dict[str, Any]+ expires_at: float+++@dataclass+class CostGovernor:+ """Enforces per-tenant budgets, dedup, and the deterministic circuit breaker."""++ config: BudgetConfig = field(default_factory=BudgetConfig)+ now: Callable[[], float] = time.monotonic+ _spend: dict[str, deque[_SpendEvent]] = field(default_factory=dict, init=False)+ _cache: dict[tuple[str, str], _CacheEntry] = field(default_factory=dict, init=False)++ # -- fingerprinting --------------------------------------------------------++ @staticmethod+ def evidence_fingerprint(tenant_id: str, alert: Any) -> str:+ """Stable hash of the investigation-relevant evidence.++ Identical alerts (same tenant + same canonical evidence) collapse to+ the same fingerprint so repeats hit the cache. Volatile fields+ (timestamps, alert ids) are excluded by the caller passing a canonical+ subset; here we hash whatever we are given, deterministically.+ """+ try:+ canonical = json.dumps(alert, sort_keys=True, default=str)+ except (TypeError, ValueError):+ canonical = str(alert)+ digest = hashlib.sha256(f"{tenant_id}\x00{canonical}".encode()).hexdigest()+ return digest++ # -- window accounting -----------------------------------------------------++ def _prune(self, tenant_id: str) -> deque[_SpendEvent]:+ window_start = self.now() - self.config.window_seconds+ dq = self._spend.setdefault(tenant_id, deque())+ while dq and dq[0].ts < window_start:+ dq.popleft()+ return dq++ def spent_usd(self, tenant_id: str) -> float:+ return sum(e.usd for e in self._prune(tenant_id))++ def spent_tokens(self, tenant_id: str) -> int:+ return sum(e.tokens for e in self._prune(tenant_id))++ # -- enforcement -----------------------------------------------------------++ def cap_tokens(self, requested_tokens: int) -> int:+ """Clamp a per-alert token request to the ceiling."""+ return max(0, min(int(requested_tokens), self.config.max_tokens_per_alert))++ def check(self, tenant_id: str, fingerprint: str) -> GovernorDecision:+ """Decide how to handle an incoming investigation.++ Order: dedup cache -> circuit breaker -> allow. Dedup wins even when+ the circuit is open, because serving a cached verdict costs nothing.+ """+ now = self.now()++ cached = self._cache.get((tenant_id, fingerprint))+ if cached is not None and cached.expires_at > now:+ return GovernorDecision(+ decision=Decision.DEDUPLICATED,+ reason="identical investigation served from cache",+ remaining_usd=max(0.0, self.config.hard_usd - self.spent_usd(tenant_id)),+ soft_breached=self.spent_usd(tenant_id) >= self.config.soft_usd,+ cached_verdict=cached.verdict,+ )++ spent = self.spent_usd(tenant_id)+ remaining = max(0.0, self.config.hard_usd - spent)+ if spent >= self.config.hard_usd:+ return GovernorDecision(+ decision=Decision.CIRCUIT_OPEN,+ reason=f"tenant hard budget ${self.config.hard_usd:.2f} exhausted; deterministic-only",+ remaining_usd=0.0,+ soft_breached=True,+ )++ return GovernorDecision(+ decision=Decision.ALLOW,+ reason="within budget",+ remaining_usd=remaining,+ soft_breached=spent >= self.config.soft_usd,+ )++ def record_spend(self, tenant_id: str, usd: float, tokens: int) -> None:+ dq = self._prune(tenant_id)+ dq.append(_SpendEvent(ts=self.now(), usd=max(0.0, usd), tokens=max(0, tokens)))++ def record_verdict(+ self,+ tenant_id: str,+ fingerprint: str,+ verdict: dict[str, Any],+ *,+ usd: float,+ tokens: int,+ ) -> None:+ """Cache the verdict for dedup and account the spend it incurred."""+ self._cache[(tenant_id, fingerprint)] = _CacheEntry(+ verdict=verdict,+ expires_at=self.now() + self.config.cache_ttl_seconds,+ )+ self.record_spend(tenant_id, usd, tokens)++ def state(self, tenant_id: str) -> dict[str, Any]:+ spent = self.spent_usd(tenant_id)+ return {+ "tenant_id": tenant_id,+ "spent_usd": round(spent, 6),+ "soft_usd": self.config.soft_usd,+ "hard_usd": self.config.hard_usd,+ "soft_breached": spent >= self.config.soft_usd,+ "hard_breached": spent >= self.config.hard_usd,+ "spent_tokens": self.spent_tokens(tenant_id),+ "cached_entries": sum(1 for k in self._cache if k[0] == tenant_id),+ }+++_GOVERNOR: CostGovernor | None = None+++def get_governor() -> CostGovernor:+ """Process-wide governor singleton (config from env)."""+ global _GOVERNOR+ if _GOVERNOR is None:+ _GOVERNOR = CostGovernor(config=BudgetConfig.from_env())+ return _GOVERNORdiff --git a/services/agents/tests/test_cost_governor.py b/services/agents/tests/test_cost_governor.pynew file mode 100644index 000000000..67913a46f--- /dev/null+++ b/services/agents/tests/test_cost_governor.py@@ -0,0 +1,178 @@+"""Tests for the per-tenant CostGovernor (Phase 1.5 cost-DoS enforcement).++Hermetic: injectable clock, in-memory store, no DB/LLM. The headline test is+the 10k-identical-alert flood asserting bounded spend.+"""++from __future__ import annotations++from app.core.cost_governor import (+ BudgetConfig,+ CostGovernor,+ Decision,+ get_governor,+)+++class FakeClock:+ def __init__(self) -> None:+ self.t = 1000.0++ def __call__(self) -> float:+ return self.t++ def advance(self, seconds: float) -> None:+ self.t += seconds+++def _cfg(**kw) -> BudgetConfig:+ base = {+ "soft_usd": 5.0,+ "hard_usd": 10.0,+ "max_tokens_per_alert": 20_000,+ "window_seconds": 3600,+ "cache_ttl_seconds": 3600,+ }+ base.update(kw)+ return BudgetConfig(**base)+++# ── The DoS bound: 10k identical alerts cost one investigation ────────────────+++def test_flood_of_identical_alerts_is_deduplicated_to_one_spend():+ clock = FakeClock()+ gov = CostGovernor(config=_cfg(), now=clock)+ tenant = "t1"+ alert = {"category": "malware", "host": "web-1", "signature": "sig-abc"}+ fp = gov.evidence_fingerprint(tenant, alert)++ per_run_cost = 0.05+ allowed = 0+ deduped = 0+ for _ in range(10_000):+ d = gov.check(tenant, fp)+ if d.decision is Decision.ALLOW:+ allowed += 1+ # simulate the investigation running and caching its verdict+ gov.record_verdict(tenant, fp, {"verdict": "malicious"}, usd=per_run_cost, tokens=1500)+ elif d.decision is Decision.DEDUPLICATED:+ deduped += 1+ assert d.cached_verdict == {"verdict": "malicious"}++ assert allowed == 1, "identical alerts must only run once"+ assert deduped == 9_999+ # Total spend is exactly one run, not 10k runs.+ assert abs(gov.spent_usd(tenant) - per_run_cost) < 1e-9+++# ── Circuit breaker bounds spend on distinct alerts ───────────────────────────+++def test_distinct_alert_flood_trips_circuit_breaker_and_bounds_spend():+ clock = FakeClock()+ gov = CostGovernor(config=_cfg(hard_usd=10.0), now=clock)+ tenant = "t2"++ per_run_cost = 1.0+ llm_runs = 0+ deterministic_runs = 0+ for i in range(10_000):+ alert = {"category": "malware", "host": f"host-{i}", "signature": f"sig-{i}"}+ fp = gov.evidence_fingerprint(tenant, alert)+ d = gov.check(tenant, fp)+ if d.decision is Decision.ALLOW:+ llm_runs += 1+ gov.record_verdict(tenant, fp, {"verdict": "benign"}, usd=per_run_cost, tokens=1000)+ elif d.decision is Decision.CIRCUIT_OPEN:+ deterministic_runs += 1+ assert d.use_llm is False++ # Spend is capped near the hard budget, not 10k * per_run_cost.+ assert gov.spent_usd(tenant) <= 10.0 + per_run_cost+ assert llm_runs <= 10+ assert deterministic_runs >= 9_000+ assert gov.state(tenant)["hard_breached"] is True+++def test_circuit_reopens_after_window_expires():+ clock = FakeClock()+ gov = CostGovernor(config=_cfg(hard_usd=10.0, window_seconds=3600), now=clock)+ tenant = "t3"+ gov.record_spend(tenant, usd=10.0, tokens=5000)+ assert gov.check(tenant, "fp").decision is Decision.CIRCUIT_OPEN+ # advance past the window; old spend ages out+ clock.advance(3601)+ assert gov.check(tenant, "fp").decision is Decision.ALLOW+ assert gov.spent_usd(tenant) == 0.0+++# ── Per-alert token ceiling ───────────────────────────────────────────────────+++def test_per_alert_token_ceiling():+ gov = CostGovernor(config=_cfg(max_tokens_per_alert=20_000))+ assert gov.cap_tokens(1_000_000) == 20_000+ assert gov.cap_tokens(5_000) == 5_000+ assert gov.cap_tokens(-3) == 0+++# ── Soft cap precedes hard cap ────────────────────────────────────────────────+++def test_soft_breach_flagged_before_hard():+ clock = FakeClock()+ gov = CostGovernor(config=_cfg(soft_usd=5.0, hard_usd=10.0), now=clock)+ tenant = "t4"+ gov.record_spend(tenant, usd=6.0, tokens=1000) # over soft, under hard+ d = gov.check(tenant, "fp")+ assert d.decision is Decision.ALLOW+ assert d.soft_breached is True+ assert gov.state(tenant)["hard_breached"] is False+++# ── Dedup wins even when circuit is open ──────────────────────────────────────+++def test_cached_verdict_served_even_when_circuit_open():+ clock = FakeClock()+ gov = CostGovernor(config=_cfg(hard_usd=10.0), now=clock)+ tenant = "t5"+ fp = gov.evidence_fingerprint(tenant, {"a": 1})+ gov.record_verdict(tenant, fp, {"verdict": "malicious"}, usd=10.0, tokens=1000) # trips hard cap + caches+ d = gov.check(tenant, fp)+ assert d.decision is Decision.DEDUPLICATED+ assert d.cached_verdict == {"verdict": "malicious"}+++def test_cache_expiry_falls_back_to_circuit_or_allow():+ clock = FakeClock()+ gov = CostGovernor(config=_cfg(hard_usd=100.0, cache_ttl_seconds=60), now=clock)+ tenant = "t6"+ fp = gov.evidence_fingerprint(tenant, {"a": 1})+ gov.record_verdict(tenant, fp, {"v": 1}, usd=0.01, tokens=10)+ assert gov.check(tenant, fp).decision is Decision.DEDUPLICATED+ clock.advance(61)+ assert gov.check(tenant, fp).decision is Decision.ALLOW # cache expired, budget fine+++# ── fingerprint + config + singleton ──────────────────────────────────────────+++def test_fingerprint_is_stable_and_tenant_scoped():+ gov = CostGovernor(config=_cfg())+ a = {"category": "malware", "host": "h1"}+ assert gov.evidence_fingerprint("t1", a) == gov.evidence_fingerprint("t1", dict(reversed(list(a.items()))))+ assert gov.evidence_fingerprint("t1", a) != gov.evidence_fingerprint("t2", a)+++def test_config_from_env(monkeypatch):+ monkeypatch.setenv("AISOC_BUDGET_HARD_USD", "250")+ monkeypatch.setenv("AISOC_MAX_TOKENS_PER_ALERT", "9000")+ cfg = BudgetConfig.from_env()+ assert cfg.hard_usd == 250.0+ assert cfg.max_tokens_per_alert == 9000+++def test_get_governor_is_singleton():+ assert get_governor() is get_governor()