Coverage for downtify/telemetry.py: 82%
40 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-21 22:18 +0000
1"""Structured debug/info logging helpers (JSON previews, secret redaction)."""
3from __future__ import annotations
5import json
6import re
7from typing import Any
9_SENSITIVE_SUBSTRINGS = frozenset({
10 'token',
11 'secret',
12 'password',
13 'authorization',
14 'cookie',
15})
17# Query parameters that carry a credential: a signed URL's signature, a
18# WebSocket ticket, a pairing code. Masked in logged request lines.
19_URL_SECRET = re.compile(
20 r'([?&](?:sig|ticket|code|token|password)=)[^&\s"\']+', re.I
21)
24def redact_url_secrets(text: str) -> str:
25 """*text* (a log line) with credential query values masked."""
27 return _URL_SECRET.sub(r'\1<redacted>', text)
30# Spotify embed sentry / correlation blobs — noisy and irrelevant for parsing.
31_DROP_KEYS_CASEFOLD = frozenset({
32 '_sentrytracedata',
33 '_sentrybaggage',
34 '_sentrytrace_data',
35})
38def redact_sensitive_mapping(
39 obj: Any, *, depth: int = 0, max_depth: int = 28
40) -> Any:
41 """Return a nested structure safe to log (tokens and secrets redacted)."""
43 if depth > max_depth:
44 return '<max depth>'
45 if isinstance(obj, dict):
46 out: dict[str, Any] = {}
47 for k, v in obj.items():
48 ks = str(k)
49 lk = ks.casefold()
50 if lk in _DROP_KEYS_CASEFOLD:
51 continue
52 if any(fragment in lk for fragment in _SENSITIVE_SUBSTRINGS):
53 out[ks] = '<redacted>'
54 else:
55 out[ks] = redact_sensitive_mapping(v, depth=depth + 1)
56 return out
57 if isinstance(obj, list):
58 if len(obj) > 120:
59 head = [
60 redact_sensitive_mapping(x, depth=depth + 1) for x in obj[:120]
61 ]
62 return head + [f'<{len(obj) - 120} more list items>']
63 return [redact_sensitive_mapping(x, depth=depth + 1) for x in obj]
64 return obj
67def json_log_blob(obj: Any, *, max_chars: int = 16000) -> str:
68 """Serialize for logs; truncate very large responses."""
70 try:
71 blob = json.dumps(obj, ensure_ascii=False, default=str)
72 except (TypeError, ValueError):
73 blob = repr(obj)
74 blob = _collapse_ws(blob)
75 if len(blob) > max_chars:
76 return blob[:max_chars] + (
77 f'...<truncated {len(blob) - max_chars} chars>'
78 )
79 return blob
82def _collapse_ws(text: str) -> str:
83 return re.sub(r'\s+', ' ', text).strip()