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(api): Phase 1.6 KMS envelope encryption for the credential vault (#422)

Beenu Arora5d4de485360d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aef465cd7..c8e1ec79b 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.6 — platform/vault hardening (KMS envelope encryption).** New `services/api/app/security/envelope_cipher.py`: optional envelope encryption for the credential vault. Each secret is encrypted with a fresh per-secret data key (DEK); the DEK is wrapped by a key-encryption key (KEK) that never leaves KMS/HSM (`vault:v2:<kek_id>:<wrapped_dek>:<ciphertext>`), so a DB dump or a leaked env var yields only wrapped DEKs. Pluggable `KeyManager` protocol with `LocalKeyManager` (default, backward-compatible), `AwsKmsKeyManager` (boto3; GCP KMS / Vault Transit implement the same protocol), and an in-memory `FakeKmsKeyManager` for tests. Key rotation is a cheap **re-wrap** (`EnvelopeCipher.rewrap`) that never re-encrypts the secret body. Gated by `services/api/tests/test_envelope_cipher.py` (round-trip, rotation + re-wrap, plaintext-never-in-token, fail-closed on tamper/wrong-KEK). Added `docs/security/platform-threat-model.md` (STRIDE, vault as top asset) and `docs/security/connector-least-privilege.md`. Completes Phase 1.
+
- **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.
diff --git a/ROADMAP.md b/ROADMAP.md
index 2c639f0f8..de0883f45 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -23,7 +23,7 @@ This document captures the planned direction for AiSOC across major versions. Al
A proof-first, security-first program to make every README claim gate-backed, close four existential agent-security holes, and build the ingest-time-graph + multi-model-router moat. Executed one phase per PR with a mandatory CI gate each. Committed status is the checklist below (per-session working detail is tracked locally in `docs/audit/PROGRESS.md`, which is gitignored per repo convention). Baseline audit: [`docs/audit/REALITY_REPORT.md`](docs/audit/REALITY_REPORT.md) and [`docs/audit/CLAIM_TO_GATE_MATRIX.md`](docs/audit/CLAIM_TO_GATE_MATRIX.md).
- [x] Phase 0 — Reality audit (claim-to-gate matrix, ranked overclaims/untested-paths/circular-gates)
-- [ ] Phase 1 — Four existential holes (prompt injection, memory poisoning, cross-store tenant isolation, data-exfiltration/redaction, cost DoS, vault)
+- [x] Phase 1 — Four existential holes (prompt injection, memory poisoning, cross-store tenant isolation, data-exfiltration/redaction, cost DoS, vault)
- [ ] Phase 2 — Supply chain + truth (SAST/deps/containers/secrets/IaC gates, signed attested releases, hard-fail insecure prod defaults, README honesty)
- [ ] Phase 3 — Integration / E2E / chaos / DR (real-container spine test, backup-restore, chaos, upgrade)
- [ ] Phase 4 — Real evals + detection content truth table (third-party-labeled corpus, hallucination/calibration/abstention, model matrix)
diff --git a/SECURITY.md b/SECURITY.md
index 653b2b76b..8429eedc7 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -5,7 +5,8 @@ AiSOC is security software, so we take vulnerabilities in our own stack seriousl
## Threat models
- Agent + tool surface (prompt injection, tool abuse): [`docs/security/agent-threat-model.md`](docs/security/agent-threat-model.md).
-- Platform + credential vault: [`docs/security/platform-threat-model.md`](docs/security/platform-threat-model.md) (Phase 1.6).
+- Platform + credential vault (KMS envelope encryption, key rotation): [`docs/security/platform-threat-model.md`](docs/security/platform-threat-model.md).
+- Connector least-privilege scopes: [`docs/security/connector-least-privilege.md`](docs/security/connector-least-privilege.md).
## Supported versions
diff --git a/docs/security/connector-least-privilege.md b/docs/security/connector-least-privilege.md
new file mode 100644
index 000000000..575367ebb
--- /dev/null
+++ b/docs/security/connector-least-privilege.md
@@ -0,0 +1,41 @@
+# Connector Least-Privilege Scopes
+
+Phase 1.6 of the world-class program. Because a vault compromise pivots into every connected system, each connector credential must be granted the **minimum** scope it needs — read/telemetry for detection, plus only the specific write scopes for any SOAR action the operator enables.
+
+Principle: grant read/audit scopes by default; add a containment scope only when the matching autonomous action is enabled for that connector, and prefer resource-scoped policies over account-wide ones.
+
+This is the living reference; a representative set of the highest-impact connectors is documented below. Contributions adding a connector must include its minimum-scope row (enforced narratively in review; a scope-audit gate is tracked for Phase 10's conformance suite).
+
+## AWS (CloudTrail / GuardDuty / Security Hub)
+
+- Read/detect: `cloudtrail:LookupEvents`, `guardduty:GetFindings`, `guardduty:ListFindings`, `securityhub:GetFindings`.
+- Contain (only if enabled): `ec2:AuthorizeSecurityGroupIngress`/`RevokeSecurityGroupIngress` scoped to a quarantine SG; `iam:UpdateAccessKey` scoped to the target user path.
+- Do NOT grant: `*:*`, `iam:CreateUser`, org-wide admin.
+
+## Okta
+
+- Read/detect: `okta.logs.read`, `okta.users.read`, `okta.sessions.read`.
+- Contain (only if enabled): `okta.users.manage` limited to session-revocation / suspend; scope to a non-admin group where possible.
+- Do NOT grant: super-admin API token.
+
+## CrowdStrike Falcon
+
+- Read/detect: Detections `READ`, Hosts `READ`, Event streams `READ`.
+- Contain (only if enabled): Host containment `WRITE` (network-contain), Real Time Response only if host-isolation playbooks are enabled.
+- Do NOT grant: Falcon administrator, API client management.
+
+## GitHub
+
+- Read/detect: `read:audit_log` (org), `repo:read` metadata, `read:org`.
+- Contain (only if enabled): `admin:org` is over-scoped — prefer fine-grained tokens limited to the specific repos/actions (e.g. revoke a compromised deploy key).
+- Do NOT grant: classic PAT with full `repo` + `admin:org` unless a specific action requires it.
+
+## Splunk / Elastic (SIEM)
+
+- Read/detect: search/query role on the relevant indexes only.
+- Contain: SIEM connectors are read-oriented; no write scope unless a notable-update action is enabled.
+- Do NOT grant: admin/`sc_admin`.
+
+## Audit
+
+Until the Phase 10 conformance gate lands, review every connector PR against this principle and record the connector's minimum scope in its docs page under `apps/docs/docs/connectors/<id>.md`. The vault threat model that motivates this is in [`platform-threat-model.md`](platform-threat-model.md).
diff --git a/docs/security/platform-threat-model.md b/docs/security/platform-threat-model.md
new file mode 100644
index 000000000..b96c850f6
--- /dev/null
+++ b/docs/security/platform-threat-model.md
@@ -0,0 +1,70 @@
+# Platform Threat Model (STRIDE)
+
+Scope: the AiSOC platform as a whole, with the **credential vault as the top asset**. AiSOC's `CredentialVault` holds live credentials to CrowdStrike, AWS, Okta, Splunk, and GitHub. Compromising AiSOC compromises everything it connects to, so the platform's own security is a P0 product feature.
+
+This document is Phase 1.6 of the world-class program. It is referenced from [`SECURITY.md`](../../SECURITY.md). The agent/tool surface has its own model in [`agent-threat-model.md`](agent-threat-model.md).
+
+## Assets (ranked)
+
+1. **Connector credentials** in the vault (`services/api/app/security/credential_vault.py`) — the crown jewels.
+2. The KEK / `AISOC_CREDENTIAL_KEY` and any KMS key material.
+3. Tenant data at rest (Postgres, ClickHouse, Neo4j, Qdrant, Redis, Kafka).
+4. The audit log / Investigation Ledger (must be tamper-evident).
+5. Platform admin + SSO/JWT signing secrets.
+
+## Trust boundaries
+
+```mermaid
+flowchart LR
+ Operator["Operator / SSO"] --> API["Core API"]
+ Tenant["Tenant users"] --> API
+ API --> Vault["CredentialVault"]
+ Vault --> KMS["KEK in KMS/HSM"]
+ Vault --> DB[("Postgres (wrapped DEK + ciphertext)")]
+ API --> Connectors["Connectors"]
+ Connectors -->|"least-privilege creds"| Vendors["CrowdStrike / AWS / Okta / Splunk / GitHub"]
+```
+
+## STRIDE
+
+### Spoofing
+- Threats: forged JWT/SSO to assume an operator/tenant; a connector impersonating another tenant.
+- Controls: OIDC/SAML token issuance fails closed on placeholder secrets (`services/api/app/auth/`); per-request tenant binding (`app.current_tenant_id`) + query-layer `tenant_id` filters; API keys are vault-encrypted.
+
+### Tampering
+- Threats: editing ciphertext in the DB; altering the audit trail.
+- Controls: authenticated encryption (Fernet HMAC / envelope DEK) makes tampered ciphertext fail closed; audit hash chain (`services/api/app/services/audit_hash.py`) makes ledger edits detectable; audit rows reject UPDATE/DELETE by the app role (Phase 3.1 gate).
+
+### Repudiation
+- Threats: an operator denies a credential change or an autonomous action.
+- Controls: append-only audit log with actor + hash chain; ledger records the deciding model/tier.
+
+### Information disclosure (top risk for this asset)
+- Threats: a DB dump or leaked `AISOC_CREDENTIAL_KEY` exposes every connector credential; plaintext secrets in logs.
+- Controls:
+ - **Envelope encryption** (`services/api/app/security/envelope_cipher.py`, Phase 1.6): each secret is encrypted with a per-secret DEK; the DEK is wrapped by a KEK that never leaves KMS/HSM (`AwsKmsKeyManager`; GCP KMS / Vault Transit implement the same `KeyManager` protocol). A DB dump yields only wrapped DEKs + ciphertext — useless without KMS `decrypt` permission. `LocalKeyManager` remains the default for hobby deploys.
+ - Per-secret DEKs mean a single compromised DEK exposes one secret, not the whole vault.
+ - Leaf-level encryption keeps structural fields queryable while every secret value is ciphertext.
+ - The vault refuses to boot without a key outside development; plaintext keys never log.
+
+### Denial of service
+- Threats: flooding investigations to exhaust budget/compute (see agent model, Phase 1.5); KMS throttling.
+- Controls: per-tenant cost governor (Phase 1.5); KMS calls are per-secret-write/rotation, not per-request, so KMS rate is bounded.
+
+### Elevation of privilege
+- Threats: an over-scoped connector credential lets a vault compromise pivot into full cloud admin.
+- Controls: **least-privilege connector scopes** ([`connector-least-privilege.md`](connector-least-privilege.md)) — document and audit the minimum IAM/API scope each connector needs; break-glass + rollback for autonomous actions (Phase 9).
+
+## Key rotation (tested)
+
+Rotation is a **re-wrap**, not a re-encrypt of every secret body:
+
+1. Provision a new KEK in KMS (or add a new `LocalKeyManager` primary, keeping the old as historical).
+2. Run `EnvelopeCipher.rewrap(token)` over every stored token: the DEK is unwrapped with its original KEK and re-wrapped with the current one. The ciphertext body is untouched and the plaintext never leaves KMS's reach.
+3. Retire the old KEK once no token references it.
+
+Gated by `services/api/tests/test_envelope_cipher.py` (round-trip, rotation + re-wrap, plaintext-never-in-token, fail-closed on tamper/wrong-KEK).
+
+## Residual risk
+
+A live KMS `decrypt` permission on the running API host is still a compromise path (the app must be able to decrypt to use credentials). Mitigations: scope the KMS key policy to the API role only, enable KMS CloudTrail on `decrypt`, and alert on anomalous decrypt volume. HSM-backed KEKs raise the bar further.
diff --git a/services/api/app/security/envelope_cipher.py b/services/api/app/security/envelope_cipher.py
new file mode 100644
index 000000000..679e7cd6b
--- /dev/null
+++ b/services/api/app/security/envelope_cipher.py
@@ -0,0 +1,230 @@
+"""KMS/HSM envelope encryption for the credential vault (Phase 1.6).
+
+The `CredentialVault` (`credential_vault.py`) protects connector secrets with a
+single Fernet key mounted from an env var. That is adequate for a hobby deploy
+but not for what this vault actually holds: live credentials to CrowdStrike,
+AWS, Okta, Splunk, and GitHub. Compromising the env key compromises everything.
+
+This module adds an optional **envelope-encryption** layer:
+
+- A fresh random **data encryption key (DEK)** is generated per secret and used
+ to encrypt the plaintext (Fernet / AES-128-CBC + HMAC).
+- The DEK is then **wrapped (encrypted) by a key encryption key (KEK)** that
+ never leaves the KMS/HSM. Only the wrapped DEK + ciphertext are stored.
+- Token format: ``vault:v2:<kek_id>:<b64 wrapped_dek>:<b64 ciphertext>``.
+
+Because the KEK stays in KMS, a database dump or a leaked env var does not
+reveal the DEKs, and **key rotation is re-wrapping the DEKs** (cheap, no
+plaintext ever touches the process beyond the DEK) rather than re-encrypting
+every secret body.
+
+The `KeyManager` protocol keeps the KMS backend pluggable:
+
+- `LocalKeyManager` — KEK is a Fernet key from the environment (default; matches
+ today's trust model but with per-secret DEKs).
+- `AwsKmsKeyManager` — wraps DEKs via AWS KMS ``encrypt``/``decrypt`` (boto3,
+ lazy-imported). GCP KMS / HashiCorp Vault Transit implement the same protocol.
+- `FakeKmsKeyManager` — in-memory, rotatable; lets the envelope round-trip and
+ the rotation/re-wrap flow be unit-tested offline with no cloud credentials.
+
+This module is pure (no DB, no `settings` import) so it is trivially testable.
+"""
+
+from __future__ import annotations
+
+import base64
+from typing import Protocol, runtime_checkable
+
+from cryptography.fernet import Fernet, InvalidToken
+
+_ENVELOPE_PREFIX = "vault:v2:"
+
+
+class EnvelopeError(RuntimeError):
+ """Raised when envelope encryption/decryption cannot proceed safely."""
+
+
+@runtime_checkable
+class KeyManager(Protocol):
+ """Wraps/unwraps data-encryption keys with a KEK held in a KMS/HSM."""
+
+ @property
+ def key_id(self) -> str:
+ """Identifier of the current (primary) KEK, embedded in the token."""
+ ...
+
+ def wrap(self, dek: bytes) -> bytes:
+ """Encrypt a DEK under the current KEK."""
+ ...
+
+ def unwrap(self, wrapped: bytes, key_id: str) -> bytes:
+ """Decrypt a DEK that was wrapped under the KEK named ``key_id``."""
+ ...
+
+
+class LocalKeyManager:
+ """KEK is a local Fernet key (env-mounted). Default backend.
+
+ Supports rotation: pass historical KEKs so DEKs wrapped under an old KEK
+ still unwrap until they have been re-wrapped.
+ """
+
+ def __init__(self, primary_key: bytes, *, key_id: str = "local-1", historical: dict[str, bytes] | None = None) -> None:
+ self._key_id = key_id
+ try:
+ self._primary = Fernet(primary_key)
+ except (TypeError, ValueError) as exc:
+ raise EnvelopeError(f"invalid local KEK: {exc}") from exc
+ self._ring: dict[str, Fernet] = {key_id: self._primary}
+ for kid, key in (historical or {}).items():
+ try:
+ self._ring[kid] = Fernet(key)
+ except (TypeError, ValueError):
+ continue
+
+ @property
+ def key_id(self) -> str:
+ return self._key_id
+
+ def wrap(self, dek: bytes) -> bytes:
+ return self._primary.encrypt(dek)
+
+ def unwrap(self, wrapped: bytes, key_id: str) -> bytes:
+ fernet = self._ring.get(key_id)
+ if fernet is None:
+ raise EnvelopeError(f"no KEK available for key_id {key_id!r}")
+ try:
+ return fernet.decrypt(wrapped)
+ except InvalidToken as exc:
+ raise EnvelopeError("wrapped DEK failed integrity check") from exc
+
+
+class AwsKmsKeyManager:
+ """Wraps DEKs via AWS KMS. Requires boto3 + AWS credentials at runtime.
+
+ The KEK never leaves KMS; we call ``encrypt``/``decrypt`` on the DEK bytes.
+ ``key_id`` is the KMS key ARN/alias, and KMS resolves the correct key
+ material for ``decrypt`` from the ciphertext blob, so rotation is handled by
+ KMS-managed key versions transparently.
+ """
+
+ def __init__(self, kms_key_id: str, *, client: object | None = None) -> None:
+ self._key_id = kms_key_id
+ if client is not None:
+ self._client = client
+ else: # pragma: no cover - requires AWS creds
+ import boto3 # type: ignore[import]
+
+ self._client = boto3.client("kms")
+
+ @property
+ def key_id(self) -> str:
+ return self._key_id
+
+ def wrap(self, dek: bytes) -> bytes: # pragma: no cover - requires AWS/mocked client
+ resp = self._client.encrypt(KeyId=self._key_id, Plaintext=dek) # type: ignore[attr-defined]
+ return resp["CiphertextBlob"]
+
+ def unwrap(self, wrapped: bytes, key_id: str) -> bytes: # pragma: no cover - requires AWS/mocked client
+ resp = self._client.decrypt(CiphertextBlob=wrapped, KeyId=self._key_id) # type: ignore[attr-defined]
+ return resp["Plaintext"]
+
+
+class FakeKmsKeyManager:
+ """In-memory KMS stand-in for tests. Rotatable.
+
+ Wrapping XORs the DEK with a per-KEK keystream (deterministic, reversible) —
+ good enough to prove the envelope + rotation flow without a crypto backend.
+ """
+
+ def __init__(self) -> None:
+ self._keys: dict[str, bytes] = {}
+ self._current: str = ""
+ self.rotate("kek-1")
+
+ def rotate(self, key_id: str) -> None:
+ import os
+
+ self._keys[key_id] = os.urandom(32)
+ self._current = key_id
+
+ @property
+ def key_id(self) -> str:
+ return self._current
+
+ def _xor(self, data: bytes, key: bytes) -> bytes:
+ return bytes(b ^ key[i % len(key)] for i, b in enumerate(data))
+
+ def wrap(self, dek: bytes) -> bytes:
+ return self._xor(dek, self._keys[self._current])
+
+ def unwrap(self, wrapped: bytes, key_id: str) -> bytes:
+ key = self._keys.get(key_id)
+ if key is None:
+ raise EnvelopeError(f"no KEK for {key_id!r}")
+ return self._xor(wrapped, key)
+
+
+class EnvelopeCipher:
+ """Per-secret envelope encryption over a pluggable :class:`KeyManager`."""
+
+ def __init__(self, key_manager: KeyManager) -> None:
+ self._km = key_manager
+
+ def encrypt(self, plaintext: str) -> str:
+ if not isinstance(plaintext, str):
+ raise EnvelopeError(f"encrypt expects str, got {type(plaintext).__name__}")
+ if plaintext.startswith(_ENVELOPE_PREFIX):
+ return plaintext
+ dek = Fernet.generate_key()
+ ciphertext = Fernet(dek).encrypt(plaintext.encode("utf-8"))
+ wrapped = self._km.wrap(dek)
+ return (
+ f"{_ENVELOPE_PREFIX}{self._km.key_id}:"
+ f"{base64.urlsafe_b64encode(wrapped).decode('ascii')}:"
+ f"{base64.urlsafe_b64encode(ciphertext).decode('ascii')}"
+ )
+
+ def _parse(self, token: str) -> tuple[str, bytes, bytes]:
+ if not token.startswith(_ENVELOPE_PREFIX):
+ raise EnvelopeError("not a vault:v2 envelope token")
+ body = token[len(_ENVELOPE_PREFIX) :]
+ try:
+ key_id, wrapped_b64, ct_b64 = body.split(":", 2)
+ # binascii.Error (raised by b64decode) is a ValueError subclass.
+ wrapped = base64.urlsafe_b64decode(wrapped_b64)
+ ciphertext = base64.urlsafe_b64decode(ct_b64)
+ except ValueError as exc:
+ raise EnvelopeError(f"malformed envelope token: {exc}") from exc
+ return key_id, wrapped, ciphertext
+
+ def decrypt(self, token: str) -> str:
+ if not isinstance(token, str):
+ raise EnvelopeError(f"decrypt expects str, got {type(token).__name__}")
+ if not token.startswith(_ENVELOPE_PREFIX):
+ return token # plaintext / v1 pass-through
+ key_id, wrapped, ciphertext = self._parse(token)
+ dek = self._km.unwrap(wrapped, key_id)
+ try:
+ return Fernet(dek).decrypt(ciphertext).decode("utf-8")
+ except (InvalidToken, ValueError) as exc:
+ # ValueError covers a corrupt/wrong DEK (e.g. unwrapped under the
+ # wrong KEK) producing invalid Fernet key material. Fail closed.
+ raise EnvelopeError("ciphertext failed integrity check") from exc
+
+ def rewrap(self, token: str) -> str:
+ """Re-wrap the DEK under the current KEK without touching plaintext.
+
+ This is the rotation primitive: after rotating the KEK, run this over
+ every stored token. The DEK is unwrapped with its original KEK and
+ re-wrapped with the current one; the secret body is never re-encrypted
+ and the plaintext never leaves KMS's reach.
+ """
+ key_id, wrapped, ciphertext = self._parse(token)
+ dek = self._km.unwrap(wrapped, key_id)
+ rewrapped = self._km.wrap(dek)
+ return (
+ f"{_ENVELOPE_PREFIX}{self._km.key_id}:"
+ f"{base64.urlsafe_b64encode(rewrapped).decode('ascii')}:"
+ f"{base64.urlsafe_b64encode(ciphertext).decode('ascii')}"
+ )
diff --git a/services/api/tests/test_envelope_cipher.py b/services/api/tests/test_envelope_cipher.py
new file mode 100644
index 000000000..1c5e328f2
--- /dev/null
+++ b/services/api/tests/test_envelope_cipher.py
@@ -0,0 +1,109 @@
+"""Tests for KMS envelope encryption + rotation (Phase 1.6).
+
+Offline via FakeKmsKeyManager. The core guarantees:
+- round-trip correctness,
+- plaintext never appears in the stored token (what lands in a DB row),
+- KEK rotation is a re-wrap that never re-encrypts the secret body,
+- tampering fails closed.
+"""
+
+from __future__ import annotations
+
+import pytest
+from app.security.envelope_cipher import (
+ EnvelopeCipher,
+ EnvelopeError,
+ FakeKmsKeyManager,
+ LocalKeyManager,
+)
+from cryptography.fernet import Fernet
+
+SECRET = "crowdstrike-api-token-SUPERSECRET-9f3a"
+
+
+def test_round_trip_fake_kms():
+ cipher = EnvelopeCipher(FakeKmsKeyManager())
+ token = cipher.encrypt(SECRET)
+ assert token.startswith("vault:v2:")
+ assert cipher.decrypt(token) == SECRET
+
+
+def test_plaintext_never_appears_in_token():
+ cipher = EnvelopeCipher(FakeKmsKeyManager())
+ token = cipher.encrypt(SECRET)
+ # The token is exactly what gets written to the DB row / could hit a log.
+ assert SECRET not in token
+ for frag in ("SUPERSECRET", "crowdstrike-api-token"):
+ assert frag not in token
+
+
+def test_each_encrypt_uses_a_fresh_dek():
+ cipher = EnvelopeCipher(FakeKmsKeyManager())
+ t1 = cipher.encrypt(SECRET)
+ t2 = cipher.encrypt(SECRET)
+ assert t1 != t2 # fresh DEK per secret -> different ciphertext + wrapped dek
+ assert cipher.decrypt(t1) == cipher.decrypt(t2) == SECRET
+
+
+def test_kek_rotation_then_rewrap():
+ km = FakeKmsKeyManager() # starts at kek-1
+ cipher = EnvelopeCipher(km)
+ token_v1 = cipher.encrypt(SECRET)
+ assert ":kek-1:" in token_v1
+
+ # Rotate the KEK. The old token still decrypts because the old KEK is
+ # retained for unwrap.
+ km.rotate("kek-2")
+ assert cipher.decrypt(token_v1) == SECRET
+
+ # Re-wrap: DEK is unwrapped with kek-1 and re-wrapped with kek-2. The
+ # ciphertext body is unchanged; only the wrapped-DEK segment rotates.
+ token_v2 = cipher.rewrap(token_v1)
+ assert ":kek-2:" in token_v2
+ assert token_v1.rsplit(":", 1)[-1] == token_v2.rsplit(":", 1)[-1] # same ciphertext body
+ assert cipher.decrypt(token_v2) == SECRET
+
+
+def test_local_key_manager_round_trip_and_rotation():
+ kek1 = Fernet.generate_key()
+ kek2 = Fernet.generate_key()
+ cipher1 = EnvelopeCipher(LocalKeyManager(kek1, key_id="local-1"))
+ token = cipher1.encrypt(SECRET)
+ assert ":local-1:" in token
+
+ # New primary KEK, old kept for unwrap.
+ cipher2 = EnvelopeCipher(LocalKeyManager(kek2, key_id="local-2", historical={"local-1": kek1}))
+ assert cipher2.decrypt(token) == SECRET
+ rewrapped = cipher2.rewrap(token)
+ assert ":local-2:" in rewrapped
+ assert cipher2.decrypt(rewrapped) == SECRET
+
+
+def test_tampered_ciphertext_fails_closed():
+ cipher = EnvelopeCipher(FakeKmsKeyManager())
+ token = cipher.encrypt(SECRET)
+ tampered = token[:-4] + ("AAAA" if not token.endswith("AAAA") else "BBBB")
+ with pytest.raises(EnvelopeError):
+ cipher.decrypt(tampered)
+
+
+def test_plaintext_passthrough_and_idempotent_encrypt():
+ cipher = EnvelopeCipher(FakeKmsKeyManager())
+ assert cipher.decrypt("plain-legacy-value") == "plain-legacy-value"
+ token = cipher.encrypt(SECRET)
+ assert cipher.encrypt(token) == token # already enveloped -> unchanged
+
+
+def test_malformed_token_raises():
+ cipher = EnvelopeCipher(FakeKmsKeyManager())
+ with pytest.raises(EnvelopeError):
+ cipher._parse("vault:v2:onlyonesegment")
+
+
+def test_unwrap_with_unknown_kek_fails():
+ km = FakeKmsKeyManager()
+ cipher = EnvelopeCipher(km)
+ token = cipher.encrypt(SECRET)
+ fresh = EnvelopeCipher(FakeKmsKeyManager()) # different in-memory KEKs
+ with pytest.raises(EnvelopeError):
+ fresh.decrypt(token)