| 1 | """Auth-token header validation and exception secret scrubbing.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import re |
| 6 | from typing import Any, Iterable, Optional |
| 7 | |
| 8 | _INVALID_HEADER_RE = re.compile(r"(Invalid header value\s+).*", re.IGNORECASE | re.DOTALL) |
| 9 | _AUTH_SCHEME_VALUE_RE = re.compile(r"(?i)\b(Bearer|Basic|Token)\s+[^\s'\"\\]+") |
| 10 | _HEADER_KEY_VALUE_RE = re.compile(r"(?i)(x-api-key\s*[:=]\s*)[^\s'\"\\,;]+") |
| 11 | |
| 12 | |
| 13 | def normalize_header_token(raw: Any) -> tuple[Optional[str], Optional[str]]: |
| 14 | """Strip surrounding whitespace from a header token and reject control/non-ASCII chars. |
| 15 | |
| 16 | Returns ``(clean_token, error)``: |
| 17 | - Missing or whitespace-only input -> ``(None, None)``. |
| 18 | - Valid ASCII header token -> ``(clean_token, None)``. |
| 19 | - Malformed token (embedded CR/LF, NUL, other CTLs, or non-ASCII) -> |
| 20 | ``(None, "Invalid token format")`` without echoing the value. |
| 21 | """ |
| 22 | if raw is None or raw == "": |
| 23 | return None, None |
| 24 | if not isinstance(raw, str): |
| 25 | return None, "Invalid token format" |
| 26 | cleaned = raw.strip(" \t\r\n") |
| 27 | if not cleaned: |
| 28 | return None, None |
| 29 | if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in cleaned) or not cleaned.isascii(): |
| 30 | return None, "Invalid token format" |
| 31 | return cleaned, None |
| 32 | |
| 33 | |
| 34 | def scrub_secrets(text: str, secrets: Iterable[Any] = ()) -> str: |
| 35 | """Remove credential values and putheader ValueError header dumps from text.""" |
| 36 | if not isinstance(text, str) or not text: |
| 37 | return "" |
| 38 | scrubbed = _INVALID_HEADER_RE.sub(r"\1<redacted>", text) |
| 39 | scrubbed = _AUTH_SCHEME_VALUE_RE.sub(r"\1 <redacted>", scrubbed) |
| 40 | scrubbed = _HEADER_KEY_VALUE_RE.sub(r"\1<redacted>", scrubbed) |
| 41 | |
| 42 | candidates: set[str] = set() |
| 43 | for secret in secrets: |
| 44 | if not isinstance(secret, str) or not secret: |
| 45 | continue |
| 46 | variants = {secret, secret.strip()} |
| 47 | for piece in re.split(r"[\r\n\x00]+", secret): |
| 48 | if piece: |
| 49 | variants.add(piece) |
| 50 | variants.add(piece.strip()) |
| 51 | for variant in list(variants): |
| 52 | if not variant: |
| 53 | continue |
| 54 | escaped = repr(variant)[1:-1] |
| 55 | if len(variant) >= 4: |
| 56 | candidates.add(variant) |
| 57 | if len(escaped) >= 4: |
| 58 | candidates.add(escaped) |
| 59 | |
| 60 | for needle in sorted(candidates, key=len, reverse=True): |
| 61 | scrubbed = scrubbed.replace(needle, "<redacted>") |
| 62 | return scrubbed |
| 63 |