Redact secret-shaped fields by default, countable per field path
All checks were successful
CI Smoke / host-smoke (push) Successful in 0s
CI Smoke / container-smoke (push) Successful in 1s

AUDIT-WP-0004-T04, closing the workplan.

Decision (Bernd): default to redaction, allow rejection per sender. Losing an
audit record over one field is worse than storing it masked, but a
higher-assurance channel must be able to refuse rather than mask. secret_policy
is set per sender identity in AUDIT_CORE_SENDERS and defaults to redact.

Detection now covers the whole payload at any depth, including lists, rather
than only the top level of data. Under redaction the value is masked and the
key is preserved: dropping the key would hide that the sender transmitted the
field at all, which is exactly what an operator needs in order to stop it. The
stored record carries details.redaction with policy and affected paths, so a
reader never has to infer whether what they see is what was sent.

Idempotency is unaffected - the payload hash is taken over the original request
body, so redaction is deterministic and a resubmission still reconciles as a
duplicate.

Both outcomes are counted durably by sender, source, action and field path,
exposed at GET /v1/secret-findings. Per-path aggregation is the point: the
actionable unit is "stop emitting data.auth.token on membership.added", not
"there were 47 redactions". Counters survive restart because the fix they drive
lives in another service.

Contract doc updated to match. Tests 46 -> 50. WP-0004 is finished.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tegwick 2026-08-10 16:02:22 +02:00
parent 0ad526c2d8
commit 576caa2665
8 changed files with 441 additions and 29 deletions

View file

@ -38,11 +38,16 @@ from audit_core.interface import (
EventValidationError,
IdempotentAuditBackend,
)
from audit_core.redaction import (
POLICY_REDACT,
SecretFieldRejection,
apply_policy,
finding_from_path,
)
from audit_core.senders import SenderIdentity, SenderRegistry, development_registry
from audit_core.sqlite_backend import SQLiteAuditBackend
MAX_BODY_BYTES = 256 * 1024
_SECRET_FRAGMENTS = ("password", "secret", "token", "credential", "private_key")
log = logging.getLogger("audit_core.ingestion")
@ -99,7 +104,10 @@ class IngestionApplication:
start_response, HTTPStatus.UNAUTHORIZED, {"error": "unauthorized"}
)
if method == "GET" and (path.startswith("/v1/events") or path == "/v1/dead-letters"):
if method == "GET" and (
path.startswith("/v1/events")
or path in ("/v1/dead-letters", "/v1/secret-findings")
):
return self._read(start_response, environ, path, identity)
if path != "/v1/events" or method != "POST":
@ -109,15 +117,26 @@ class IngestionApplication:
return self._json(start_response, HTTPStatus.FORBIDDEN, {"error": "write_forbidden"})
raw = b""
payload: Any = {}
try:
raw = self._read_body(environ)
event = normalize(
json.loads(raw), environ.get("HTTP_IDEMPOTENCY_KEY"), identity
)
payload = json.loads(raw)
event = normalize(payload, environ.get("HTTP_IDEMPOTENCY_KEY"), identity)
except SecretFieldRejection as exc:
self._count_secrets(payload, identity, "rejected", exc.findings)
self._dead_letter(raw, str(exc), identity)
return self._json(start_response, HTTPStatus.BAD_REQUEST, {"error": str(exc)})
except (ValueError, TypeError, KeyError, json.JSONDecodeError) as exc:
self._dead_letter(raw, str(exc), identity)
return self._json(start_response, HTTPStatus.BAD_REQUEST, {"error": str(exc)})
redaction = event.details.get("redaction")
if redaction:
self._count_secrets(
payload, identity, "redacted",
[finding_from_path(p) for p in redaction["paths"]],
)
try:
result = self.backend.accept(event, hashlib.sha256(raw).hexdigest())
except EventConflictError as exc:
@ -156,6 +175,11 @@ class IngestionApplication:
start_response, HTTPStatus.OK,
{"dead_letters": self.backend.dead_letters(_limit(query))},
)
if path == "/v1/secret-findings":
return self._json(
start_response, HTTPStatus.OK,
{"secret_findings": self.backend.secret_findings(_limit(query))},
)
if path == "/v1/events":
correlation = (query.get("correlation_id") or [""])[0]
if not correlation:
@ -178,6 +202,28 @@ class IngestionApplication:
start_response, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "backend_unavailable"}
)
def _count_secrets(self, payload: Any, identity, outcome: str, findings) -> None:
"""Count secret-shaped fields by path, sender, source and action.
Counted so the sending service can be fixed. Aggregation is by field
path rather than by event, because the actionable unit is "stop
emitting ``data.auth.token`` on ``membership.added``", not "there were
47 redactions".
"""
counter = getattr(self.backend, "count_secret_findings", None)
if not callable(counter) or not findings:
return
source = str(payload.get("source") or "") if isinstance(payload, dict) else ""
action = str(payload.get("type") or "") if isinstance(payload, dict) else ""
try:
counter(
sender=identity.name, source=source, action=action,
outcome=outcome, findings=findings,
)
except BackendUnavailableError as exc:
# A missed counter must never change the event's outcome.
log.error("could not count secret findings: %s", exc)
def _dead_letter(self, raw: bytes, reason: str, identity) -> None:
"""Record a rejection so an operator can see what the sender dropped."""
recorder = getattr(self.backend, "record_rejection", None)
@ -268,8 +314,21 @@ def normalize(
elif source != "user-engine":
raise ValueError("source_not_allowed")
observed_at = _normalize_timestamp(payload["occurred_at"])
if _contains_secret(payload["data"]):
raise ValueError("secret_shaped_field")
policy = identity.secret_policy if identity is not None else POLICY_REDACT
# Raises SecretFieldRejection under the reject policy; that exception
# carries the findings so the caller can count them.
data, findings = apply_policy(payload, policy)
details: dict[str, Any] = {
"correlation_id": str(payload["correlation_id"]),
"data": data,
}
if findings:
# The stored record differs from what the sender transmitted. Say so in
# the record itself rather than leaving it to be inferred.
details["redaction"] = {
"policy": policy,
"paths": [f.path for f in findings],
}
return AuditEvent(
event_id=str(payload["id"]),
observed_at=observed_at,
@ -280,7 +339,7 @@ def normalize(
resource=str(payload["subject"]),
outcome="recorded",
actor=None,
details={"correlation_id": str(payload["correlation_id"]), "data": payload["data"]},
details=details,
)
@ -299,18 +358,6 @@ def _normalize_timestamp(value: Any) -> str:
return parsed.astimezone(timezone.utc).isoformat()
def _contains_secret(value: Any) -> bool:
if isinstance(value, dict):
return any(
any(fragment in str(key).lower() for fragment in _SECRET_FRAGMENTS)
or _contains_secret(item)
for key, item in value.items()
)
if isinstance(value, list):
return any(_contains_secret(item) for item in value)
return False
def _limit(query: dict[str, list[str]], default: int = 100, ceiling: int = 1000) -> int:
try:
return max(1, min(int((query.get("limit") or [default])[0]), ceiling))

127
audit_core/redaction.py Normal file
View file

@ -0,0 +1,127 @@
"""Secret-shaped field detection, redaction, and rejection.
AUDIT-WP-0004-T04. The default is to **redact and accept**: rejecting an
otherwise legitimate event loses the audit record entirely, which is a worse
outcome than storing it with one field masked. A sender that needs the
stricter posture can be switched to **reject** per identity, so a
higher-assurance channel can refuse rather than mask.
Both outcomes are counted per field path, because the goal is not to redact
efficiently it is to stop producing such fields at the source. A counter
that only says "47 redactions" tells an operator nothing actionable; one that
says ``data.credentials.password`` on ``membership.added`` from ``user-engine``
names the thing to fix.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
SECRET_FRAGMENTS = ("password", "secret", "token", "credential", "private_key")
REDACTED = "[redacted]"
POLICY_REDACT = "redact"
POLICY_REJECT = "reject"
POLICIES = (POLICY_REDACT, POLICY_REJECT)
@dataclass(frozen=True)
class Finding:
"""One secret-shaped field, located by dotted path."""
path: str
in_persisted_data: bool
class SecretFieldRejection(ValueError):
"""Raised under the reject policy. Carries the findings for counting."""
def __init__(self, findings: list[Finding]) -> None:
self.findings = findings
# The message stays the stable error code senders already key on.
super().__init__("secret_shaped_field")
def _is_secret_key(key: Any) -> bool:
lowered = str(key).lower()
return any(fragment in lowered for fragment in SECRET_FRAGMENTS)
def scan(value: Any, prefix: str = "") -> list[Finding]:
"""Locate every secret-shaped key, by dotted path.
Detection is by key name across the whole structure, including nested
dicts and lists. Values are not inspected: a value-shape heuristic on an
audit payload produces false positives on legitimate identifiers, and a
false positive here silently mangles an audit record.
"""
findings: list[Finding] = []
_walk(value, prefix, findings)
return findings
def _walk(value: Any, prefix: str, findings: list[Finding]) -> None:
if isinstance(value, dict):
for key, item in value.items():
path = f"{prefix}.{key}" if prefix else str(key)
if _is_secret_key(key):
findings.append(Finding(path=path, in_persisted_data=_persisted(path)))
continue # do not descend into a field already flagged
_walk(item, path, findings)
elif isinstance(value, list):
for index, item in enumerate(value):
_walk(item, f"{prefix}[{index}]", findings)
def _persisted(path: str) -> bool:
"""Whether this path lands in the stored record.
Only ``data`` is persisted into the event details. A secret-shaped key
elsewhere in the envelope is still reported, but it is dropped by
normalization rather than stored, so it needs no masking.
"""
return path == "data" or path.startswith("data.") or path.startswith("data[")
def redact(value: Any) -> Any:
"""Return a copy with every secret-shaped field's value masked.
Keys are preserved. Removing them would hide the fact that the sender
transmitted the field at all, which is exactly what the operator needs to
see in order to stop it.
"""
if isinstance(value, dict):
return {
key: (REDACTED if _is_secret_key(key) else redact(item))
for key, item in value.items()
}
if isinstance(value, list):
return [redact(item) for item in value]
return value
def apply_policy(payload: dict[str, Any], policy: str) -> tuple[Any, list[Finding]]:
"""Apply ``policy`` to ``payload['data']``.
Returns the data to persist and every finding across the whole payload.
Raises :class:`SecretFieldRejection` under the reject policy.
"""
findings = scan(payload)
data = payload.get("data")
if not findings:
return data, findings
if policy == POLICY_REJECT:
raise SecretFieldRejection(findings)
return redact(data), findings
def finding_from_path(path: str) -> Finding:
"""Rebuild a Finding from its path.
``in_persisted_data`` is a pure function of the path, so a finding recorded
on an event record can be reconstructed for counting without carrying the
flag through the stored details.
"""
return Finding(path=path, in_persisted_data=_persisted(path))

View file

@ -19,6 +19,8 @@ import os
from dataclasses import dataclass, field
from typing import Any, Iterable
from audit_core.redaction import POLICIES, POLICY_REDACT
WILDCARD = "*"
@ -32,10 +34,19 @@ class SenderIdentity:
tenants: frozenset[str] = field(default_factory=lambda: frozenset({WILDCARD}))
may_write: bool = True
may_read: bool = False
# Secret-shaped field handling. Defaults to redact-and-accept, so a
# legitimate event is not lost over one field; a higher-assurance channel
# can be set to reject instead (AUDIT-WP-0004-T04).
secret_policy: str = POLICY_REDACT
def __post_init__(self) -> None:
if not self.name:
raise ValueError("sender identity needs a name")
if self.secret_policy not in POLICIES:
raise ValueError(
f"sender {self.name!r}: secret_policy must be one of {POLICIES}, "
f"got {self.secret_policy!r}"
)
if not self.tokens or any(not t for t in self.tokens):
raise ValueError(f"sender {self.name!r} needs at least one non-empty token")
if not self.sources:
@ -144,6 +155,7 @@ def _identity_from(entry: Any) -> SenderIdentity:
tenants=frozenset(str(t) for t in (entry.get("tenants") or [WILDCARD])),
may_write=bool(entry.get("may_write", True)),
may_read=bool(entry.get("may_read", False)),
secret_policy=str(entry.get("secret_policy", POLICY_REDACT)),
)

View file

@ -46,6 +46,21 @@ CREATE TABLE IF NOT EXISTS dead_letters (
payload_withheld INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS dead_letters_event_idx ON dead_letters (event_id);
-- Counted per field path, not merely per event: the point is to stop senders
-- emitting secret-shaped fields, and that needs the offending path named.
CREATE TABLE IF NOT EXISTS secret_findings (
sender TEXT NOT NULL,
source TEXT NOT NULL,
action TEXT NOT NULL,
field_path TEXT NOT NULL,
outcome TEXT NOT NULL,
persisted INTEGER NOT NULL DEFAULT 0,
occurrences INTEGER NOT NULL DEFAULT 0,
first_seen TEXT NOT NULL,
last_seen TEXT NOT NULL,
PRIMARY KEY (sender, source, action, field_path, outcome)
);
"""
# Rejection reasons whose payload must never be persisted. Storing the body of
@ -238,6 +253,52 @@ class SQLiteAuditBackend:
for r in rows
]
def count_secret_findings(
self, *, sender: str, source: str, action: str, outcome: str, findings
) -> None:
"""Increment the per-path counter for each finding.
Written durably rather than held in memory: these counters exist to
drive a fix in the sending service, and that work outlives a pod
restart.
"""
now = datetime.now(timezone.utc).replace(microsecond=0).isoformat()
try:
for finding in findings:
self.db.execute(
"""
INSERT INTO secret_findings
(sender, source, action, field_path, outcome, persisted,
occurrences, first_seen, last_seen)
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?)
ON CONFLICT(sender, source, action, field_path, outcome)
DO UPDATE SET occurrences = occurrences + 1, last_seen = excluded.last_seen
""",
(
sender, source, action, finding.path, outcome,
1 if finding.in_persisted_data else 0, now, now,
),
)
except sqlite3.Error as exc:
raise BackendUnavailableError(str(exc)) from exc
def secret_findings(self, limit: int = 100) -> list[dict]:
"""Return secret-shaped field counters, most frequent first."""
rows = self._query(
"SELECT sender, source, action, field_path, outcome, persisted, "
"occurrences, first_seen, last_seen FROM secret_findings "
"ORDER BY occurrences DESC, last_seen DESC LIMIT ?",
(int(limit),),
)
return [
{
"sender": r[0], "source": r[1], "action": r[2], "field_path": r[3],
"outcome": r[4], "persisted": bool(r[5]), "occurrences": r[6],
"first_seen": r[7], "last_seen": r[8],
}
for r in rows
]
def _query(self, sql: str, params: tuple) -> list:
try:
return self.db.execute(sql, params).fetchall()