Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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

feat(agents): Phase 1.4 evidence redaction pipeline (honest no-exfil) (#419)

Beenu Arora410c73e2aa7a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 675a5df64..00eea83f8 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -324,6 +324,7 @@ jobs:
tests/test_fusion_client.py \
tests/test_prompt_sanitizer.py \
tests/test_prompt_envelope.py \
+ tests/test_privacy_redactor.py \
-v --tb=short
# ──────────────────────────────────────────────
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6976e2e28..8974fe6af 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.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.
- **Phase 1.2 — memory-poisoning defenses for the override-learning loop.** New pure `services/api/app/services/memory_poisoning.py`: provenance on every memory write (`MemoryProvenance` — no anonymous memory), trust weighting (verified human outranks autonomous closure) with age decay so lessons must be re-confirmed, a `PoisoningDetector` that flags a burst of same-signature false-positive dispositions from low-trust authors, and blast-radius controls for retroactive re-disposition (`plan_redisposition` + `compute_confirmation_token`: capped batches, explicit confirmation token over the exact alert set, quarantine on flagged signatures). Wired into `override_learning.py` (poisoning-resistant signature key now includes the entity-independent severity band; provenance stamped on writes; `apply_redisposition` requires the token and enforces the cap) and the `/feedback` endpoints (preview returns the token + quarantine state; apply rejects stale/tampered/over-cap batches with 409). The farming-attack eval (`services/api/tests/test_memory_poisoning.py::test_farming_attack_then_real_attack_is_not_auto_closed`) gates the api job: a poisoned signature is flagged and its retroactive apply quarantined, so the real intrusion is not auto-closed.
diff --git a/README.md b/README.md
index dc5d34444..58d494730 100644
--- a/README.md
+++ b/README.md
@@ -60,7 +60,7 @@ Three properties distinguish it from closed-source AI SOC vendors:
1. **Agent decisions are logged.** The Investigation Ledger stores the LLM prompt, the response, the evidence cited, and the downstream tool calls for every step of every run. Replays are available later.
2. **The substrate has a public eval harness in CI.** Five suites gate every PR targeting `main` / `develop` — alert reduction is a real measurement against a fixed 1 000-alert stream; three rubric-based suites are substrate self-consistency gates over a deterministic 200-incident dataset (55 templates) with per-template macros; a fifth gate validates the backing telemetry corpus. The [benchmark page](apps/docs/docs/benchmark.md) documents exactly what each suite measures and what it does not.
-3. **It runs entirely on your infrastructure.** No callbacks to a vendor cloud and no data exfiltration for "model improvement."
+3. **You control what leaves your perimeter.** No callbacks to a vendor cloud and no "model improvement" telemetry. With a hosted LLM, evidence is pseudonymized by default (internal IPs, hostnames, emails, paths, secrets, usernames become opaque tokens); run a local model (Ollama/vLLM) for a fully air-gapped path. Exactly what leaves under each mode: [`docs/trust/data-flows.md`](docs/trust/data-flows.md).
The orchestrator is a ~600-line LangGraph in [`services/agents/`](services/agents/). It is small enough to read end-to-end, swap models in, and patch.
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 035dcdc97..a733d2baa 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -16,7 +16,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Investigation Ledger stores every step | README L61, L169 | `ci.yml :: api tests` (`audit_hash`, audit immutability) | PARTIAL (write path gated; UI replay only in hermetic e2e) | Phase 3.2 |
| Public eval harness gates every PR | README L62, L77 | `ci.yml :: p1-eval` | GATED (but suites are self-consistency; see reality report) | Phase 4 |
| Alert-reduction is a real measurement | README L62 | `ci.yml :: p1-eval` (`alert_reduction`) | PARTIAL (gates an in-test fusion re-impl, not `services/fusion`) | Phase 4 |
-| Runs entirely on your infrastructure / no data exfiltration | README L63 | none | NO GATE | Phase 1.4 |
+| Runs entirely on your infrastructure / no data exfiltration | README L63 | `ci.yml :: python-test` (agents) runs `test_privacy_redactor.py` (zero raw PII survives) | PARTIAL (redaction gated + README made precise per mode; air-gapped egress-blocked CI + Helm NetworkPolicy in continuation/Phase 2) | Phase 2 |
| Detection-as-Code rejects candidates that regress MITRE accuracy | README L170 | `ci.yml :: p1-eval` (w2-dac baseline) | PARTIAL (circular: candidate `rule_body` never evaluated) | Phase 4 |
| 800+ native detection rules | README L78, L170 | `validate-detections.yml` (strict fixture replay) | GATED | - |
| 6000+ imported detection rules | README L78 | `validate-detections.yml` (parse/provenance) | PARTIAL (97% quarantined/non-executable; heatmap is tag-based) | Phase 4 Tier 3 |
@@ -39,7 +39,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
- GATED: 9
-- PARTIAL: 13
-- NO GATE: 5 (Phase 1.1 moved prompt-injection resistance to PARTIAL; Phase 1.3 moved non-Postgres tenant isolation to PARTIAL)
+- PARTIAL: 14
+- NO GATE: 4 (Phases 1.1/1.3/1.4 moved prompt-injection, non-Postgres isolation, and no-data-exfiltration from NO GATE to PARTIAL)
The Definition of Done requires zero `NO GATE` and zero unclosed `PARTIAL`. Each row's "Closes in" column is the binding commitment.
diff --git a/docs/trust/data-flows.md b/docs/trust/data-flows.md
new file mode 100644
index 000000000..25c368960
--- /dev/null
+++ b/docs/trust/data-flows.md
@@ -0,0 +1,46 @@
+# Data flows and egress
+
+Phase 1.4 of the world-class program. This page states exactly what leaves your
+perimeter under each configuration, so the README's "runs on your
+infrastructure" claim is precise rather than aspirational.
+
+## What never leaves
+
+- AiSOC sends **no telemetry to the AiSOC project** and makes no "model
+ improvement" callbacks. There is no phone-home. (Gated: Phase 12 trust
+ surface adds a no-telemetry CI assertion.)
+- Your database, object storage, graph, cache, and Kafka spine stay on your
+ infrastructure.
+
+## The one egress that exists: your chosen LLM
+
+The investigation agent calls an LLM you configure. There are three modes:
+
+1. **Local model (fully air-gapped).** Point `AISOC_LLM_*` at Ollama / vLLM /
+ llama.cpp. No evidence leaves your network at all. This is the only mode in
+ which the "no data leaves" claim is unconditionally true.
+2. **Hosted LLM with redaction (default).** When you configure a cloud provider
+ (Anthropic/OpenAI), evidence is pseudonymized before egress by
+ `services/agents/app/privacy/redactor.py`: internal IPs, emails, file paths,
+ secrets, internal hostnames, and usernames are replaced with opaque,
+ per-run, in-memory tokens (`USER_1`, `HOST_2`, `IP_3`). The LLM reasons over
+ tokens; the ledger and console re-hydrate real values locally. Public threat
+ indicators (external domains/IPs) are preserved so the agent can reason about
+ them. Gated: `services/agents/tests/test_privacy_redactor.py` asserts zero
+ raw customer PII survives redaction.
+3. **Hosted LLM without redaction (opt-out).** If you disable redaction, raw
+ evidence reaches the provider. Use only with a provider under a signed
+ zero-retention agreement.
+
+## Egress allowlist
+
+The only outbound destinations under normal operation are the LLM provider you
+configure and the threat-intel feeds you enable. A rendered Kubernetes
+`NetworkPolicy` that enforces this allowlist ships with the Helm chart (Phase 1.4
+continuation / Phase 2); until then, restrict egress at your network layer.
+
+## Air-gapped verification (planned gate)
+
+Phase 1.4 continuation adds a CI job that runs a full investigation with network
+egress blocked and asserts success on the local-model path — proving mode 1 is
+genuinely air-gapped, not just documented.
diff --git a/services/agents/app/privacy/__init__.py b/services/agents/app/privacy/__init__.py
new file mode 100644
index 000000000..2e89e36cb
--- /dev/null
+++ b/services/agents/app/privacy/__init__.py
@@ -0,0 +1,11 @@
+"""Privacy / redaction primitives for the investigation agent.
+
+The single sanctioned way to pseudonymize untrusted evidence before it leaves
+the process for a third-party LLM. See :mod:`app.privacy.redactor`.
+"""
+
+from __future__ import annotations
+
+from app.privacy.redactor import Pseudonymizer, RedactionConfig, default_pseudonymizer
+
+__all__ = ["Pseudonymizer", "RedactionConfig", "default_pseudonymizer"]
diff --git a/services/agents/app/privacy/redactor.py b/services/agents/app/privacy/redactor.py
new file mode 100644
index 000000000..7c1fe65f0
--- /dev/null
+++ b/services/agents/app/privacy/redactor.py
@@ -0,0 +1,168 @@
+"""Reversible pseudonymization of evidence before it leaves the process.
+
+Phase 1.4 of the world-class program. The README promises "no data
+exfiltration", yet the default path sends raw evidence to a third-party LLM.
+This module pseudonymizes the *customer's* identifying data — internal IPs,
+emails, file paths, secrets, internal hostnames, usernames — through a per-run,
+per-tenant, in-memory-only bidirectional map. The LLM reasons over ``USER_1``,
+``HOST_2``, ``IP_3``; the ledger and console re-hydrate the real values locally
+via :meth:`Pseudonymizer.rehydrate`.
+
+Public threat indicators (external domains/IPs) are intentionally *not*
+redacted by default: they are IOCs, not customer PII, and the agent needs them
+to reason. This is a deliberate, documented trade-off (see docs/trust/).
+
+Pure/synchronous, stdlib only, so it is unit-testable offline and gated: a
+golden-corpus test asserts zero raw customer PII survives redaction.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from typing import Any
+
+__all__ = ["RedactionConfig", "Pseudonymizer", "default_pseudonymizer"]
+
+# Field-name hints whose *values* are treated as usernames when redacting
+# structured evidence.
+_USER_FIELD_HINTS = frozenset({"user", "username", "user_name", "account", "actor", "principal", "samaccountname", "upn", "subject"})
+
+_EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}\b")
+# Windows (C:\...), UNC (\\host\share), and multi-segment unix paths.
+_WIN_PATH_RE = re.compile(r"[A-Za-z]:\\[^\s\"']+")
+_UNC_PATH_RE = re.compile(r"\\\\[^\s\"']+")
+_UNIX_PATH_RE = re.compile(r"(?:/[A-Za-z0-9._\-]+){2,}/?")
+# DOMAIN\user (down-level logon name).
+_DOMAIN_USER_RE = re.compile(r"\b[A-Za-z0-9.\-]+\\[A-Za-z0-9._\-]+")
+# Common secret shapes: AWS keys, OpenAI-style, bearer/JWT, private key headers.
+_SECRET_RES: tuple[re.Pattern[str], ...] = (
+ re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
+ re.compile(r"\b(?:sk|rk)-[A-Za-z0-9]{20,}\b"),
+ re.compile(r"\bghp_[A-Za-z0-9]{36}\b"),
+ re.compile(r"\beyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\b"), # JWT
+ re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),
+)
+_IPV4_RE = re.compile(r"\b\d{1,3}(?:\.\d{1,3}){3}\b")
+# FQDNs; only redacted when the suffix is in the internal set.
+_FQDN_RE = re.compile(r"\b(?:[A-Za-z0-9](?:[A-Za-z0-9\-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,}\b")
+
+_DEFAULT_INTERNAL_SUFFIXES = (".local", ".internal", ".corp", ".lan", ".intranet", ".home.arpa")
+
+
+@dataclass(frozen=True)
+class RedactionConfig:
+ """What to pseudonymize. Defaults are on (fail-safe for the no-exfil claim)."""
+
+ redact_internal_ips: bool = True
+ redact_emails: bool = True
+ redact_paths: bool = True
+ redact_secrets: bool = True
+ redact_internal_hostnames: bool = True
+ redact_usernames: bool = True
+ # Extra domain suffixes considered internal (customer-configurable).
+ internal_domain_suffixes: tuple[str, ...] = _DEFAULT_INTERNAL_SUFFIXES
+
+
+def _is_internal_ip(value: str) -> bool:
+ try:
+ ip = ipaddress.ip_address(value)
+ except ValueError:
+ return False
+ return ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved
+
+
+class Pseudonymizer:
+ """Per-run, per-tenant reversible entity map held only in memory."""
+
+ def __init__(self, *, tenant_id: str = "", config: RedactionConfig | None = None) -> None:
+ self.tenant_id = tenant_id
+ self.config = config or RedactionConfig()
+ self._to_token: dict[str, str] = {}
+ self._to_original: dict[str, str] = {}
+ self._counters: dict[str, int] = {}
+
+ # -- public API ------------------------------------------------------------
+
+ @property
+ def mapping(self) -> dict[str, str]:
+ """token -> original, for local (never-egress) re-hydration."""
+ return dict(self._to_original)
+
+ def redact(self, text: str) -> str:
+ if not text or not isinstance(text, str):
+ return text if isinstance(text, str) else ""
+ out = text
+ # Order matters: secrets/emails/paths/domain-user before bare IPs/hosts,
+ # so a token like EMAIL_1 is never re-matched by a later pattern.
+ if self.config.redact_secrets:
+ for pat in _SECRET_RES:
+ out = pat.sub(lambda m: self._token("SECRET", m.group(0)), out)
+ if self.config.redact_emails:
+ out = _EMAIL_RE.sub(lambda m: self._token("EMAIL", m.group(0)), out)
+ # Paths before DOMAIN\user: a Windows path (C:\Users\alice\...) contains
+ # backslash-separated segments that would otherwise be mis-matched as a
+ # down-level logon name and fragment the path.
+ if self.config.redact_paths:
+ out = _WIN_PATH_RE.sub(lambda m: self._token("PATH", m.group(0)), out)
+ out = _UNC_PATH_RE.sub(lambda m: self._token("PATH", m.group(0)), out)
+ out = _UNIX_PATH_RE.sub(lambda m: self._token("PATH", m.group(0)), out)
+ if self.config.redact_usernames:
+ out = _DOMAIN_USER_RE.sub(lambda m: self._token("USER", m.group(0)), out)
+ if self.config.redact_internal_hostnames:
+ out = _FQDN_RE.sub(self._maybe_internal_host, out)
+ if self.config.redact_internal_ips:
+ out = _IPV4_RE.sub(self._maybe_internal_ip, out)
+ return out
+
+ def redact_value(self, value: Any, *, _key: str | None = None) -> Any:
+ """Recursively redact a JSON-like value. Values under user-ish keys are
+ pseudonymized as usernames even if they are plain identifiers."""
+ if isinstance(value, str):
+ if _key and self.config.redact_usernames and _key.lower() in _USER_FIELD_HINTS and "@" not in value:
+ return self._token("USER", value)
+ return self.redact(value)
+ if isinstance(value, Mapping):
+ return {k: self.redact_value(v, _key=str(k)) for k, v in value.items()}
+ if isinstance(value, Sequence) and not isinstance(value, str | bytes):
+ return [self.redact_value(v) for v in value]
+ return value
+
+ def rehydrate(self, text: str) -> str:
+ """Reverse redaction locally (never send the result to the LLM)."""
+ if not text:
+ return text
+ out = text
+ # Replace longer tokens first to avoid USER_1 clobbering USER_10.
+ for token in sorted(self._to_original, key=len, reverse=True):
+ out = out.replace(token, self._to_original[token])
+ return out
+
+ # -- internals -------------------------------------------------------------
+
+ def _token(self, kind: str, original: str) -> str:
+ if original in self._to_token:
+ return self._to_token[original]
+ self._counters[kind] = self._counters.get(kind, 0) + 1
+ token = f"{kind}_{self._counters[kind]}"
+ self._to_token[original] = token
+ self._to_original[token] = original
+ return token
+
+ def _maybe_internal_ip(self, m: re.Match[str]) -> str:
+ val = m.group(0)
+ return self._token("IP", val) if _is_internal_ip(val) else val
+
+ def _maybe_internal_host(self, m: re.Match[str]) -> str:
+ host = m.group(0)
+ lowered = host.lower()
+ if any(lowered.endswith(sfx) for sfx in self.config.internal_domain_suffixes):
+ return self._token("HOST", host)
+ return host
+
+
+def default_pseudonymizer(tenant_id: str = "") -> Pseudonymizer:
+ """A pseudonymizer with all redaction on (the safe default for no-exfil)."""
+ return Pseudonymizer(tenant_id=tenant_id, config=RedactionConfig())
diff --git a/services/agents/tests/test_privacy_redactor.py b/services/agents/tests/test_privacy_redactor.py
new file mode 100644
index 000000000..9d1b9b1d5
--- /dev/null
+++ b/services/agents/tests/test_privacy_redactor.py
@@ -0,0 +1,107 @@
+"""Tests for the evidence pseudonymizer (Phase 1.4).
+
+Pure/offline: app.privacy.redactor is stdlib-only, so this imports directly.
+Gated in the CI agents job.
+"""
+
+from __future__ import annotations
+
+from app.privacy.redactor import Pseudonymizer, RedactionConfig, default_pseudonymizer
+
+# Realistic mixed evidence: customer PII + public threat indicators.
+GOLDEN = (
+ "User ACME\\alice logged in from 10.0.0.5 to DC01.acme.local, "
+ "opened C:\\Users\\alice\\secret.docx, emailed [email protected], "
+ "then beaconed to evil-c2.example (8.8.8.8) using key AKIAIOSFODNN7EXAMPLE."
+)
+
+# Raw customer values that must NEVER survive redaction.
+CUSTOMER_PII = [
+ "ACME\\alice",
+ "10.0.0.5",
+ "DC01.acme.local",
+ "C:\\Users\\alice\\secret.docx",
+ "AKIAIOSFODNN7EXAMPLE",
+]
+
+# Public threat indicators that SHOULD survive (they are IOCs, not PII).
+PUBLIC_IOCS = ["evil-c2.example", "8.8.8.8"]
+
+
+def test_zero_raw_customer_pii_survives_redaction():
+ p = default_pseudonymizer(tenant_id="t1")
+ redacted = p.redact(GOLDEN)
+ for pii in CUSTOMER_PII:
+ assert pii not in redacted, f"raw PII leaked into outbound payload: {pii!r} in {redacted!r}"
+
+
+def test_public_iocs_are_preserved_for_analysis():
+ p = default_pseudonymizer()
+ redacted = p.redact(GOLDEN)
+ for ioc in PUBLIC_IOCS:
+ assert ioc in redacted, f"public IOC was over-redacted: {ioc!r}"
+
+
+def test_tokens_are_typed_and_present():
+ p = default_pseudonymizer()
+ redacted = p.redact(GOLDEN)
+ assert "IP_1" in redacted # internal IP
+ assert any(t in redacted for t in ("EMAIL_1", "EMAIL_2"))
+ assert any(t in redacted for t in ("PATH_1", "PATH_2"))
+ assert any(t.startswith("SECRET_") for t in p.mapping)
+ assert any(t.startswith("USER_") for t in p.mapping)
+
+
+def test_rehydrate_round_trips():
+ p = default_pseudonymizer()
+ redacted = p.redact(GOLDEN)
+ assert p.rehydrate(redacted) == GOLDEN
+
+
+def test_tokens_are_stable_within_a_run():
+ p = default_pseudonymizer()
+ a = p.redact("host 10.0.0.5 and again 10.0.0.5")
+ # Same original -> same token, both occurrences.
+ assert a.count("IP_1") == 2
+
+
+def test_public_ip_not_redacted_internal_ip_is():
+ p = default_pseudonymizer()
+ out = p.redact("internal 192.168.1.9 external 1.1.1.1")
+ assert "192.168.1.9" not in out
+ assert "1.1.1.1" in out
+
+
+def test_structured_username_field_is_pseudonymized():
+ p = default_pseudonymizer()
+ out = p.redact_value({"username": "bob", "action": "login", "src_ip": "10.1.2.3"})
+ assert out["username"].startswith("USER_")
+ assert out["action"] == "login"
+ assert out["src_ip"] != "10.1.2.3" # internal IP redacted inside string value
+
+
+def test_config_can_disable_a_category():
+ # Disable emails + internal hostnames so the full address survives; IPs stay on.
+ p = Pseudonymizer(config=RedactionConfig(redact_emails=False, redact_internal_hostnames=False))
+ out = p.redact("mail [email protected] from 10.0.0.5")
+ assert "[email protected]" in out # emails off (and host off, so domain survives)
+ assert "10.0.0.5" not in out # ips still on
+
+
+def test_mapping_is_per_instance():
+ p1 = default_pseudonymizer()
+ p2 = default_pseudonymizer()
+ p1.redact("10.0.0.5")
+ assert p1.mapping # p1 learned a mapping
+ assert not p2.mapping # p2 is independent (per-run isolation)
+
+
+def test_default_config_is_all_on():
+ cfg = RedactionConfig()
+ assert cfg.redact_internal_ips
+ assert cfg.redact_emails
+ assert cfg.redact_paths
+ assert cfg.redact_secrets
+ assert cfg.redact_internal_hostnames
+ assert cfg.redact_usernames