redaction.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Redaction applied to monitoring data before egress.
  2. One unconditional scrub, no modes, no knobs. Every string that leaves the process passes
  3. through ``redact_for_export``: secrets via ``agent/redact.py::redact_for_egress`` (the single
  4. pattern source; fails CLOSED so a broken redactor never emits the raw string), then PII
  5. (e-mail, phone, UUID-shaped ids -> ``[email]`` / ``[phone]`` / ``[id]``).
  6. """
  7. from __future__ import annotations
  8. import re
  9. from typing import Any, Optional
  10. from agent.redact import REDACTION_UNAVAILABLE as UNAVAILABLE, redact_for_egress
  11. # ── PII shapes ───────────────────────────────────────────────────────────────
  12. _EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}")
  13. # E.164-ish and common separators; conservative to avoid nuking code/IDs.
  14. _PHONE_RE = re.compile(
  15. r"(?<!\w)(?:\+?\d{1,3}[\s.\-]?)?(?:\(\d{2,4}\)[\s.\-]?)?\d{3}[\s.\-]?\d{3,4}(?:[\s.\-]?\d{2,4})?(?!\w)"
  16. )
  17. _UUID_RE = re.compile(r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b")
  18. def redact_for_export(text: Optional[str]) -> Optional[str]:
  19. """Scrub a string for egress: secrets, then PII. Unconditional."""
  20. if text is None:
  21. return None
  22. out = redact_for_egress(str(text))
  23. out = _EMAIL_RE.sub("[email]", out)
  24. out = _UUID_RE.sub("[id]", out)
  25. out = _PHONE_RE.sub("[phone]", out)
  26. return out
  27. def redact_bounded(raw: Any, *, limit: int = 500, empty: str = "[redacted]", unavailable: str = UNAVAILABLE) -> str:
  28. """Redact ``str(raw or "")`` and length-bound it; ``empty`` replaces an empty
  29. result, ``unavailable`` is returned if redaction itself raises."""
  30. try:
  31. return (redact_for_export(str(raw or "")) or empty)[:limit]
  32. except Exception:
  33. return unavailable
  34. __all__ = ["redact_bounded", "redact_for_export"]