inferdiff 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
inferdiff/redact.py ADDED
@@ -0,0 +1,355 @@
1
+ """Sensitive header, URL, body, and wire-text redaction with deterministic SHA-256 fingerprints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import re
7
+ import urllib.parse
8
+ from typing import Any, Dict, Mapping, Sequence, Tuple
9
+
10
+ SENSITIVE_HEADER_NAMES = frozenset(
11
+ {
12
+ "authorization",
13
+ "api-key",
14
+ "x-api-key",
15
+ "x-openai-api-key",
16
+ "x-goog-api-key",
17
+ "x-auth-token",
18
+ "cookie",
19
+ "set-cookie",
20
+ "proxy-authorization",
21
+ }
22
+ )
23
+
24
+ _SENSITIVE_HEADER_SUBSTRINGS = (
25
+ "auth",
26
+ "api-key",
27
+ "apikey",
28
+ "token",
29
+ "secret",
30
+ "cookie",
31
+ "password",
32
+ "passwd",
33
+ "credential",
34
+ )
35
+
36
+ RECOGNIZED_AUTH_SCHEMES = frozenset(
37
+ {
38
+ "bearer",
39
+ "basic",
40
+ "digest",
41
+ "token",
42
+ "apikey",
43
+ "aws4-hmac-sha256",
44
+ "hoba",
45
+ "mutual",
46
+ "negotiate",
47
+ "oauth",
48
+ "scram-sha-1",
49
+ "scram-sha-256",
50
+ "vapid",
51
+ }
52
+ )
53
+
54
+ SAFE_EXPORT_QUERY_KEYS = frozenset(
55
+ {
56
+ "api-version",
57
+ "version",
58
+ "alt",
59
+ "stream",
60
+ }
61
+ )
62
+
63
+ _SENSITIVE_BODY_KEY_RE = re.compile(
64
+ r"(?i)(?:^|[_\-\.])("
65
+ r"api[_\-]?key|secret|password|passwd|auth|authorization|cookie|"
66
+ r"credential|credentials|bearer|private[_\-]?key|client[_\-]?secret|"
67
+ r"access[_\-]?token|refresh[_\-]?token|id[_\-]?token|session[_\-]?token|auth[_\-]?token"
68
+ r")$"
69
+ )
70
+
71
+ # Common credential / API-key value shapes scrubbed from exported text and wire excerpts.
72
+ _SECRET_VALUE_PATTERNS = (
73
+ re.compile(r"\b(?:sk|rk|pk)-(?:proj-|ant-|live-|test-)?[A-Za-z0-9_\-]{12,}\b"),
74
+ re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}\b"),
75
+ re.compile(r"\bAIza[0-9A-Za-z_\-]{20,}\b"),
76
+ re.compile(r"\bxox[baprs]-[0-9A-Za-z\-]{10,}\b"),
77
+ re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
78
+ re.compile(r"\beyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\b"),
79
+ re.compile(r"(?i)\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=\-]{8,}"),
80
+ re.compile(
81
+ r"(?i)\b(api[_\-]?key|access[_\-]?token|auth[_\-]?token|secret|password|passwd)"
82
+ r"(\s*[:=]\s*[\"']?)([^\s\"',;}{&]{4,})"
83
+ ),
84
+ )
85
+
86
+ SAFE_REPRO_PROTOCOL_KEYS = frozenset(
87
+ {
88
+ "model",
89
+ "stream",
90
+ "max_tokens",
91
+ "max_completion_tokens",
92
+ "max_output_tokens",
93
+ "max_new_tokens",
94
+ "temperature",
95
+ "top_p",
96
+ "top_k",
97
+ "seed",
98
+ "ignore_eos",
99
+ "stop",
100
+ "stop_token_ids",
101
+ "stop_regex",
102
+ "stream_options",
103
+ "sampling_params",
104
+ "options",
105
+ "extra_request_body",
106
+ "tool_choice",
107
+ "parallel_tool_calls",
108
+ "reasoning",
109
+ "think",
110
+ }
111
+ )
112
+
113
+
114
+ def fingerprint8(value: str) -> str:
115
+ """Return the first 8 hex characters of SHA-256(value) for equality checks."""
116
+ return hashlib.sha256(value.encode("utf-8", errors="surrogateescape")).hexdigest()[:8]
117
+
118
+
119
+ def is_sensitive_header(name: str) -> bool:
120
+ low = name.strip().lower()
121
+ if low in SENSITIVE_HEADER_NAMES:
122
+ return True
123
+ return any(sub in low for sub in _SENSITIVE_HEADER_SUBSTRINGS)
124
+
125
+
126
+ def redact_header_value(name: str, value: str) -> str:
127
+ """Mask sensitive header values, preserving only recognized auth scheme prefixes."""
128
+ low = name.strip().lower()
129
+ if not is_sensitive_header(low):
130
+ return value
131
+ digest = fingerprint8(value)
132
+ if low in ("authorization", "proxy-authorization"):
133
+ parts = value.strip().split(None, 1)
134
+ if len(parts) == 2 and parts[0].lower() in RECOGNIZED_AUTH_SCHEMES:
135
+ return f"{parts[0]} $REDACTED_sha256:{digest}"
136
+ return f"$REDACTED_sha256:{digest}"
137
+
138
+
139
+ def redact_headers(headers: Mapping[str, str] | Sequence[Tuple[str, str]]) -> Dict[str, str]:
140
+ """Return lowercase-keyed header dict with sensitive values redacted."""
141
+ items = headers.items() if isinstance(headers, Mapping) else headers
142
+ out: Dict[str, str] = {}
143
+ for k, v in items:
144
+ low = k.strip().lower()
145
+ if not low:
146
+ continue
147
+ out[low] = redact_header_value(low, v)
148
+ return out
149
+
150
+
151
+ def extract_header_secret_values(headers: Mapping[str, str]) -> list[str]:
152
+ """Return raw sensitive header/token values (len >= 6) so echoed secrets can be scrubbed."""
153
+ secrets_out: list[str] = []
154
+ for k, v in headers.items():
155
+ if not is_sensitive_header(k) or not isinstance(v, str):
156
+ continue
157
+ raw = v.strip()
158
+ if len(raw) >= 6:
159
+ secrets_out.append(raw)
160
+ parts = raw.split(None, 1)
161
+ if len(parts) == 2 and parts[0].lower() in RECOGNIZED_AUTH_SCHEMES and len(parts[1].strip()) >= 6:
162
+ secrets_out.append(parts[1].strip())
163
+ return sorted(set(secrets_out), key=len, reverse=True)
164
+
165
+
166
+ def scrub_known_secrets(text: str, known_secrets: Sequence[str] = ()) -> str:
167
+ """Scrub exact known outgoing secret strings plus standard secret patterns from text."""
168
+ if not text:
169
+ return text
170
+ out = text
171
+ for sec in sorted(set(s for s in known_secrets if isinstance(s, str) and len(s) >= 6), key=len, reverse=True):
172
+ if sec in out:
173
+ out = out.replace(sec, f"$REDACTED_sha256:{fingerprint8(sec)}")
174
+ return redact_secret_text(out)
175
+
176
+
177
+ def redact_secret_text(text: str) -> str:
178
+ """Scrub recognized credential patterns from free-form text or wire excerpts."""
179
+ if not text:
180
+ return text
181
+ out = text
182
+ for idx, pat in enumerate(_SECRET_VALUE_PATTERNS):
183
+ if idx == 6:
184
+ out = pat.sub(lambda m: f"{m.group(1)} $REDACTED_sha256:{fingerprint8(m.group(0))}", out)
185
+ elif idx == 7:
186
+ out = pat.sub(
187
+ lambda m: f"{m.group(1)}{m.group(2)}$REDACTED_sha256:{fingerprint8(m.group(3))}",
188
+ out,
189
+ )
190
+ else:
191
+ out = pat.sub(lambda m: f"$REDACTED_sha256:{fingerprint8(m.group(0))}", out)
192
+ return out
193
+
194
+
195
+ def has_control_chars(text: str) -> bool:
196
+ return any(ord(ch) < 32 or ord(ch) == 127 for ch in text)
197
+
198
+
199
+ def sanitize_url_for_error(url: str) -> str:
200
+ """Return scheme://host[:port]/path with credentials, query, and fragment stripped."""
201
+ if not isinstance(url, str) or not url or has_control_chars(url):
202
+ return "<invalid-url>"
203
+ try:
204
+ parsed = urllib.parse.urlsplit(url)
205
+ except ValueError:
206
+ return "<invalid-url>"
207
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
208
+ return "<invalid-url>"
209
+ host = parsed.hostname
210
+ if ":" in host and not host.startswith("["):
211
+ host = f"[{host}]"
212
+ try:
213
+ port = parsed.port
214
+ except ValueError:
215
+ return "<invalid-url>"
216
+ netloc = f"{host}:{port}" if port is not None else host
217
+ path = redact_secret_text(parsed.path or "/")
218
+ suffix = "?<redacted>" if parsed.query else ""
219
+ return f"{parsed.scheme}://{netloc}{path}{suffix}"
220
+
221
+
222
+ def sanitize_url_for_export(url: str) -> str:
223
+ """Validate HTTP(S) URL, strip userinfo/fragment, and redact non-allowlisted query params."""
224
+ if not isinstance(url, str) or not url or has_control_chars(url):
225
+ raise ValueError("Invalid or unsafe URL")
226
+ parsed = urllib.parse.urlsplit(url)
227
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
228
+ raise ValueError("URL must use http:// or https:// with a valid hostname")
229
+ host = parsed.hostname
230
+ if ":" in host and not host.startswith("["):
231
+ host = f"[{host}]"
232
+ port = parsed.port # raises ValueError if invalid
233
+ netloc = f"{host}:{port}" if port is not None else host
234
+ path = redact_secret_text(parsed.path or "/")
235
+
236
+ if parsed.query:
237
+ pairs = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
238
+ safe_pairs = []
239
+ for k, v in pairs:
240
+ if k.lower() in SAFE_EXPORT_QUERY_KEYS and not _looks_like_secret(v):
241
+ safe_pairs.append((k, v))
242
+ else:
243
+ safe_pairs.append((k, f"REDACTED_sha256:{fingerprint8(v)}"))
244
+ query = urllib.parse.urlencode(safe_pairs, safe=":")
245
+ else:
246
+ query = ""
247
+
248
+ return urllib.parse.urlunsplit((parsed.scheme, netloc, path, query, ""))
249
+
250
+
251
+ def _looks_like_secret(val: str) -> bool:
252
+ return redact_secret_text(val) != val
253
+
254
+
255
+ def _collect_sensitive_values(obj: Any, out: list[str]) -> None:
256
+ if isinstance(obj, dict):
257
+ for k, v in obj.items():
258
+ if _SENSITIVE_BODY_KEY_RE.search(str(k)) and isinstance(v, str) and len(v) >= 6:
259
+ out.append(v)
260
+ else:
261
+ _collect_sensitive_values(v, out)
262
+ elif isinstance(obj, list):
263
+ for item in obj:
264
+ _collect_sensitive_values(item, out)
265
+
266
+
267
+ def sanitize_body_for_export(obj: Any, *, key_name: str = "") -> Any:
268
+ """Recursively redact sensitive fields, known secret values, and credential-shaped strings."""
269
+ known_secrets: list[str] = []
270
+ _collect_sensitive_values(obj, known_secrets)
271
+ # Longest first to avoid partial overlap
272
+ known_secrets = sorted(set(known_secrets), key=len, reverse=True)
273
+
274
+ def _scrub_str(text: str) -> str:
275
+ s = redact_secret_text(text)
276
+ for sec in known_secrets:
277
+ if sec in s:
278
+ s = s.replace(sec, f"$REDACTED_sha256:{fingerprint8(sec)}")
279
+ return s
280
+
281
+ def _walk(node: Any) -> Any:
282
+ if isinstance(node, dict):
283
+ out: Dict[str, Any] = {}
284
+ for k, v in node.items():
285
+ k_str = str(k)
286
+ if _SENSITIVE_BODY_KEY_RE.search(k_str):
287
+ out[k_str] = f"$REDACTED_sha256:{fingerprint8(str(v))}"
288
+ else:
289
+ out[k_str] = _walk(v)
290
+ return out
291
+ if isinstance(node, list):
292
+ return [_walk(item) for item in node]
293
+ if isinstance(node, str):
294
+ return _scrub_str(node)
295
+ return node
296
+
297
+ return _walk(obj)
298
+
299
+
300
+ SAFE_SCALAR_PROTOCOL_KEYS = frozenset(
301
+ {
302
+ "model",
303
+ "stream",
304
+ "max_tokens",
305
+ "max_completion_tokens",
306
+ "max_output_tokens",
307
+ "max_new_tokens",
308
+ "temperature",
309
+ "top_p",
310
+ "top_k",
311
+ "seed",
312
+ "ignore_eos",
313
+ "parallel_tool_calls",
314
+ "think",
315
+ }
316
+ )
317
+
318
+ SAFE_NESTED_PROTOCOL_KEYS = {
319
+ "sampling_params": frozenset({"max_new_tokens", "max_tokens", "ignore_eos", "temperature", "top_p", "top_k", "seed"}),
320
+ "options": frozenset({"num_predict", "ignore_eos", "temperature", "top_p", "top_k", "seed"}),
321
+ "extra_request_body": frozenset({"max_output_tokens", "max_completion_tokens", "max_tokens", "max_new_tokens", "ignore_eos", "temperature", "seed"}),
322
+ "stream_options": frozenset({"include_usage"}),
323
+ }
324
+
325
+
326
+ def _is_safe_primitive(key: str, val: Any) -> bool:
327
+ if key == "model":
328
+ return isinstance(val, str) and len(val) <= 128 and not _looks_like_secret(val)
329
+ if key in ("stream", "ignore_eos", "parallel_tool_calls", "think", "include_usage"):
330
+ return isinstance(val, bool)
331
+ if isinstance(val, bool):
332
+ return False
333
+ return isinstance(val, (int, float))
334
+
335
+
336
+ def extract_safe_repro_body(body: Mapping[str, Any]) -> Tuple[Dict[str, Any], bool]:
337
+ """Keep ONLY strictly validated protocol primitives; flag omitted=True for any arbitrary keys/strings."""
338
+ safe: Dict[str, Any] = {}
339
+ omitted = False
340
+ for k, v in body.items():
341
+ if k in SAFE_SCALAR_PROTOCOL_KEYS and _is_safe_primitive(k, v):
342
+ safe[k] = redact_secret_text(v) if isinstance(v, str) else v
343
+ elif k in SAFE_NESTED_PROTOCOL_KEYS and isinstance(v, dict):
344
+ allowed = SAFE_NESTED_PROTOCOL_KEYS[k]
345
+ sub_safe: Dict[str, Any] = {}
346
+ for sk, sv in v.items():
347
+ if sk in allowed and _is_safe_primitive(sk, sv):
348
+ sub_safe[sk] = sv
349
+ else:
350
+ omitted = True
351
+ if sub_safe:
352
+ safe[k] = sub_safe
353
+ else:
354
+ omitted = True
355
+ return safe, omitted