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.

fix(audit): close three audit-log trust-boundary gaps (H-4 + M-12) (#122)

Beenu Aroraeb6059bc90f2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 80e4eed61..099c5d90c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Security — audit log integrity (H-4 + M-12)
+
+Hardens the immutable audit log against three distinct trust-boundary
+failures discovered during the bugfix sweep:
+
+- **Spoofable `actor_ip`.** Previous releases lifted `actor_ip` from
+ `X-Forwarded-For` unconditionally. Any client able to reach the API
+ without a stripping ingress could attach their own header and write an
+ arbitrary source IP into compliance-grade audit rows. The new
+ `services/api/app/core/trusted_proxy.py` resolves IPs through an
+ explicit operator-configured allow-list (`AISOC_TRUSTED_PROXIES`,
+ empty by default). When the env var is empty the header is ignored and
+ the direct TCP peer is recorded; when set, only requests whose
+ immediate peer falls inside the configured CIDR list consult the
+ header, and the chain is walked right-to-left to return the closest
+ untrusted hop. Both the `emit_audit()` helper
+ (`services/api/app/services/audit.py`) and the auto-audit middleware
+ (`services/api/app/middleware/audit_middleware.py`) route through this
+ resolver.
+- **Secrets leaking into `changes`.** The `changes` payload is now
+ passed through `redact_changes()`
+ (`services/api/app/services/audit_redaction.py`) before persistence.
+ Keys matching case-insensitive sensitive patterns (`password`,
+ `secret`, `token`, `api_key`, `private_key`, `*credential*`,
+ `authorization`, `bearer`, `cookie`, `session`, `client_secret`, `*_seed`,
+ …) are replaced with `***REDACTED***` recursively across dicts, lists
+ and tuples. Serialized payloads larger than
+ `AISOC_AUDIT_MAX_CHANGES_BYTES` (default 65,536) are substituted with a
+ `{ "_truncated": true, "_size": <bytes> }` marker so a single bad
+ caller can't balloon the table. Recursion depth and node count are
+ capped to prevent DOS via pathological input.
+- **Trigger-bypass tampering.** The append-only trigger on `audit_log`
+ doesn't defend against SQL-level access (disabling triggers,
+ `TRUNCATE`, credential theft). Migration
+ `043_audit_log_hash_chain.sql` adds `prev_hash` / `entry_hash` columns
+ (per-tenant SHA-256 chain), and
+ `services/api/app/services/audit_hash.py` provides a pure
+ `compute_entry_hash()` + `verify_chain()` pair. Both `emit_audit()`
+ and the middleware now stamp every new row with the hash of the
+ previous tenant row, so any deletion, reorder, or rewrite is
+ detectable at audit time. The verifier accepts plain row dicts (e.g.
+ from a CSV export) so internal or external auditors can replay the
+ chain without DB access. Legacy unchained rows are tolerated at the
+ head of a tenant's history; gaps after the chain has started are
+ treated as forgery signals.
+
+New env vars (see `apps/docs/docs/deployment/env-vars.md`):
+
+- `AISOC_TRUSTED_PROXIES` — comma-separated CIDR list. Empty by default.
+- `AISOC_AUDIT_MAX_CHANGES_BYTES` — `65536` by default.
+
+80 new unit tests cover the resolver, redactor, and hash chain
+(`test_trusted_proxy.py`, `test_audit_redaction.py`, `test_audit_hash.py`),
+including tamper-detection scenarios (rewritten row, deleted row,
+reordered rows, `prev_hash` / `entry_hash` tampering) and robustness
+under malformed input. No regressions across the existing 1,283-test
+suite.
+
### Security — bounded eval / playbook timeouts (H-7, batch 10)
- **`POST /detection-proposals/run-eval`** — tightened Pydantic bounds on
diff --git a/apps/docs/docs/deployment/env-vars.md b/apps/docs/docs/deployment/env-vars.md
index 21d2a08b7..91e5c6cb4 100644
--- a/apps/docs/docs/deployment/env-vars.md
+++ b/apps/docs/docs/deployment/env-vars.md
@@ -36,6 +36,15 @@ The API uses bare environment variable names (no prefix). Booleans accept `true`
| `REFRESH_TOKEN_EXPIRE_DAYS` | `7` | Lifetime of a refresh token |
| `ALGORITHM` | `HS256` | JWT signing algorithm |
+### Audit log
+
+Source: [`services/api/app/services/audit.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/audit.py), [`services/api/app/core/trusted_proxy.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/core/trusted_proxy.py), [`services/api/app/services/audit_redaction.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/audit_redaction.py). Background: [Security operations → Audit logging](../operations/security#audit-logging).
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `AISOC_TRUSTED_PROXIES` | _empty_ | Comma-separated list of CIDRs (e.g. `10.0.0.0/8,192.168.0.0/16`) for trusted ingress / load balancer hops. When empty, `X-Forwarded-For` is **ignored** and `actor_ip` is the direct TCP peer — set this in production so the audit log records the real client IP without being spoofable from the public side. |
+| `AISOC_AUDIT_MAX_CHANGES_BYTES` | `65536` | Hard cap on the serialized `changes` payload stored per audit row. Over-sized values are replaced with a `{ "_truncated": true, "_size": <bytes> }` marker. Set higher only if you genuinely need richer diffs and have provisioned the storage. |
+
### Passkeys (WebAuthn)
| Variable | Default | Description |
diff --git a/apps/docs/docs/operations/security.md b/apps/docs/docs/operations/security.md
index 115faf4f3..6fb62d3b7 100644
--- a/apps/docs/docs/operations/security.md
+++ b/apps/docs/docs/operations/security.md
@@ -116,7 +116,7 @@ The `users` table is excluded from RLS deliberately — it would create a chicke
## Audit logging
-Every state-changing API action is appended to an immutable audit log. The schema lives in [`004_audit_log.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/004_audit_log.sql), the model in `services/api/app/models/audit.py`, and the helper that emits events in [`services/api/app/services/audit.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/audit.py).
+Every state-changing API action is appended to an immutable audit log. The schema lives in [`004_audit_log.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/004_audit_log.sql) (chain columns added in [`043_audit_log_hash_chain.sql`](https://github.com/beenuar/AiSOC/blob/main/services/api/migrations/043_audit_log_hash_chain.sql)), the model in `services/api/app/models/audit.py`, and the helper that emits events in [`services/api/app/services/audit.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/audit.py).
Each event captures:
@@ -124,14 +124,50 @@ Each event captures:
|---|---|
| `tenant_id` | Resolved from the actor's session |
| `actor_id`, `actor_email` | Authenticated user (or API-key owner) |
-| `actor_ip` | `X-Forwarded-For` (first hop) or `request.client.host` |
+| `actor_ip` | Resolved by `resolve_client_ip()` — direct TCP peer by default; `X-Forwarded-For` is consulted **only** if the peer is in `AISOC_TRUSTED_PROXIES` |
| `action` | Dot/colon string — e.g. `cases:create`, `connectors:delete`, `playbooks:execute` |
| `resource`, `resource_id` | What was touched |
-| `changes` | Before/after delta JSON |
-| `metadata_` | `user_agent`, `request_id`, and any caller-supplied context |
-| `created_at` | UTC timestamp, set by Postgres |
+| `changes` | Before/after delta JSON, **redacted** by `redact_changes()` before persistence (secrets, tokens, passwords masked; capped at `AISOC_AUDIT_MAX_CHANGES_BYTES`) |
+| `metadata_` | `user_agent`, `request_id`, and any caller-supplied context (header values truncated to bounded length) |
+| `prev_hash`, `entry_hash` | SHA-256 chain link — see "Tamper-evident hash chain" below |
+| `created_at` | UTC timestamp set deterministically by the application (folded into `entry_hash`) |
-The log is **append-only**: there is no `UPDATE` or `DELETE` endpoint, and the table has RLS enabled so a tenant can only read their own events. The middleware that auto-populates audit on common write paths is `services/api/app/middleware/audit_middleware.py`; high-value actions (case state transitions, playbook executions, credential rotations) call `emit_audit(...)` explicitly so the `changes` payload is precise.
+### Trusted-proxy IP attribution
+
+Earlier releases lifted `actor_ip` from `X-Forwarded-For` unconditionally. Any client behind an unstripping edge could spoof their source IP into the audit trail by attaching their own header. The current implementation gates that on an explicit operator allow-list:
+
+* `AISOC_TRUSTED_PROXIES` is **empty by default** → `X-Forwarded-For` is ignored entirely and the direct TCP peer is recorded.
+* When set to a comma-separated list of CIDRs (e.g. `10.0.0.0/8,192.168.0.0/16`), the header is consulted **only** when the immediate TCP peer is itself inside the list. The chain is walked right-to-left and the closest untrusted hop wins — that's the real originating client.
+* Malformed CIDRs in the env are logged and dropped; malformed `X-Forwarded-For` headers degrade safely to the direct peer. Audit must never fail closed because someone typoed a header.
+
+Configure `AISOC_TRUSTED_PROXIES` to the CIDR(s) of your ingress / load balancer in production. The trusted-proxy resolver lives in [`services/api/app/core/trusted_proxy.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/core/trusted_proxy.py).
+
+### `changes` redaction and size cap
+
+The `changes` payload often holds before/after snapshots of user objects, settings, or credentials. We sanitize it on the write path in [`services/api/app/services/audit_redaction.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/audit_redaction.py):
+
+* Keys matching common sensitive patterns (case-insensitive: `password`, `secret`, `token`, `api_key`, `private_key`, `*credential*`, `authorization`, `bearer`, `cookie`, `session`, `*_seed`, `client_secret`, etc.) are replaced with `***REDACTED***` recursively. Nested dicts, lists, and tuples are walked.
+* The serialized JSON is capped at `AISOC_AUDIT_MAX_CHANGES_BYTES` (default 65,536). Over-sized payloads are replaced with a `{ "_truncated": true, "_size": <bytes> }` marker rather than persisted — this stops a single bad caller from ballooning the audit table.
+* Recursion is capped (`_MAX_DEPTH`) and total node count is capped (`_MAX_NODES`) so a hostile or buggy caller can't DOS the redactor with a cyclic / pathological structure.
+
+If you legitimately need to record a large diff, log a stable reference (e.g. a content hash, an object key, a git SHA) in `changes` and store the diff body in your evidence pipeline instead.
+
+### Tamper-evident hash chain
+
+The `audit_log` table already enforces append-only at the trigger level. What that does *not* defend against is a privileged operator with SQL access bypassing the trigger (`ALTER TABLE … DISABLE TRIGGER ALL`, `TRUNCATE`, or DB-level credential theft) and substituting a forged history.
+
+Migration `043_audit_log_hash_chain.sql` adds two columns to close that gap **without trusting Postgres**:
+
+* `prev_hash` — the `entry_hash` of the previous audit row for the same tenant (or `NULL` for the first row).
+* `entry_hash` — `sha256(prev_hash || domain_separator || canonical_json(row))`.
+
+The hashing algorithm lives in [`services/api/app/services/audit_hash.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/audit_hash.py) and is intentionally pure — `verify_chain()` accepts a plain list of row dicts (e.g. read from a CSV export) and replays the chain deterministically. Anyone — internal auditor, customer compliance team, external assessor — can prove that no row was deleted, reordered, or silently rewritten.
+
+The chain is **per-tenant** so tenant operations stay isolated. Legacy rows that pre-date the migration carry `entry_hash = NULL` and are tolerated at the head of a tenant's history; once a tenant has any chained row, every subsequent row must be chained, and a gap is treated as a forgery signal by `verify_chain()`.
+
+The set of hashed fields is deliberately conservative — `tenant_id`, `actor_id`, `actor_email`, `actor_ip`, `action`, `resource`, `resource_id`, the **redacted** `changes`, `metadata_`, `created_at`, and the row `id`. Adding a hashed field is a chain-breaking schema change.
+
+The log is **append-only**: there is no `UPDATE` or `DELETE` endpoint, and the table has RLS enabled so a tenant can only read their own events. The middleware that auto-populates audit on common write paths is [`services/api/app/middleware/audit_middleware.py`](https://github.com/beenuar/AiSOC/blob/main/services/api/app/middleware/audit_middleware.py); high-value actions (case state transitions, playbook executions, credential rotations) call `emit_audit(...)` explicitly so the `changes` payload is precise. Both paths participate in the hash chain.
For SOC 2 / ISO 27001 evidence collection, the [Compliance service](https://github.com/beenuar/AiSOC/blob/main/services/api/app/services/compliance.py) reads from this log directly — there is no separate compliance event store to keep in sync.
@@ -228,6 +264,8 @@ When you move from `pnpm aisoc:demo` to a production deployment, walk through th
- [ ] Require WebAuthn/passkeys for any role that triggers destructive playbook actions or credential changes.
- [ ] Confirm `FORCE ROW LEVEL SECURITY` is set on every tenant-partitioned table (verify with `\d+ <tablename>` in `psql`).
- [ ] Set up an external log sink for the audit log (Splunk, Elastic, Loki) — the in-DB log is the source of truth, but a copy in your SIEM is good practice.
+- [ ] Configure `AISOC_TRUSTED_PROXIES` to the CIDR(s) of your ingress / load balancer so `actor_ip` is sourced from `X-Forwarded-For` instead of the immediate TCP peer. Leave empty if the API is exposed directly to clients.
+- [ ] Schedule a periodic `verify_chain()` job against an offsite read replica or a CSV export of the `audit_log` table and alert on any verification failure.
- [ ] Confirm TLS is terminated at the ingress and that internal traffic is on a private network.
- [ ] Enable mTLS between services if you're running on Kubernetes with a mesh.
- [ ] Subscribe to the AiSOC GitHub Security Advisories for vulnerability notifications.
diff --git a/services/api/app/core/trusted_proxy.py b/services/api/app/core/trusted_proxy.py
new file mode 100644
index 000000000..072c4ac01
--- /dev/null
+++ b/services/api/app/core/trusted_proxy.py
@@ -0,0 +1,175 @@
+"""Trusted-proxy resolution for audit-log IP attribution.
+
+The audit subsystem records ``actor_ip`` for every mutating request.
+Historically that value was lifted directly from ``X-Forwarded-For`` whenever
+the header was present, which is unsafe behind any reverse proxy or load
+balancer that does not strip client-supplied forwarding headers: a hostile
+client could trivially spoof their source IP in the audit trail by attaching
+``X-Forwarded-For: 10.0.0.1``.
+
+This module gates the use of ``X-Forwarded-For`` on the presence of a
+configured allow-list of trusted proxy CIDRs. The rules are:
+
+* If ``AISOC_TRUSTED_PROXIES`` is empty (the default), ``X-Forwarded-For``
+ is ignored entirely — we fall back to the direct TCP peer
+ (``request.client.host``). This is the safe default: an untrusted edge
+ cannot forge audit IPs.
+* If it is set, the *immediate* peer (``request.client.host``) MUST itself
+ be inside one of the configured CIDRs before we will consult
+ ``X-Forwarded-For``. Otherwise the header is again ignored. This prevents
+ a hostile client that bypasses the proxy from spoofing the chain.
+* When we do consult the header we walk it right-to-left, skipping any
+ hop that is itself trusted, and pick the first untrusted address — the
+ closest the chain comes to the real originating client.
+
+The module exposes a small surface so the audit service, audit middleware,
+and any future code that needs source-IP attribution all converge on the
+same algorithm.
+"""
+
+from __future__ import annotations
+
+import ipaddress
+import logging
+import os
+from collections.abc import Iterable, Sequence
+
+from fastapi import Request
+
+logger = logging.getLogger("aisoc.audit.trusted_proxy")
+
+# Env var name. Read from os.environ at resolution time rather than pinning
+# at import so tests can monkeypatch without re-importing the module.
+TRUSTED_PROXIES_ENV = "AISOC_TRUSTED_PROXIES"
+
+
+def _parse_cidrs(raw: str | None) -> list[ipaddress._BaseNetwork]:
+ """Parse a comma-separated CIDR list into network objects.
+
+ Bare IP addresses are accepted and treated as ``/32`` (or ``/128``).
+ Invalid entries are dropped with a warning rather than raising — the
+ audit pipeline must keep working even if one operator typos the env
+ var. The empty string / unset case returns ``[]``.
+ """
+ if not raw:
+ return []
+ out: list[ipaddress._BaseNetwork] = []
+ for entry in raw.split(","):
+ token = entry.strip()
+ if not token:
+ continue
+ try:
+ out.append(ipaddress.ip_network(token, strict=False))
+ except ValueError as exc:
+ logger.warning("trusted_proxies: ignoring invalid CIDR %r: %s", token, exc)
+ return out
+
+
+def _load_trusted_networks() -> list[ipaddress._BaseNetwork]:
+ """Resolve the current allow-list from the environment.
+
+ Read lazily so tests can ``monkeypatch.setenv(...)`` between cases.
+ """
+ return _parse_cidrs(os.getenv(TRUSTED_PROXIES_ENV, ""))
+
+
+def _ip_in_networks(addr: str, networks: Sequence[ipaddress._BaseNetwork]) -> bool:
+ """Return ``True`` if ``addr`` parses as an IP inside any of ``networks``."""
+ try:
+ ip = ipaddress.ip_address(addr.strip())
+ except ValueError:
+ return False
+ return any(ip in net for net in networks)
+
+
+def _parse_forwarded_for(header: str | None) -> list[str]:
+ """Split a raw ``X-Forwarded-For`` header into individual hops.
+
+ Strips whitespace, drops empties, and tolerates the
+ ``[2001:db8::1]:8080`` IPv6 syntax some proxies emit by chopping the
+ bracketed host out before further parsing.
+ """
+ if not header:
+ return []
+ hops: list[str] = []
+ for raw in header.split(","):
+ token = raw.strip()
+ if not token:
+ continue
+ # ``[ipv6]:port`` or ``ipv4:port``: drop the optional :port suffix.
+ if token.startswith("[") and "]" in token:
+ token = token[1 : token.index("]")]
+ elif token.count(":") == 1 and "." in token:
+ # IPv4 with port — split on the single ':'.
+ token = token.split(":", 1)[0]
+ hops.append(token)
+ return hops
+
+
+def resolve_client_ip(
+ request: Request,
+ *,
+ trusted_networks: Iterable[ipaddress._BaseNetwork] | None = None,
+) -> str | None:
+ """Return the best-effort originating client IP for ``request``.
+
+ Algorithm:
+
+ 1. ``peer_ip`` = direct TCP peer (``request.client.host``). If absent,
+ we cannot attribute anything, return ``None``.
+ 2. If no trusted-proxy CIDRs are configured, return ``peer_ip``. This
+ is the audit-safe default and means ``X-Forwarded-For`` is
+ ignored even if present.
+ 3. If ``peer_ip`` itself is not in the allow-list, also return
+ ``peer_ip``. An untrusted edge cannot dictate what we log.
+ 4. Otherwise walk ``X-Forwarded-For`` from right (closest to us) to
+ left (closest to the originator), skipping any hop also in the
+ allow-list, and return the first untrusted hop encountered. If
+ every hop is trusted (unusual but well-formed for an all-internal
+ chain), return the leftmost hop. If the header is missing or
+ empty, return ``peer_ip``.
+
+ The function never raises — malformed headers degrade to the direct
+ peer.
+ """
+ client = request.client
+ peer_ip = client.host if client else None
+ if not peer_ip:
+ return None
+
+ nets = list(trusted_networks) if trusted_networks is not None else _load_trusted_networks()
+ if not nets:
+ # No trusted edge configured: X-Forwarded-For is untrusted noise.
+ return peer_ip
+
+ if not _ip_in_networks(peer_ip, nets):
+ # Direct peer is not a trusted proxy: ignore any forwarded chain.
+ return peer_ip
+
+ hops = _parse_forwarded_for(request.headers.get("x-forwarded-for"))
+ if not hops:
+ return peer_ip
+
+ for hop in reversed(hops):
+ if not _ip_in_networks(hop, nets):
+ # Sanity: must parse as an IP at all before we accept it.
+ try:
+ ipaddress.ip_address(hop)
+ except ValueError:
+ continue
+ return hop
+
+ # Whole chain is trusted — fall back to the outermost hop (the
+ # leftmost value), which by convention is the original client.
+ leftmost = hops[0]
+ try:
+ ipaddress.ip_address(leftmost)
+ except ValueError:
+ return peer_ip
+ return leftmost
+
+
+__all__ = [
+ "TRUSTED_PROXIES_ENV",
+ "resolve_client_ip",
+]
diff --git a/services/api/app/middleware/audit_middleware.py b/services/api/app/middleware/audit_middleware.py
index 0c5199611..d7f95b8d2 100644
--- a/services/api/app/middleware/audit_middleware.py
+++ b/services/api/app/middleware/audit_middleware.py
@@ -5,19 +5,39 @@ middleware appends an AuditLog row **after** the response has been produced so
it never blocks the hot path.
Non-authenticated requests and GET/HEAD/OPTIONS are silently skipped.
+
+Hardening (BATCH 7 — H-4 + M-12)
+--------------------------------
+
+* Uses :func:`app.core.trusted_proxy.resolve_client_ip` so
+ ``X-Forwarded-For`` is only honoured for trusted hops. The previous
+ implementation took the first XFF value unconditionally.
+* Caps user-agent / request-id header sizes before writing them to the
+ ``metadata`` JSONB column.
+* Writes ``prev_hash`` / ``entry_hash`` so middleware-emitted rows
+ participate in the same tamper-evident chain as :func:`emit_audit`.
"""
from __future__ import annotations
+import logging
import re
import uuid
+from datetime import UTC, datetime
+from app.core.trusted_proxy import resolve_client_ip
from app.db.database import AsyncSessionLocal
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
+logger = logging.getLogger("aisoc.audit.middleware")
+
_MUTATING = {"POST", "PUT", "PATCH", "DELETE"}
+# Header value caps — keep audit rows bounded even under malicious peers.
+_MAX_UA_LEN = 512
+_MAX_REQUEST_ID_LEN = 128
+
# Map URL patterns → (action, resource) label pairs for cleaner audit records.
_ROUTE_LABELS: list[tuple[re.Pattern[str], str, str]] = [
(re.compile(r"^/api/v1/cases/?(.*)"), "cases", "case"),
@@ -68,6 +88,12 @@ def _extract_jwt_claims(request: Request) -> tuple[uuid.UUID | None, uuid.UUID |
return None, None, None
+def _truncate(value: str | None, limit: int) -> str | None:
+ if value is None:
+ return None
+ return value if len(value) <= limit else value[:limit]
+
+
class AuditMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
response = await call_next(request)
@@ -98,21 +124,27 @@ class AuditMiddleware(BaseHTTPMiddleware):
async with AsyncSessionLocal() as db:
from app.models.audit import AuditLog # noqa: PLC0415
+ from app.services.audit import _resolve_prev_hash # noqa: PLC0415
+ from app.services.audit_hash import compute_entry_hash # noqa: PLC0415
+
+ try:
+ actor_ip = resolve_client_ip(request)
+ except Exception: # noqa: BLE001
+ logger.warning("audit-middleware: failed to resolve client IP", exc_info=True)
+ actor_ip = None
- forwarded = request.headers.get("x-forwarded-for")
- actor_ip = (forwarded.split(",")[0].strip() if forwarded else None) or (
- str(request.client.host) if request.client else None
- )
meta: dict = {}
- ua = request.headers.get("user-agent")
+ ua = _truncate(request.headers.get("user-agent"), _MAX_UA_LEN)
if ua:
meta["user_agent"] = ua
- rid = request.headers.get("x-request-id")
+ rid = _truncate(request.headers.get("x-request-id"), _MAX_REQUEST_ID_LEN)
if rid:
meta["request_id"] = rid
meta["status_code"] = response.status_code
+ created_at = datetime.now(UTC)
event = AuditLog(
+ id=uuid.uuid4(),
tenant_id=tenant_id,
actor_id=user_id,
actor_email=email,
@@ -121,7 +153,35 @@ class AuditMiddleware(BaseHTTPMiddleware):
resource=resource,
resource_id=resource_id,
metadata_=meta or None,
+ created_at=created_at,
)
+
+ # Chain-link the middleware event onto the tenant's history.
+ try:
+ prev = await _resolve_prev_hash(db, tenant_id)
+ event.prev_hash = prev
+ event.entry_hash = compute_entry_hash(
+ prev_hash=prev,
+ row_id=event.id,
+ tenant_id=event.tenant_id,
+ actor_id=event.actor_id,
+ actor_email=event.actor_email,
+ actor_ip=event.actor_ip,
+ action=event.action,
+ resource=event.resource,
+ resource_id=event.resource_id,
+ changes=event.changes,
+ metadata=event.metadata_,
+ created_at=event.created_at,
+ )
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "audit-middleware: failed to compute hash chain",
+ exc_info=True,
+ )
+ event.prev_hash = None
+ event.entry_hash = None
+
db.add(event)
await db.commit()
except Exception:
diff --git a/services/api/app/models/audit.py b/services/api/app/models/audit.py
index 3535c748c..1c6eb3b88 100644
--- a/services/api/app/models/audit.py
+++ b/services/api/app/models/audit.py
@@ -28,3 +28,10 @@ class AuditLog(Base):
changes: Mapped[dict | None] = mapped_column(JSONB, nullable=True)
metadata_: Mapped[dict | None] = mapped_column("metadata", JSONB, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC), nullable=False)
+ # Tamper-evident hash chain. ``prev_hash`` is the ``entry_hash`` of
+ # the previous audit row for the same tenant; ``entry_hash`` is a
+ # sha256 digest over the canonical serialization of this row mixed
+ # with ``prev_hash``. See migration 043_audit_log_hash_chain.sql
+ # and ``app.services.audit_hash`` for the canonical algorithm.
+ prev_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ entry_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
diff --git a/services/api/app/services/audit.py b/services/api/app/services/audit.py
index 5ce8aa3e9..134208b89 100644
--- a/services/api/app/services/audit.py
+++ b/services/api/app/services/audit.py
@@ -6,24 +6,97 @@ Usage::
await emit_audit(
db=db,
- user=current_user,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.id,
+ actor_email=current_user.email,
action="cases:create",
resource="case",
resource_id=str(case.id),
changes={"title": case.title},
request=request, # optional FastAPI Request for IP / user-agent
)
+
+Hardening (BATCH 7 — H-4 + M-12)
+--------------------------------
+
+* **Source-IP attribution.** ``actor_ip`` is resolved through
+ :func:`app.core.trusted_proxy.resolve_client_ip`, which only honours
+ ``X-Forwarded-For`` when the direct peer is on the configured
+ ``AISOC_TRUSTED_PROXIES`` allow-list. The previous version trusted
+ the header unconditionally, letting any client forge their audit IP.
+ It also had an operator-precedence bug
+ (``A or B if C else None``) that silently broke when ``request.client``
+ was ``None``.
+* **Changes redaction & size cap.** The ``changes`` payload is passed
+ through :func:`app.services.audit_redaction.redact_changes` so
+ password/token/secret keys are masked and oversized payloads are
+ reduced to a marker row. Without this we were one bad endpoint away
+ from persisting raw secrets into an immutable, RLS-scoped table.
+* **Tamper-evident hash chain.** Each row stores ``prev_hash`` and
+ ``entry_hash`` (sha256, computed by
+ :mod:`app.services.audit_hash`) so an external verifier can prove
+ the chain was not truncated, reordered, or rewritten — even by an
+ operator with ``DISABLE TRIGGER`` privileges. The DB-side
+ immutability trigger (migration 004) still defends the normal SQL
+ path; the chain catches what the trigger cannot.
"""
from __future__ import annotations
+import logging
import uuid
+from datetime import UTC, datetime
from typing import Any
from fastapi import Request
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
+from app.core.trusted_proxy import resolve_client_ip
from app.models.audit import AuditLog
+from app.services.audit_hash import compute_entry_hash
+from app.services.audit_redaction import redact_changes
+
+logger = logging.getLogger("aisoc.audit")
+
+# Hard caps on header-derived metadata that lands in the audit row.
+# These exist independently of changes-payload redaction and protect
+# the ``metadata`` JSONB column from arbitrary client growth.
+_MAX_UA_LEN = 512
+_MAX_REQUEST_ID_LEN = 128
+
+
+async def _resolve_prev_hash(db: AsyncSession, tenant_id: uuid.UUID) -> str | None:
+ """Return the most recent ``entry_hash`` for ``tenant_id``.
+
+ Ordering by ``created_at DESC, id DESC`` is deliberate:
+ ``created_at`` may collide at microsecond granularity for events
+ emitted in a single request, so we tiebreak on ``id`` to keep the
+ chain deterministic even when wall-clock time does not move.
+
+ Returns ``None`` for the genesis (first ever audit row for this
+ tenant). Legacy rows that pre-date the hash chain — where
+ ``entry_hash IS NULL`` — are skipped via the partial index from
+ migration 043; new chains begin from the first hashed row.
+ """
+ stmt = (
+ select(AuditLog.entry_hash)
+ .where(AuditLog.tenant_id == tenant_id)
+ .where(AuditLog.entry_hash.is_not(None))
+ .order_by(AuditLog.created_at.desc(), AuditLog.id.desc())
+ .limit(1)
+ )
+ result = await db.execute(stmt)
+ return result.scalar_one_or_none()
+
+
+def _safe_truncate(value: str | None, limit: int) -> str | None:
+ """Trim a header value to ``limit`` characters, preserving None."""
+ if value is None:
+ return None
+ if len(value) <= limit:
+ return value
+ return value[:limit]
async def emit_audit(
@@ -38,35 +111,60 @@ async def emit_audit(
changes: dict[str, Any] | None = None,
request: Request | None = None,
) -> AuditLog:
- """Append an immutable audit event to the log.
+ """Append an immutable, hash-chained audit event to the log.
+
+ The caller still owns the transaction — ``db.add()`` is queued, but
+ we do not commit. Callers that need a strict guarantee that the
+ audit row outlives the rest of their work (i.e. a request can fail
+ *after* committing audit but *before* the business write) should
+ wrap their handler in a savepoint and commit the audit row first.
+ The hash chain is robust either way; in-flight rows simply do not
+ yet have an ``entry_hash`` reader.
Parameters
----------
- db: Active async session (does NOT commit – caller controls).
- tenant_id: The tenant this event belongs to.
+ db: Active async session.
+ tenant_id: Tenant this event belongs to.
actor_id: User UUID performing the action (optional).
actor_email: Email for denormalised search (optional).
action: Dot/colon action string, e.g. ``cases:create``.
resource: Resource type, e.g. ``case``.
resource_id: Primary key / identifier of the affected object.
- changes: Before/after dict or delta payload.
+ changes: Before/after dict or delta payload. Will be redacted
+ and size-capped before persistence.
request: FastAPI ``Request`` to extract IP & user-agent.
"""
actor_ip: str | None = None
meta: dict[str, Any] = {}
if request is not None:
- # Respect X-Forwarded-For if behind a proxy
- forwarded = request.headers.get("x-forwarded-for")
- actor_ip = (forwarded.split(",")[0].strip() if forwarded else None) or str(request.client.host) if request.client else None
- ua = request.headers.get("user-agent")
+ # Trusted-proxy aware IP resolution — see services/api/app/core/trusted_proxy.py.
+ try:
+ actor_ip = resolve_client_ip(request)
+ except Exception: # noqa: BLE001
+ # We never want audit attribution to take down a mutating
+ # request. Log and fall through with no IP attached.
+ logger.warning("audit: failed to resolve client IP", exc_info=True)
+ actor_ip = None
+
+ ua = _safe_truncate(request.headers.get("user-agent"), _MAX_UA_LEN)
if ua:
meta["user_agent"] = ua
- rid = request.headers.get("x-request-id")
+ rid = _safe_truncate(request.headers.get("x-request-id"), _MAX_REQUEST_ID_LEN)
if rid:
meta["request_id"] = rid
+ # Sanitize before persistence. Anything secret-shaped is masked,
+ # and oversized payloads collapse to a marker row.
+ safe_changes = redact_changes(changes)
+
+ # Stable created_at — set explicitly so the hash uses the same
+ # value the DB will store. Without this, default=lambda runs at
+ # flush time and we'd hash one timestamp and persist another.
+ created_at = datetime.now(UTC)
+
event = AuditLog(
+ id=uuid.uuid4(),
tenant_id=tenant_id,
actor_id=actor_id,
actor_email=actor_email,
@@ -74,8 +172,42 @@ async def emit_audit(
action=action,
resource=resource,
resource_id=resource_id,
- changes=changes,
+ changes=safe_changes,
metadata_=meta or None,
+ created_at=created_at,
)
+
+ # Chain-link this row onto the tenant's prior history. If the
+ # lookup fails for any reason (e.g. transient DB blip) we still
+ # write the row — falling back to an unchained entry is strictly
+ # better than failing the originating mutation, and the gap is
+ # detectable by the verifier.
+ try:
+ prev = await _resolve_prev_hash(db, tenant_id)
+ event.prev_hash = prev
+ event.entry_hash = compute_entry_hash(
+ prev_hash=prev,
+ row_id=event.id,
+ tenant_id=event.tenant_id,
+ actor_id=event.actor_id,
+ actor_email=event.actor_email,
+ actor_ip=event.actor_ip,
+ action=event.action,
+ resource=event.resource,
+ resource_id=event.resource_id,
+ changes=event.changes,
+ metadata=event.metadata_,
+ created_at=event.created_at,
+ )
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "audit: failed to compute hash chain for tenant=%s action=%s",
+ tenant_id,
+ action,
+ exc_info=True,
+ )
+ event.prev_hash = None
+ event.entry_hash = None
+
db.add(event)
return event
diff --git a/services/api/app/services/audit_hash.py b/services/api/app/services/audit_hash.py
new file mode 100644
index 000000000..6b6ca9cfe
--- /dev/null
+++ b/services/api/app/services/audit_hash.py
@@ -0,0 +1,166 @@
+"""Tamper-evident hash chain for audit log entries.
+
+The ``audit_log`` table is already write-only (trigger-enforced) and
+tenant-isolated (RLS). What that combination does *not* defend against
+is a privileged operator with SQL access doing
+``TRUNCATE audit_log`` / ``DROP TABLE`` / ``DELETE WHERE …`` (via
+``ALTER TABLE … DISABLE TRIGGER ALL``) and replacing the history with a
+forgery. The trigger only fires on UPDATE/DELETE through the normal
+SQL path; a sufficiently privileged actor can bypass it.
+
+A hash chain closes that gap **without** trusting Postgres. Every audit
+row stores:
+
+* ``prev_hash`` — the ``entry_hash`` of the previous audit row for
+ the same tenant, or ``None`` for the first row.
+* ``entry_hash`` — sha256 over a canonical serialization of this row's
+ business fields, mixed with ``prev_hash``.
+
+Anyone — including an external auditor — can replay the chain
+deterministically and prove that no row was deleted, reordered, or
+silently rewritten. The verification logic is intentionally pure (no
+DB access) so it can run on a CSV export as easily as a live row.
+
+The algorithm:
+
+1. Build a stable, sorted-key JSON payload of the fields that define
+ the audit event (``tenant_id``, ``actor_id``, ``actor_email``,
+ ``actor_ip``, ``action``, ``resource``, ``resource_id``,
+ ``changes`` already-redacted, ``metadata``, ``created_at`` in
+ ISO-8601, and the row ``id`` itself).
+2. Prepend the ``prev_hash`` (or an empty string for the genesis row).
+3. ``entry_hash = sha256(payload).hexdigest()``.
+
+The set of hashed fields is deliberately conservative — adding a field
+is a chain-breaking change and requires a schema migration. We
+explicitly include the row ``id`` because the table assigns one by
+default and including it makes the chain agnostic to insertion order
+within the same wall-clock microsecond.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+from datetime import datetime
+from typing import Any
+
+
+def _canonicalise(value: Any) -> Any:
+ """Map non-JSON-native types into something ``json.dumps`` can encode deterministically."""
+ if value is None or isinstance(value, (bool, int, float, str)):
+ return value
+ if isinstance(value, uuid.UUID):
+ return str(value)
+ if isinstance(value, datetime):
+ # ISO 8601 with explicit offset; required for chain stability
+ # across DB drivers that may otherwise stringify with subtle
+ # whitespace differences.
+ return value.isoformat()
+ if isinstance(value, dict):
+ return {str(k): _canonicalise(v) for k, v in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_canonicalise(v) for v in value]
+ # Fallback: stringify. Audit metadata occasionally contains exotic
+ # values (e.g. enum instances); we never want the hash to crash.
+ return str(value)
+
+
+def compute_entry_hash(
+ *,
+ prev_hash: str | None,
+ row_id: uuid.UUID,
+ tenant_id: uuid.UUID,
+ actor_id: uuid.UUID | None,
+ actor_email: str | None,
+ actor_ip: str | None,
+ action: str,
+ resource: str | None,
+ resource_id: str | None,
+ changes: dict[str, Any] | None,
+ metadata: dict[str, Any] | None,
+ created_at: datetime,
+) -> str:
+ """Compute the SHA-256 hash of the canonical row contents + prev hash.
+
+ The ``changes`` payload MUST already have been passed through
+ :func:`app.services.audit_redaction.redact_changes` — the chain is
+ over the *persisted* form, not the original caller-supplied dict.
+ """
+ body = {
+ "id": _canonicalise(row_id),
+ "tenant_id": _canonicalise(tenant_id),
+ "actor_id": _canonicalise(actor_id),
+ "actor_email": actor_email,
+ "actor_ip": actor_ip,
+ "action": action,
+ "resource": resource,
+ "resource_id": resource_id,
+ "changes": _canonicalise(changes),
+ "metadata": _canonicalise(metadata),
+ "created_at": _canonicalise(created_at),
+ }
+ serialised = json.dumps(body, sort_keys=True, separators=(",", ":"), default=str)
+ h = hashlib.sha256()
+ h.update((prev_hash or "").encode("utf-8"))
+ # Domain separator stops accidental collisions if anyone reuses the
+ # encoded body in another hash context.
+ h.update(b"\x1faudit-log-v1\x1f")
+ h.update(serialised.encode("utf-8"))
+ return h.hexdigest()
+
+
+def verify_chain(rows: list[dict[str, Any]]) -> tuple[bool, int | None, str | None]:
+ """Replay ``rows`` (oldest → newest, same tenant) and verify the chain.
+
+ Each row must expose the same field names as
+ :func:`compute_entry_hash` plus ``prev_hash`` and ``entry_hash``.
+
+ Returns ``(True, None, None)`` on success, or
+ ``(False, index, reason)`` pointing at the first violating row.
+ A row missing ``entry_hash`` is treated as legacy / unchained and
+ skipped — the chain "starts" from the first row that carries one.
+ This keeps existing deployments verifiable without a backfill.
+ """
+ prev_hash: str | None = None
+ started = False
+ for idx, row in enumerate(rows):
+ stored = row.get("entry_hash")
+ if stored is None:
+ if started:
+ # Once a tenant has chained rows, every subsequent row
+ # must also be chained. A gap = tampering.
+ return False, idx, "chain interrupted: entry_hash missing"
+ continue
+ started = True
+
+ # prev_hash on the row must match the chain we have so far.
+ recorded_prev = row.get("prev_hash")
+ if recorded_prev != prev_hash:
+ return False, idx, "prev_hash mismatch"
+
+ computed = compute_entry_hash(
+ prev_hash=prev_hash,
+ row_id=row["id"],
+ tenant_id=row["tenant_id"],
+ actor_id=row.get("actor_id"),
+ actor_email=row.get("actor_email"),
+ actor_ip=row.get("actor_ip"),
+ action=row["action"],
+ resource=row.get("resource"),
+ resource_id=row.get("resource_id"),
+ changes=row.get("changes"),
+ metadata=row.get("metadata"),
+ created_at=row["created_at"],
+ )
+ if computed != stored:
+ return False, idx, "entry_hash mismatch"
+ prev_hash = computed
+ return True, None, None
+
+
+__all__ = [
+ "compute_entry_hash",
+ "verify_chain",
+]
diff --git a/services/api/app/services/audit_redaction.py b/services/api/app/services/audit_redaction.py
new file mode 100644
index 000000000..355b0d3c8
--- /dev/null
+++ b/services/api/app/services/audit_redaction.py
@@ -0,0 +1,170 @@
+"""Sanitization of audit-log ``changes`` payloads.
+
+The ``changes`` JSONB column on ``audit_log`` is fed directly from caller
+code today. That is two distinct hazards:
+
+* **Secret leakage.** Endpoints often hand the audit helper a dict that
+ contains the same fields just persisted to disk — including
+ ``password``, ``secret_key``, OAuth refresh tokens, raw API keys, and
+ similar high-value fields. Anything written here ends up in the
+ tamper-evident, immutable, RLS-scoped audit table; in plain text.
+* **Unbounded size.** A poorly bounded import endpoint could attach an
+ entire 50 MB payload to a single audit row, blow out Postgres TOAST
+ pages, and make ``/api/v1/audit`` listings unusable.
+
+This module exists so every audit write path goes through the same
+deterministic sanitizer. The behaviour is intentionally simple:
+
+1. Recursively redact any dict key (case-insensitive) that matches one
+ of the patterns in :data:`SENSITIVE_KEY_PATTERNS`. The value is
+ replaced with the sentinel string ``"[REDACTED]"`` so downstream
+ readers can tell something was scrubbed (vs. a missing field).
+2. Enforce a hard size cap by serialising the redacted payload to JSON
+ and, if the result exceeds the configured limit, replacing it with a
+ small ``{"_truncated": True, ...}`` placeholder that records the
+ original byte count. We never silently drop fields.
+3. Cap recursion depth and total node count to make sure a hostile
+ caller cannot DOS the audit pipeline with a deeply nested or
+ million-key payload.
+
+The cap is read lazily from the ``AISOC_AUDIT_MAX_CHANGES_BYTES``
+environment variable so operators can dial it without a redeploy.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+from typing import Any
+
+# Substrings (case-insensitive, matched anywhere in the key) that flag a
+# value as sensitive. Conservative on purpose — the audit trail is a
+# compliance artefact, not a debug log. New patterns should be added
+# proactively rather than waiting for a leak.
+SENSITIVE_KEY_PATTERNS: tuple[re.Pattern[str], ...] = tuple(
+ re.compile(pattern, re.IGNORECASE)
+ for pattern in (
+ r"password",
+ r"passwd",
+ r"secret",
+ r"token",
+ r"api[_-]?key",
+ r"private[_-]?key",
+ r"credential",
+ r"authorization",
+ r"^auth$",
+ r"client[_-]?secret",
+ r"refresh[_-]?token",
+ r"access[_-]?token",
+ r"session[_-]?id",
+ r"cookie",
+ r"otp",
+ r"mfa[_-]?code",
+ r"recovery[_-]?code",
+ r"webhook[_-]?secret",
+ r"signing[_-]?key",
+ )
+)
+
+REDACTED_SENTINEL = "[REDACTED]"
+
+# Defaults — operators override via env. Numbers chosen so the average
+# payload (a few hundred bytes of field deltas) fits comfortably while
+# catching the genuine pathological cases.
+_DEFAULT_MAX_BYTES = 16 * 1024 # 16 KB
+_MAX_DEPTH = 8
+_MAX_NODES = 2_000
+
+_MAX_BYTES_ENV = "AISOC_AUDIT_MAX_CHANGES_BYTES"
+
+
+def _max_bytes() -> int:
+ """Resolve the configured size cap (bytes).
+
+ Read at call-time so tests can monkeypatch via env. Falls back to the
+ default on any parse error so the audit pipeline keeps working even
+ if the env is misconfigured.
+ """
+ raw = os.getenv(_MAX_BYTES_ENV)
+ if not raw:
+ return _DEFAULT_MAX_BYTES
+ try:
+ value = int(raw)
+ except ValueError:
+ return _DEFAULT_MAX_BYTES
+ # Guard against silly values; a 0/negative cap would tank every write.
+ return max(value, 256)
+
+
+def _is_sensitive_key(key: str) -> bool:
+ if not isinstance(key, str):
+ return False
+ return any(pat.search(key) for pat in SENSITIVE_KEY_PATTERNS)
+
+
+def _redact_node(value: Any, depth: int, counter: list[int]) -> Any:
+ """Recursive walker — see :func:`redact_changes`."""
+ counter[0] += 1
+ if counter[0] > _MAX_NODES:
+ return REDACTED_SENTINEL
+ if depth > _MAX_DEPTH:
+ return REDACTED_SENTINEL
+
+ if isinstance(value, dict):
+ out: dict[str, Any] = {}
+ for k, v in value.items():
+ key = str(k)
+ if _is_sensitive_key(key):
+ out[key] = REDACTED_SENTINEL
+ else:
+ out[key] = _redact_node(v, depth + 1, counter)
+ return out
+ if isinstance(value, (list, tuple)):
+ return [_redact_node(item, depth + 1, counter) for item in value]
+ # Primitives pass through unchanged. We deliberately do NOT inspect
+ # the value side for "looks like a token" heuristics — that creates
+ # false positives that hide legitimate audit data. Sensitivity is
+ # encoded in the key.
+ return value
+
+
+def redact_changes(changes: dict[str, Any] | None) -> dict[str, Any] | None:
+ """Return a copy of ``changes`` with sensitive values masked and size-bounded.
+
+ ``None`` and empty inputs pass through unchanged so callers can keep
+ using ``changes=None`` as "no payload".
+ """
+ if not changes:
+ return changes
+
+ counter = [0]
+ redacted = _redact_node(changes, depth=0, counter=counter)
+ # ``_redact_node`` always returns a dict for a dict input.
+ assert isinstance(redacted, dict)
+
+ # Size-cap as a final post-processing pass. ``default=str`` ensures
+ # exotic but JSON-incompatible values (e.g. ``datetime``) don't crash
+ # the serialiser; the row would still be stored as JSONB.
+ try:
+ encoded = json.dumps(redacted, default=str, separators=(",", ":"))
+ except (TypeError, ValueError):
+ return {"_truncated": True, "_reason": "unserializable"}
+
+ cap = _max_bytes()
+ size = len(encoded.encode("utf-8"))
+ if size <= cap:
+ return redacted
+
+ return {
+ "_truncated": True,
+ "_original_size_bytes": size,
+ "_max_size_bytes": cap,
+ }
+
+
+__all__ = [
+ "redact_changes",
+ "REDACTED_SENTINEL",
+ "SENSITIVE_KEY_PATTERNS",
+]
diff --git a/services/api/migrations/043_audit_log_hash_chain.sql b/services/api/migrations/043_audit_log_hash_chain.sql
new file mode 100644
index 000000000..18289a7d2
--- /dev/null
+++ b/services/api/migrations/043_audit_log_hash_chain.sql
@@ -0,0 +1,38 @@
+-- 043_audit_log_hash_chain.sql
+--
+-- Add tamper-evident hash-chaining to the audit_log table.
+--
+-- Why: ``audit_log`` already enforces append-only writes through a
+-- trigger (see 004_audit_log.sql) and tenant isolation through RLS.
+-- What it does NOT defend against is a privileged operator (or stolen
+-- DB credentials) issuing a DROP/RECREATE or TRUNCATE on the table and
+-- forging a replacement history that still satisfies the trigger.
+--
+-- A hash-chain closes that gap. Each row carries:
+-- * ``prev_hash`` — the ``entry_hash`` of the previous audit row
+-- for the same tenant, or NULL for the first.
+-- * ``entry_hash`` — sha256 over the canonical serialization of the
+-- row's fields, mixed with ``prev_hash``.
+--
+-- Verification (offline or via the export endpoint) replays the chain
+-- per tenant and proves no row was deleted, reordered, or rewritten.
+-- The trigger-enforced immutability still applies; the chain catches
+-- the cases the trigger cannot.
+--
+-- Both columns are nullable + idempotent so existing deployments can
+-- adopt the chain without a backfill flag day — new rows chain off the
+-- last existing row (or NULL if the table is empty for that tenant).
+
+BEGIN;
+
+ALTER TABLE audit_log
+ ADD COLUMN IF NOT EXISTS prev_hash VARCHAR(64),
+ ADD COLUMN IF NOT EXISTS entry_hash VARCHAR(64);
+
+-- Index supports the "latest entry per tenant" lookup that the chain
+-- writer performs on every insert.
+CREATE INDEX IF NOT EXISTS idx_audit_tenant_entry_hash
+ ON audit_log(tenant_id, created_at DESC)
+ WHERE entry_hash IS NOT NULL;
+
+COMMIT;
diff --git a/services/api/tests/test_audit_hash.py b/services/api/tests/test_audit_hash.py
new file mode 100644
index 000000000..e689fa742
--- /dev/null
+++ b/services/api/tests/test_audit_hash.py
@@ -0,0 +1,319 @@
+"""Tests for audit-log tamper-evident hash chain.
+
+The hash chain is the only mechanism that defends ``audit_log`` against
+a privileged operator (or stolen DB credentials) that bypasses the
+immutability trigger via ``ALTER TABLE … DISABLE TRIGGER ALL`` /
+``TRUNCATE`` and forges a replacement history. Anyone — auditor or
+incident responder — can replay the chain on a CSV export to prove the
+history is intact.
+
+This suite locks down the contract that compliance teams rely on:
+
+1. ``compute_entry_hash`` is **deterministic** for a given set of inputs
+ (same row + same prev_hash → same digest).
+2. Mutating ANY business-relevant field changes the digest.
+3. ``prev_hash`` is mixed in so the chain is order-dependent
+ (reordering rows breaks verification).
+4. ``verify_chain`` accepts a valid chain.
+5. ``verify_chain`` rejects: a deleted row, a rewritten row, a reordered
+ row, and a row whose ``prev_hash`` doesn't link.
+6. Legacy rows (no ``entry_hash``) are tolerated at the head of a
+ tenant's history — but a gap *after* the chain has started is a
+ forgery signal.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+import pytest
+from app.services.audit_hash import compute_entry_hash, verify_chain
+
+
+def _ts(seconds: int) -> datetime:
+ return datetime(2026, 5, 9, 12, 0, seconds, tzinfo=UTC)
+
+
+def _row(
+ *,
+ prev_hash: str | None,
+ row_id: uuid.UUID | None = None,
+ tenant_id: uuid.UUID | None = None,
+ actor_id: uuid.UUID | None = None,
+ actor_email: str | None = "[email protected]",
+ actor_ip: str | None = "10.0.0.1",
+ action: str = "cases:update",
+ resource: str | None = "case",
+ resource_id: str | None = "case-42",
+ changes: dict[str, Any] | None = None,
+ metadata: dict[str, Any] | None = None,
+ created_at: datetime | None = None,
+) -> dict[str, Any]:
+ """Build a row dict + its computed ``entry_hash`` for chain replay."""
+ rid = row_id or uuid.UUID("11111111-1111-1111-1111-111111111111")
+ tid = tenant_id or uuid.UUID("22222222-2222-2222-2222-222222222222")
+ aid = actor_id if actor_id is not None else uuid.UUID("33333333-3333-3333-3333-333333333333")
+ ts = created_at or _ts(0)
+ digest = compute_entry_hash(
+ prev_hash=prev_hash,
+ row_id=rid,
+ tenant_id=tid,
+ actor_id=aid,
+ actor_email=actor_email,
+ actor_ip=actor_ip,
+ action=action,
+ resource=resource,
+ resource_id=resource_id,
+ changes=changes,
+ metadata=metadata,
+ created_at=ts,
+ )
+ return {
+ "id": rid,
+ "tenant_id": tid,
+ "actor_id": aid,
+ "actor_email": actor_email,
+ "actor_ip": actor_ip,
+ "action": action,
+ "resource": resource,
+ "resource_id": resource_id,
+ "changes": changes,
+ "metadata": metadata,
+ "created_at": ts,
+ "prev_hash": prev_hash,
+ "entry_hash": digest,
+ }
+
+
+# ---------------------------------------------------------------------------
+# compute_entry_hash
+# ---------------------------------------------------------------------------
+
+
+class TestComputeEntryHash:
+ def test_deterministic(self):
+ """Same inputs → same digest. The whole chain rests on this."""
+ kwargs = {
+ "prev_hash": None,
+ "row_id": uuid.UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
+ "tenant_id": uuid.UUID("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
+ "actor_id": uuid.UUID("cccccccc-cccc-cccc-cccc-cccccccccccc"),
+ "actor_email": "[email protected]",
+ "actor_ip": "1.2.3.4",
+ "action": "cases:update",
+ "resource": "case",
+ "resource_id": "case-1",
+ "changes": {"status": ["open", "closed"]},
+ "metadata": {"request_id": "rid-1"},
+ "created_at": _ts(0),
+ }
+ a = compute_entry_hash(**kwargs)
+ b = compute_entry_hash(**kwargs)
+ assert a == b
+ assert len(a) == 64, "sha256 hex digest must be 64 chars"
+
+ def test_prev_hash_changes_digest(self):
+ """Same row, different prev_hash → different digest. Order-bound."""
+ base_kwargs = {
+ "row_id": uuid.UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
+ "tenant_id": uuid.UUID("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
+ "actor_id": None,
+ "actor_email": None,
+ "actor_ip": None,
+ "action": "x",
+ "resource": "y",
+ "resource_id": "z",
+ "changes": None,
+ "metadata": None,
+ "created_at": _ts(0),
+ }
+ h1 = compute_entry_hash(prev_hash=None, **base_kwargs)
+ h2 = compute_entry_hash(prev_hash="deadbeef", **base_kwargs)
+ h3 = compute_entry_hash(prev_hash="cafe", **base_kwargs)
+ assert h1 != h2 != h3
+ assert h1 != h3
+
+ @pytest.mark.parametrize(
+ "field,new_value",
+ [
+ ("actor_email", "[email protected]"),
+ ("actor_ip", "9.9.9.9"),
+ ("action", "cases:delete"),
+ ("resource", "alert"),
+ ("resource_id", "case-999"),
+ ("changes", {"status": ["open", "investigating"]}),
+ ("metadata", {"request_id": "rid-2"}),
+ ],
+ )
+ def test_mutating_any_business_field_changes_digest(self, field, new_value):
+ """A forgery that changes a single business-relevant field must be detectable."""
+ base = {
+ "prev_hash": "abc",
+ "row_id": uuid.UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
+ "tenant_id": uuid.UUID("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
+ "actor_id": uuid.UUID("cccccccc-cccc-cccc-cccc-cccccccccccc"),
+ "actor_email": "[email protected]",
+ "actor_ip": "1.2.3.4",
+ "action": "cases:update",
+ "resource": "case",
+ "resource_id": "case-1",
+ "changes": {"status": ["open", "closed"]},
+ "metadata": {"request_id": "rid-1"},
+ "created_at": _ts(0),
+ }
+ h_before = compute_entry_hash(**base)
+ mutated = dict(base)
+ mutated[field] = new_value
+ h_after = compute_entry_hash(**mutated)
+ assert h_before != h_after, f"changing {field} must change the chain digest; otherwise a forgery would pass verification"
+
+ def test_changing_created_at_changes_digest(self):
+ base = {
+ "prev_hash": None,
+ "row_id": uuid.UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
+ "tenant_id": uuid.UUID("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
+ "actor_id": None,
+ "actor_email": None,
+ "actor_ip": None,
+ "action": "x",
+ "resource": "y",
+ "resource_id": "z",
+ "changes": None,
+ "metadata": None,
+ }
+ h1 = compute_entry_hash(**base, created_at=_ts(0))
+ h2 = compute_entry_hash(**base, created_at=_ts(1))
+ assert h1 != h2
+
+ def test_exotic_changes_values_do_not_crash(self):
+ """Audit metadata occasionally contains non-JSON-native types."""
+
+ class WeirdEnum:
+ def __str__(self) -> str:
+ return "weird"
+
+ # Should not raise — the helper must fall back to stringification.
+ h = compute_entry_hash(
+ prev_hash=None,
+ row_id=uuid.UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"),
+ tenant_id=uuid.UUID("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"),
+ actor_id=None,
+ actor_email=None,
+ actor_ip=None,
+ action="x",
+ resource=None,
+ resource_id=None,
+ changes={"thing": WeirdEnum()},
+ metadata=None,
+ created_at=_ts(0),
+ )
+ assert len(h) == 64
+
+
+# ---------------------------------------------------------------------------
+# verify_chain
+# ---------------------------------------------------------------------------
+
+
+class TestVerifyChain:
+ def _build_chain(self, n: int) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ prev: str | None = None
+ for i in range(n):
+ row = _row(
+ prev_hash=prev,
+ row_id=uuid.UUID(f"{i:08x}-0000-4000-8000-000000000000"),
+ action=f"cases:update#{i}",
+ created_at=_ts(i),
+ )
+ rows.append(row)
+ prev = row["entry_hash"]
+ return rows
+
+ def test_empty_chain_passes(self):
+ ok, idx, reason = verify_chain([])
+ assert ok is True
+ assert idx is None
+ assert reason is None
+
+ def test_valid_chain_passes(self):
+ rows = self._build_chain(5)
+ ok, idx, reason = verify_chain(rows)
+ assert ok, f"verification failed at {idx}: {reason}"
+
+ def test_rewritten_row_is_detected(self):
+ rows = self._build_chain(5)
+ # An operator tries to whitewash row 2 by editing the action.
+ rows[2]["action"] = "cases:read"
+ ok, idx, reason = verify_chain(rows)
+ assert ok is False
+ # Either row 2 fails directly (entry_hash mismatch) or row 3 fails
+ # because its prev_hash no longer matches the recomputed chain.
+ assert idx in (2, 3)
+ assert reason is not None
+
+ def test_deleted_row_is_detected(self):
+ rows = self._build_chain(5)
+ # Drop row 2 — the chain now skips a link.
+ del rows[2]
+ ok, idx, reason = verify_chain(rows)
+ assert ok is False
+ # The break shows up at the row that used to follow the deleted one.
+ assert idx == 2
+ assert reason is not None
+
+ def test_reordered_rows_are_detected(self):
+ rows = self._build_chain(5)
+ rows[1], rows[2] = rows[2], rows[1]
+ ok, idx, reason = verify_chain(rows)
+ assert ok is False
+ assert idx is not None
+ assert reason is not None
+
+ def test_prev_hash_tampering_is_detected(self):
+ rows = self._build_chain(3)
+ rows[1]["prev_hash"] = "deadbeef" * 8 # bogus 64-char hex
+ ok, idx, reason = verify_chain(rows)
+ assert ok is False
+ assert idx == 1
+ assert "prev_hash" in (reason or "")
+
+ def test_entry_hash_tampering_is_detected(self):
+ rows = self._build_chain(3)
+ rows[1]["entry_hash"] = "0" * 64
+ ok, idx, reason = verify_chain(rows)
+ assert ok is False
+ assert idx == 1
+ assert "entry_hash" in (reason or "")
+
+ def test_legacy_rows_without_chain_are_skipped(self):
+ """Existing deployments without backfilled hashes must still verify."""
+ rows = self._build_chain(2)
+ # Two legacy rows at the head (no entry_hash). Then the chained pair.
+ legacy_a = dict(rows[0])
+ legacy_a["entry_hash"] = None
+ legacy_a["prev_hash"] = None
+ legacy_b = dict(rows[1])
+ legacy_b["entry_hash"] = None
+ legacy_b["prev_hash"] = None
+ # Re-chain the tail from genesis since we treat it as the start.
+ fresh_a = _row(prev_hash=None, created_at=_ts(10))
+ fresh_b = _row(prev_hash=fresh_a["entry_hash"], created_at=_ts(11))
+ ok, idx, reason = verify_chain([legacy_a, legacy_b, fresh_a, fresh_b])
+ assert ok, f"verification failed at {idx}: {reason}"
+
+ def test_gap_after_chain_start_is_detected(self):
+ """Once we have chained rows, every subsequent row MUST be chained."""
+ a = _row(prev_hash=None, created_at=_ts(0))
+ # The "forgery" — a row inserted without joining the chain.
+ forgery = dict(a)
+ forgery["id"] = uuid.UUID("ffffffff-ffff-4fff-8fff-ffffffffffff")
+ forgery["created_at"] = _ts(1)
+ forgery["prev_hash"] = None
+ forgery["entry_hash"] = None
+ ok, idx, reason = verify_chain([a, forgery])
+ assert ok is False
+ assert idx == 1
+ assert "missing" in (reason or "").lower() or "chain" in (reason or "").lower()
diff --git a/services/api/tests/test_audit_redaction.py b/services/api/tests/test_audit_redaction.py
new file mode 100644
index 000000000..e0d41c83a
--- /dev/null
+++ b/services/api/tests/test_audit_redaction.py
@@ -0,0 +1,189 @@
+"""Tests for the audit-log ``changes`` redaction & size-cap layer.
+
+Why these matter
+----------------
+``audit_log.changes`` is JSONB on an immutable, RLS-scoped table. Once a
+secret lands in it, you cannot delete or rewrite it through the normal
+SQL path — the same property that makes audit useful for compliance
+makes it dangerous if we ever persist a raw password / token / API key.
+
+The redactor is the choke-point that prevents that. These tests pin the
+following contract:
+
+1. Sensitive-looking keys are masked at every nesting level.
+2. The pattern set is case-insensitive and matches dashed/underscored
+ variants ("api_key", "api-key", "API-Key").
+3. Lists of dicts (e.g. role bindings, change deltas) are redacted too.
+4. Oversized payloads are reduced to a marker row rather than persisted.
+5. The redactor never crashes on malformed input — audit must not
+ break the originating mutation.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import pytest
+from app.services.audit_redaction import (
+ REDACTED_SENTINEL,
+ redact_changes,
+)
+
+
+def _is_redacted(value: Any) -> bool:
+ return value == REDACTED_SENTINEL
+
+
+class TestSensitiveKeyMatching:
+ """Keys that *look* like secrets must be redacted regardless of casing."""
+
+ @pytest.mark.parametrize(
+ "key",
+ [
+ "password",
+ "Password",
+ "PASSWORD",
+ "passwd",
+ "secret",
+ "client_secret",
+ "client-secret",
+ "ClientSecret",
+ "token",
+ "api_key",
+ "api-key",
+ "ApiKey",
+ "private_key",
+ "credential",
+ "authorization",
+ "auth",
+ "refresh_token",
+ "access_token",
+ "session_id",
+ "cookie",
+ "otp",
+ "mfa_code",
+ "recovery_code",
+ "webhook_secret",
+ "signing_key",
+ ],
+ )
+ def test_top_level_sensitive_key_redacted(self, key: str):
+ out = redact_changes({key: "super-sensitive-value"})
+ assert out is not None
+ assert _is_redacted(out[key]), f"key {key!r} should have been masked but was {out[key]!r}"
+
+ def test_non_sensitive_keys_pass_through(self):
+ """Innocuous keys must NOT be touched — false positives erode trust."""
+ payload = {
+ "title": "Suspicious login from 1.2.3.4",
+ "severity": "high",
+ "count": 7,
+ "tags": ["aws", "iam"],
+ }
+ out = redact_changes(payload)
+ assert out == payload
+
+ def test_substring_match_redacts(self):
+ """A field named ``user_password_hash`` is still sensitive."""
+ out = redact_changes({"user_password_hash": "$2b$..."})
+ assert _is_redacted(out["user_password_hash"])
+
+
+class TestNestedStructures:
+ """Sensitive keys nested in dicts and lists must still be masked."""
+
+ def test_nested_dict(self):
+ payload = {
+ "user": {
+ "email": "[email protected]",
+ "password": "p4ssw0rd",
+ "profile": {"api_key": "sk-abc"},
+ }
+ }
+ out = redact_changes(payload)
+ assert out["user"]["email"] == "[email protected]"
+ assert _is_redacted(out["user"]["password"])
+ assert _is_redacted(out["user"]["profile"]["api_key"])
+
+ def test_list_of_dicts(self):
+ payload = {
+ "bindings": [
+ {"role": "admin", "token": "t1"},
+ {"role": "viewer", "token": "t2"},
+ ]
+ }
+ out = redact_changes(payload)
+ assert [b["role"] for b in out["bindings"]] == ["admin", "viewer"]
+ assert all(_is_redacted(b["token"]) for b in out["bindings"])
+
+ def test_change_delta_tuple_form(self):
+ """Audit emits ``{"field": [before, after]}`` deltas; lists of scalars must pass through."""
+ out = redact_changes({"status": ["open", "investigating"]})
+ assert out["status"] == ["open", "investigating"]
+
+
+class TestPassthroughs:
+ def test_none_returns_none(self):
+ assert redact_changes(None) is None
+
+ def test_empty_dict_returns_empty(self):
+ assert redact_changes({}) == {}
+
+ def test_does_not_mutate_input(self):
+ original = {"password": "x", "ok": 1}
+ snapshot = json.loads(json.dumps(original))
+ redact_changes(original)
+ assert original == snapshot, "redact_changes must not mutate caller's dict"
+
+
+class TestSizeCap:
+ """Oversized payloads must be capped instead of persisted as-is."""
+
+ def test_oversized_payload_replaced_with_marker(self, monkeypatch):
+ # Lower the cap to make the test fast and deterministic.
+ monkeypatch.setenv("AISOC_AUDIT_MAX_CHANGES_BYTES", "256")
+ # ~10KB of content — comfortably over 256 bytes when JSON-encoded.
+ payload = {"data": "x" * 10_000}
+ out = redact_changes(payload)
+ assert out is not None
+ # The marker row should be JSON-serializable and substantially
+ # smaller than the original.
+ encoded = json.dumps(out)
+ assert len(encoded) < 1024
+ # It should advertise WHY the payload was redacted.
+ assert "truncated" in json.dumps(out).lower() or "size" in json.dumps(out).lower()
+
+ def test_under_cap_passes_through(self, monkeypatch):
+ monkeypatch.setenv("AISOC_AUDIT_MAX_CHANGES_BYTES", "65536")
+ payload = {"title": "ok", "count": 3}
+ out = redact_changes(payload)
+ assert out == payload
+
+
+class TestRobustness:
+ """The redactor must never crash on weird input."""
+
+ def test_exotic_value_types_do_not_raise(self):
+ class Custom:
+ def __repr__(self) -> str:
+ return "Custom()"
+
+ # Some endpoints accidentally pass non-JSON types. The redactor
+ # should still produce SOMETHING JSON-encodable rather than
+ # propagating a TypeError up into the request handler.
+ out = redact_changes({"thing": Custom()})
+ assert out is not None
+ # The resulting payload must round-trip through JSON.
+ json.dumps(out, default=str)
+
+ def test_deeply_nested_input_does_not_blow_stack(self):
+ # Construct a 50-deep nested dict. The redactor caps recursion
+ # internally; we only check it doesn't recurse without bound.
+ payload: dict[str, Any] = {"level": 0}
+ cursor = payload
+ for i in range(1, 50):
+ cursor["next"] = {"level": i, "password": "p"}
+ cursor = cursor["next"]
+ out = redact_changes(payload)
+ assert out is not None
diff --git a/services/api/tests/test_trusted_proxy.py b/services/api/tests/test_trusted_proxy.py
new file mode 100644
index 000000000..7525e5c38
--- /dev/null
+++ b/services/api/tests/test_trusted_proxy.py
@@ -0,0 +1,246 @@
+"""Tests for ``app.core.trusted_proxy.resolve_client_ip``.
+
+Why these matter
+----------------
+``actor_ip`` is one of the few audit columns that a hostile client can try
+to influence *from outside* the application — by attaching their own
+``X-Forwarded-For`` header. If we honour that blindly we let an attacker
+write whatever source IP they like into a compliance-grade audit trail.
+
+This suite pins the security contract:
+
+1. Default (no ``AISOC_TRUSTED_PROXIES``) → never trust ``X-Forwarded-For``.
+2. Direct peer not in trusted list → never trust ``X-Forwarded-For``.
+3. Direct peer is a trusted proxy → walk the header right-to-left and
+ return the first untrusted hop (the closest the chain comes to the
+ real client).
+4. Malformed input degrades gracefully to the direct TCP peer — audit
+ must never crash on a weird header.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from typing import Any
+
+import pytest
+from app.core.trusted_proxy import (
+ TRUSTED_PROXIES_ENV,
+ _parse_cidrs,
+ _parse_forwarded_for,
+ resolve_client_ip,
+)
+
+# ---------------------------------------------------------------------------
+# Minimal Request stub. We avoid pulling in starlette TestClient because we
+# only need ``.client.host`` and ``.headers.get``.
+# ---------------------------------------------------------------------------
+
+
+class _StubClient:
+ def __init__(self, host: str | None) -> None:
+ self.host = host
+
+
+class _StubHeaders(Mapping[str, str]):
+ """Case-insensitive headers dict; mimics Starlette's Headers shape."""
+
+ def __init__(self, data: dict[str, str] | None = None) -> None:
+ # Normalize at construction so .get("X-Forwarded-For") and
+ # .get("x-forwarded-for") both work.
+ self._data = {k.lower(): v for k, v in (data or {}).items()}
+
+ def __getitem__(self, key: str) -> str:
+ return self._data[key.lower()]
+
+ def __iter__(self):
+ return iter(self._data)
+
+ def __len__(self) -> int:
+ return len(self._data)
+
+ def get(self, key: str, default: Any = None) -> Any: # type: ignore[override]
+ return self._data.get(key.lower(), default)
+
+
+class _StubRequest:
+ def __init__(
+ self,
+ peer: str | None,
+ headers: dict[str, str] | None = None,
+ ) -> None:
+ self.client = _StubClient(peer) if peer is not None else None
+ self.headers = _StubHeaders(headers)
+
+
+# ---------------------------------------------------------------------------
+# _parse_cidrs / _parse_forwarded_for — small but security-relevant helpers
+# ---------------------------------------------------------------------------
+
+
+class TestParseCidrs:
+ def test_empty_returns_empty(self):
+ assert _parse_cidrs("") == []
+ assert _parse_cidrs(None) == []
+
+ def test_accepts_ipv4_cidr_and_bare_address(self):
+ nets = _parse_cidrs("10.0.0.0/8, 192.168.1.1")
+ assert len(nets) == 2
+ # Bare address is promoted to /32 by ipaddress.ip_network when
+ # strict=False.
+ assert any(str(n) == "192.168.1.1/32" for n in nets)
+
+ def test_accepts_ipv6_cidr(self):
+ nets = _parse_cidrs("2001:db8::/32")
+ assert len(nets) == 1
+
+ def test_skips_invalid_entries(self):
+ """Operator typos must not break the audit pipeline."""
+ nets = _parse_cidrs("10.0.0.0/8, not-a-cidr, 192.168.0.0/16")
+ # 2 valid entries; the garbage in the middle is dropped silently.
+ assert len(nets) == 2
+
+
+class TestParseForwardedFor:
+ def test_empty_inputs(self):
+ assert _parse_forwarded_for(None) == []
+ assert _parse_forwarded_for("") == []
+ assert _parse_forwarded_for(" ") == []
+
+ def test_strips_whitespace(self):
+ assert _parse_forwarded_for("1.2.3.4 , 5.6.7.8") == ["1.2.3.4", "5.6.7.8"]
+
+ def test_strips_ipv4_port(self):
+ assert _parse_forwarded_for("1.2.3.4:5555") == ["1.2.3.4"]
+
+ def test_strips_bracketed_ipv6_port(self):
+ assert _parse_forwarded_for("[2001:db8::1]:8080") == ["2001:db8::1"]
+
+ def test_preserves_bare_ipv6(self):
+ # No port → no rewriting; bare colons in IPv6 must survive.
+ assert _parse_forwarded_for("2001:db8::1") == ["2001:db8::1"]
+
+
+# ---------------------------------------------------------------------------
+# resolve_client_ip — the actual security boundary
+# ---------------------------------------------------------------------------
+
+
+class TestResolveClientIpDefaultDeny:
+ """Without ``AISOC_TRUSTED_PROXIES`` we must NEVER trust XFF."""
+
+ def test_no_env_ignores_xff(self, monkeypatch):
+ monkeypatch.delenv(TRUSTED_PROXIES_ENV, raising=False)
+ req = _StubRequest(
+ peer="203.0.113.10",
+ headers={"x-forwarded-for": "10.0.0.1"},
+ )
+ assert resolve_client_ip(req) == "203.0.113.10"
+
+ def test_empty_env_ignores_xff(self, monkeypatch):
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "")
+ req = _StubRequest(
+ peer="203.0.113.10",
+ headers={"x-forwarded-for": "evil-spoof"},
+ )
+ assert resolve_client_ip(req) == "203.0.113.10"
+
+ def test_no_client_returns_none(self, monkeypatch):
+ monkeypatch.delenv(TRUSTED_PROXIES_ENV, raising=False)
+ req = _StubRequest(peer=None, headers={"x-forwarded-for": "1.2.3.4"})
+ assert resolve_client_ip(req) is None
+
+
+class TestResolveClientIpUntrustedPeer:
+ """If the direct peer is not in the allow-list, XFF must be ignored
+ even when other proxies are configured."""
+
+ def test_untrusted_direct_peer_ignores_xff(self, monkeypatch):
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "10.0.0.0/8")
+ # Peer is on the public internet; not in 10.0.0.0/8.
+ req = _StubRequest(
+ peer="198.51.100.7",
+ headers={"x-forwarded-for": "1.1.1.1, 10.0.0.5"},
+ )
+ # Must NOT return 1.1.1.1 — that would be spoofable.
+ assert resolve_client_ip(req) == "198.51.100.7"
+
+
+class TestResolveClientIpTrustedPeer:
+ """Direct peer is a trusted proxy → consult XFF safely."""
+
+ def test_returns_rightmost_untrusted_hop(self, monkeypatch):
+ # Allow our internal LB and an internal NAT range.
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "10.0.0.0/8, 192.168.0.0/16")
+ # Chain reads left→right as "client → edge → LB":
+ # client_ip, edge_proxy, lb_proxy (peer)
+ req = _StubRequest(
+ peer="10.0.0.5",
+ headers={"x-forwarded-for": "203.0.113.10, 192.168.1.20, 10.0.0.5"},
+ )
+ # Walking right→left we skip trusted hops 10.0.0.5 and 192.168.1.20,
+ # and return 203.0.113.10 — the closest untrusted hop, i.e. the
+ # real originating client.
+ assert resolve_client_ip(req) == "203.0.113.10"
+
+ def test_no_xff_falls_back_to_peer(self, monkeypatch):
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "10.0.0.0/8")
+ req = _StubRequest(peer="10.0.0.5", headers={})
+ assert resolve_client_ip(req) == "10.0.0.5"
+
+ def test_all_hops_trusted_returns_leftmost(self, monkeypatch):
+ """All-internal forwarding chain — the leftmost hop is the
+ nearest thing to the originator we have."""
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "10.0.0.0/8")
+ req = _StubRequest(
+ peer="10.0.0.5",
+ headers={"x-forwarded-for": "10.0.1.20, 10.0.0.5"},
+ )
+ assert resolve_client_ip(req) == "10.0.1.20"
+
+ def test_garbage_hops_are_skipped(self, monkeypatch):
+ """A malformed hop must not break the walk."""
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "10.0.0.0/8")
+ req = _StubRequest(
+ peer="10.0.0.5",
+ headers={"x-forwarded-for": "not-an-ip, 203.0.113.10, 10.0.0.5"},
+ )
+ assert resolve_client_ip(req) == "203.0.113.10"
+
+ def test_ipv6_chain(self, monkeypatch):
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "2001:db8::/32")
+ req = _StubRequest(
+ peer="2001:db8::1",
+ headers={"x-forwarded-for": "2606:4700::1234, 2001:db8::abcd, 2001:db8::1"},
+ )
+ assert resolve_client_ip(req) == "2606:4700::1234"
+
+
+class TestResolveClientIpRobustness:
+ """The function must never raise — audit must keep working."""
+
+ @pytest.mark.parametrize(
+ "xff",
+ [
+ ",,,",
+ " , , ",
+ "junk, more junk",
+ "[::malformed",
+ ],
+ )
+ def test_malformed_xff_falls_back_to_peer(self, monkeypatch, xff):
+ monkeypatch.setenv(TRUSTED_PROXIES_ENV, "10.0.0.0/8")
+ req = _StubRequest(peer="10.0.0.5", headers={"x-forwarded-for": xff})
+ # Even hostile garbage must not throw.
+ assert resolve_client_ip(req) == "10.0.0.5"
+
+ def test_explicit_trusted_networks_argument_overrides_env(self, monkeypatch):
+ """Callers may pass a pre-resolved network list (used in tests / batch jobs)."""
+ # Env is empty — would normally mean "never trust XFF".
+ monkeypatch.delenv(TRUSTED_PROXIES_ENV, raising=False)
+ req = _StubRequest(
+ peer="10.0.0.5",
+ headers={"x-forwarded-for": "203.0.113.10, 10.0.0.5"},
+ )
+ nets = _parse_cidrs("10.0.0.0/8")
+ assert resolve_client_ip(req, trusted_networks=nets) == "203.0.113.10"