返回 last30days-skill
test_pr15_social_scraping_ssrf_secrets.py
根目录 / tests / test_pr15_social_scraping_ssrf_secrets.py
1 """Security and correctness regression tests for PR 15.
2
3 Covers:
4 - HIGH-177: Randomized CSPRNG multipart boundary, collision resistance,
5 sanitized filename header, and FFmpeg metadata stripping in transcribe.py.
6 - HIGH-183: Auth token header normalization, CR/LF/NUL rejection, and secret
7 scrubbing in non-HTTPError exceptions across truthsocial, threads, pinterest,
8 linkedin, telegram, and bluesky (plus unmocked putheader ValueError checks).
9 - HIGH-184: Xiaohongshu XIAOHONGSHU_API_BASE validation (blocking file://,
10 ftp://, gopher://, cloud metadata IPs/hosts, cleartext remote HTTP, userinfo,
11 queries/fragments, and off-origin redirects while preserving local/Docker/LAN
12 self-hosted bridges and remote HTTPS bridges).
13 - HIGH-185: LinkedIn author_url / profile_url validation in parse_linkedin_response,
14 _best_author_match, search_profile, enrich_articles, and read_profile.
15 - HIGH-186: Xiaohongshu null / non-dict "data" payload handling without crashes.
16 - HIGH-189: GitHub literal .git suffix removal (not rstrip(".git")) across
17 extract_repo_refs, enrich_candidates_with_stars, apply_star_map, and refetch_datum.
18 - HIGH-190: GitHub negated search qualifiers (-is:public, -created:..., -org:...,
19 -repo:..., etc.), missing GitHub qualifier keys, wrapper smuggling, and
20 unbalanced/escaped quote sanitization.
21 """
22
23 from __future__ import annotations
24
25 import http.client as http_client
26 import io
27 import json
28 import re
29 import socket
30 import threading
31 import time
32 import urllib.error
33 import urllib.parse
34 import urllib.request
35 from dataclasses import dataclass, field
36 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
37 from pathlib import Path
38 from typing import Any
39 from unittest import mock
40
41 import pytest
42
43 from lib import (
44 auth_safety,
45 bluesky,
46 env,
47 github,
48 http,
49 linkedin,
50 pinterest,
51 public_host,
52 telegram,
53 threads,
54 transcribe,
55 truthsocial,
56 xiaohongshu_api,
57 )
58
59
60 # ---------------------------------------------------------------------------
61 # HIGH-177: transcribe.py multipart boundary & filename sanitization
62 # ---------------------------------------------------------------------------
63
64
65 class _FakeWhisperResp:
66 def __init__(self, text: str = "transcribed ok") -> None:
67 self._payload = json.dumps({"text": text}).encode("utf-8")
68
69 def __enter__(self):
70 return self
71
72 def __exit__(self, *exc):
73 return False
74
75 def read(self) -> bytes:
76 return self._payload
77
78
79 class TestHigh177TranscribeMultipartBoundary:
80 def test_boundary_is_randomized_per_request_and_not_hardcoded(self, tmp_path: Path) -> None:
81 audio = tmp_path / "audio.mp3"
82 audio.write_bytes(b"ID3\x03\x00audio-bytes")
83 captured_requests: list[urllib.request.Request] = []
84
85 def fake_open(req, timeout):
86 captured_requests.append(req)
87 return _FakeWhisperResp()
88
89 with mock.patch.object(transcribe.http, "open_request", side_effect=fake_open):
90 assert transcribe._post_audio("groq", str(audio), "dummy-groq-key", 10.0) == "transcribed ok"
91 assert transcribe._post_audio("groq", str(audio), "dummy-groq-key", 10.0) == "transcribed ok"
92
93 assert len(captured_requests) == 2
94 boundaries = []
95 for req in captured_requests:
96 ct = req.get_header("Content-type") or ""
97 m = re.match(r"^multipart/form-data; boundary=(----l30d-[0-9a-f]{32})$", ct)
98 assert m is not None, f"unexpected Content-Type: {ct!r}"
99 boundary = m.group(1)
100 assert "l30dTranscribeBoundary" not in ct
101 assert b"l30dTranscribeBoundary" not in req.data
102 assert f"--{boundary}\r\n".encode("ascii") in req.data
103 assert f"\r\n--{boundary}--\r\n".encode("ascii") in req.data
104 boundaries.append(boundary)
105 assert boundaries[0] != boundaries[1]
106
107 def test_old_static_boundary_inside_audio_cannot_inject_form_fields(self, tmp_path: Path) -> None:
108 injected_payload = (
109 b"ID3\x03\x00"
110 b"\r\n------l30dTranscribeBoundary\r\n"
111 b'Content-Disposition: form-data; name="prompt"\r\n\r\n'
112 b"INJECTED_PROMPT\r\n"
113 b"------l30dTranscribeBoundary--\r\n"
114 )
115 audio = tmp_path / "audio.mp3"
116 audio.write_bytes(injected_payload)
117 captured: list[urllib.request.Request] = []
118
119 def fake_open(req, timeout):
120 captured.append(req)
121 return _FakeWhisperResp()
122
123 with mock.patch.object(transcribe.http, "open_request", side_effect=fake_open):
124 transcribe._post_audio("openai", str(audio), "dummy-openai-key", 10.0)
125
126 req = captured[0]
127 ct = req.get_header("Content-type") or ""
128 boundary = ct.split("boundary=", 1)[1]
129 parts = req.data.split(f"--{boundary}".encode("ascii"))
130 # Expect: [b"", model_part, file_part, b"--\r\n"] -> exactly 2 form fields.
131 assert len(parts) == 4
132 assert b'name="model"' in parts[1]
133 assert b'name="file"' in parts[2]
134 assert injected_payload in parts[2]
135
136 def test_boundary_regenerates_on_collision_with_audio_bytes(self, tmp_path: Path) -> None:
137 colliding_hex = "a" * 32
138 clean_hex = "b" * 32
139 audio = tmp_path / "audio.mp3"
140 audio.write_bytes(f"prefix----l30d-{colliding_hex}suffix".encode("ascii"))
141 captured: list[urllib.request.Request] = []
142
143 def fake_open(req, timeout):
144 captured.append(req)
145 return _FakeWhisperResp()
146
147 with mock.patch.object(transcribe.secrets, "token_hex", side_effect=[colliding_hex, clean_hex]), \
148 mock.patch.object(transcribe.http, "open_request", side_effect=fake_open):
149 transcribe._post_audio("groq", str(audio), "dummy-groq-key", 10.0)
150
151 ct = captured[0].get_header("Content-type") or ""
152 assert ct == f"multipart/form-data; boundary=----l30d-{clean_hex}"
153
154 def test_boundary_collision_exhaustion_raises_cleanly(self, tmp_path: Path) -> None:
155 stuck_hex = "c" * 32
156 audio = tmp_path / "audio.mp3"
157 audio.write_bytes(f"----l30d-{stuck_hex}".encode("ascii"))
158
159 with mock.patch.object(transcribe.secrets, "token_hex", return_value=stuck_hex):
160 with pytest.raises(ValueError, match="collision-free multipart boundary"):
161 transcribe._post_audio("groq", str(audio), "dummy-groq-key", 10.0)
162
163 @pytest.mark.parametrize(
164 ("filename", "expected_header_name"),
165 [
166 ("audio.mp3", "audio.mp3"),
167 ("chunk_001.mp3", "chunk_001.mp3"),
168 ('evil"; name="prompt.mp3', "audio.mp3"),
169 ("evil\r\nInjected: 1.mp3", "audio.mp3"),
170 ("evil\nInjected: 1.mp3", "audio.mp3"),
171 ("weird name.wav", "audio.mp3"),
172 ("..hidden.mp3", "audio.mp3"),
173 ],
174 )
175 def test_filename_header_is_strictly_sanitized(
176 self, filename: str, expected_header_name: str,
177 ) -> None:
178 fake_path = f"/virtual/work/{filename}"
179 assert transcribe._safe_upload_filename(fake_path) == expected_header_name
180 captured: list[urllib.request.Request] = []
181
182 def fake_open(req, timeout):
183 captured.append(req)
184 return _FakeWhisperResp()
185
186 # Patch open() instead of touching disk so Windows-illegal characters
187 # like quotes, colons, and CR/LF stay portable across OSes.
188 with mock.patch("builtins.open", return_value=io.BytesIO(b"audio-data")), \
189 mock.patch.object(transcribe.http, "open_request", side_effect=fake_open):
190 transcribe._post_audio("groq", fake_path, "dummy-groq-key", 10.0)
191
192 expected = (
193 f'Content-Disposition: form-data; name="file"; filename="{expected_header_name}"\r\n'
194 ).encode("ascii")
195 assert expected in captured[0].data
196
197 def test_chunk_audio_and_acquire_audio_strip_ffmpeg_metadata(self, tmp_path: Path, monkeypatch) -> None:
198 monkeypatch.setattr(transcribe, "MAX_UPLOAD_BYTES", 4)
199 audio = tmp_path / "audio.mp3"
200 audio.write_bytes(b"ID3\x03\x000123456789")
201 workdir = tmp_path / "w"
202 workdir.mkdir()
203 cmds: list[list[str]] = []
204
205 def fake_run(cmd, timeout=120.0, *, env=None):
206 cmds.append(cmd)
207 if "-segment_time" in cmd:
208 (tmp_path / "chunk_000.mp3").write_bytes(b"0123")
209 else:
210 Path(cmd[-1]).write_bytes(b"mp3")
211 return True
212
213 with mock.patch.object(transcribe, "_run", side_effect=fake_run):
214 acquired = transcribe._acquire_audio(str(audio), str(workdir), timeout=10.0)
215 chunks = transcribe._chunk_audio(str(audio), str(tmp_path))
216
217 assert acquired is not None
218 assert chunks
219 assert len(cmds) == 2
220 acquire_cmd, chunk_cmd = cmds
221 assert acquire_cmd[acquire_cmd.index("-map_metadata") + 1] == "-1"
222 assert chunk_cmd[chunk_cmd.index("-map_metadata") + 1] == "-1"
223
224 def test_transcribe_post_audio_rejects_malformed_key_and_scrubs_debug_log(
225 self, tmp_path: Path, monkeypatch,
226 ) -> None:
227 audio = tmp_path / "audio.mp3"
228 audio.write_bytes(b"audio")
229 bad_key = "gsk_super_secret_987654\r\nX-Evil: 1"
230 debug_lines: list[str] = []
231 monkeypatch.setattr(transcribe.log, "debug", lambda msg: debug_lines.append(msg))
232
233 with mock.patch.object(transcribe.http, "open_request") as open_mock:
234 text, provider = transcribe._transcribe_chunk(str(audio), [("groq", bad_key)], timeout=5.0)
235
236 assert text is None
237 assert provider == ""
238 open_mock.assert_not_called()
239 combined = "\n".join(debug_lines)
240 assert "gsk_super_secret_987654" not in combined
241 assert "X-Evil" not in combined
242
243
244 # ---------------------------------------------------------------------------
245 # HIGH-183: Token stripping, control-char rejection, & secret scrubbing
246 # ---------------------------------------------------------------------------
247
248
249 class TestHigh183TokenValidationAndSecretScrubbing:
250 def test_auth_safety_normalize_and_scrub_helpers(self) -> None:
251 assert auth_safety.normalize_header_token(" tok_valid_123\r\n") == ("tok_valid_123", None)
252 assert auth_safety.normalize_header_token(" \n\t ") == (None, None)
253 assert auth_safety.normalize_header_token("") == (None, None)
254 assert auth_safety.normalize_header_token(None) == (None, None)
255
256 for bad in (
257 "tok_a\r\nX-Injected: 1",
258 "tok_a\ntok_b",
259 "tok_a\x00tail",
260 "tok_a\x0btail",
261 "tok_a\x7f",
262 "tok_non_ascii_\u2603",
263 12345,
264 ):
265 cleaned, err = auth_safety.normalize_header_token(bad)
266 assert cleaned is None
267 assert err == "Invalid token format"
268
269 # putheader ValueError embeds repr(b'Bearer <secret>\n') — verify full redaction.
270 secret = "tok_secret_value_abc123"
271 putheader_msg = f"Invalid header value b'Bearer {secret}\\r\\nX-Evil: 1'"
272 scrubbed = auth_safety.scrub_secrets(putheader_msg, (f"{secret}\r\nX-Evil: 1",))
273 assert secret not in scrubbed
274 assert "X-Evil" not in scrubbed
275 assert "<redacted>" in scrubbed
276
277 # Also redact short 2-char secrets inside putheader ValueError and Bearer strings.
278 short_err = auth_safety.scrub_secrets("Invalid header value b'Bearer xy\\n'", ("xy\n",))
279 assert "xy" not in short_err
280 assert "<redacted>" in short_err
281
282 # Preserve benign non-secret diagnostics.
283 assert auth_safety.scrub_secrets("connection refused", ("pw",)) == "connection refused"
284
285 @pytest.mark.parametrize(
286 "malformed_token",
287 [
288 "SECRET_TOK_12345\r\nX-Injected: 1",
289 "SECRET_TOK_12345\nsecond-line",
290 "SECRET_TOK_12345\x00nullbyte",
291 ],
292 )
293 def test_all_six_modules_reject_malformed_tokens_without_network_or_leak(
294 self, malformed_token: str, capsys,
295 ) -> None:
296 bluesky._reset_session_cache()
297 try:
298 with mock.patch.object(http, "request") as req_mock, \
299 mock.patch.object(http, "get") as get_mock:
300 # 1. Truth Social
301 ts_res = truthsocial.search_truthsocial(
302 "tariffs", "2026-06-01", "2026-06-30",
303 config={"TRUTHSOCIAL_TOKEN": malformed_token},
304 )
305 assert ts_res["statuses"] == []
306 assert ts_res["error"] == "Invalid token format"
307
308 # 2. Threads
309 th_res = threads.search_threads(
310 "ai agents", "2026-06-01", "2026-06-30", token=malformed_token,
311 )
312 assert th_res["items"] == []
313 assert th_res["error"] == "Invalid token format"
314
315 # 3. Pinterest
316 pi_res = pinterest.search_pinterest(
317 "ai agents", "2026-06-01", "2026-06-30", token=malformed_token,
318 )
319 assert pi_res["items"] == []
320 assert pi_res["error"] == "Invalid token format"
321
322 # 4. LinkedIn (search_linkedin, search_profile, read_profile, enrich_articles)
323 li_res = linkedin.search_linkedin(
324 "ai agents", "2026-06-01", "2026-06-30", token=malformed_token,
325 )
326 assert li_res["posts"] == []
327 assert li_res["error"] == "Invalid token format"
328 assert linkedin.search_profile("https://www.linkedin.com/in/janedoe", malformed_token) == {}
329 rp_res = linkedin.read_profile("https://www.linkedin.com/in/janedoe", malformed_token)
330 assert rp_res["status"] == "failed"
331 assert rp_res["detail"] == "Invalid token format"
332
333 # 5. Telegram (search_telegram and direct _fetch_channel_posts)
334 tg_res = telegram.search_telegram(
335 "ai agents", "2026-06-01", "2026-06-30",
336 token=malformed_token, config={"TELEGRAM_SOURCES": "aipost"},
337 )
338 assert tg_res["items"] == []
339 assert tg_res["error"] == "Invalid token format"
340 assert telegram._fetch_channel_posts(
341 "aipost", malformed_token, from_date="2026-06-01", topic="ai", max_pages=1,
342 ) == []
343
344 # 6. Bluesky (search with malformed session JWT + refresh JWT)
345 bs_refresh_tok, bs_refresh_err, _bs_refresh_status = bluesky._refresh_session(malformed_token)
346 assert bs_refresh_tok is None
347 assert "SECRET_TOK_12345" not in (bs_refresh_err or "")
348 with mock.patch.object(bluesky, "_create_session", return_value=(malformed_token, None, None)):
349 bs_res = bluesky.search_bluesky(
350 "ai agents", "2026-06-01", "2026-06-30",
351 config={"BSKY_HANDLE": "u.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"},
352 )
353 assert bs_res["posts"] == []
354 assert "Invalid token format" in bs_res["error"]
355
356 req_mock.assert_not_called()
357 get_mock.assert_not_called()
358
359 stderr = capsys.readouterr().err
360 for output in (
361 stderr,
362 ts_res["error"],
363 th_res["error"],
364 pi_res["error"],
365 li_res["error"],
366 rp_res["detail"],
367 tg_res["error"],
368 bs_res["error"],
369 ):
370 assert "SECRET_TOK_12345" not in output
371 assert "X-Injected" not in output
372 finally:
373 bluesky._reset_session_cache()
374
375 def test_trailing_newline_from_devtools_is_stripped_cleanly(self) -> None:
376 token_with_nl = " valid_devtools_secret_999\r\n"
377
378 with mock.patch.object(truthsocial.http, "request", return_value={"statuses": []}) as ts_req:
379 truthsocial.search_truthsocial("ai", "2026-06-01", "2026-06-30", config={"TRUTHSOCIAL_TOKEN": token_with_nl})
380 assert ts_req.call_args.kwargs["headers"]["Authorization"] == "Bearer valid_devtools_secret_999"
381
382 with mock.patch.object(threads.http, "get", return_value={"items": []}) as th_get:
383 threads.search_threads("ai", "2026-06-01", "2026-06-30", token=token_with_nl)
384 assert th_get.call_args.kwargs["headers"]["x-api-key"] == "valid_devtools_secret_999"
385
386 with mock.patch.object(pinterest.http, "get", return_value={"pins": []}) as pi_get:
387 pinterest.search_pinterest("ai", "2026-06-01", "2026-06-30", token=token_with_nl)
388 assert pi_get.call_args.kwargs["headers"]["x-api-key"] == "valid_devtools_secret_999"
389
390 with mock.patch.object(linkedin.http, "get", return_value={"posts": []}) as li_get:
391 linkedin.search_linkedin("ai", "2026-06-01", "2026-06-30", token=token_with_nl)
392 assert li_get.call_args.kwargs["headers"]["x-api-key"] == "valid_devtools_secret_999"
393
394 with mock.patch.object(telegram.http, "get", return_value={"success": True, "posts": []}) as tg_get:
395 telegram.search_telegram(
396 "ai", "2026-06-01", "2026-06-30",
397 token=token_with_nl, config={"TELEGRAM_SOURCES": "aipost"},
398 )
399 assert tg_get.call_args.kwargs["headers"]["x-api-key"] == "valid_devtools_secret_999"
400
401 bluesky._reset_session_cache()
402 try:
403 with mock.patch.object(
404 bluesky.http,
405 "request",
406 side_effect=[{"accessJwt": token_with_nl, "refreshJwt": "ref_ok"}, {"posts": []}],
407 ) as bs_req:
408 bluesky.search_bluesky(
409 "ai", "2026-06-01", "2026-06-30",
410 config={"BSKY_HANDLE": "u.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"},
411 )
412 assert bs_req.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer valid_devtools_secret_999"
413 finally:
414 bluesky._reset_session_cache()
415
416 def test_unredacted_putheader_valueerror_from_transport_is_scrubbed_everywhere(self, capsys) -> None:
417 """Even if a lower layer raises a ValueError containing the secret, none of the
418 six modules may leak it to stderr or the returned error dict."""
419 secret = "LIVE_SECRET_TOKEN_XYZ789"
420 leaking_exc = ValueError(f"Invalid header value b'Bearer {secret}\\n'")
421
422 bluesky._reset_session_cache()
423 try:
424 with mock.patch.object(truthsocial.http, "request", side_effect=leaking_exc):
425 ts = truthsocial.search_truthsocial("ai", "2026-06-01", "2026-06-30", config={"TRUTHSOCIAL_TOKEN": secret})
426 with mock.patch.object(threads.http, "get", side_effect=leaking_exc):
427 th = threads.search_threads("ai", "2026-06-01", "2026-06-30", token=secret)
428 with mock.patch.object(pinterest.http, "get", side_effect=leaking_exc):
429 pi = pinterest.search_pinterest("ai", "2026-06-01", "2026-06-30", token=secret)
430 with mock.patch.object(linkedin.http, "get", side_effect=leaking_exc):
431 li = linkedin.search_linkedin("ai", "2026-06-01", "2026-06-30", token=secret)
432 lip = linkedin.search_profile("https://www.linkedin.com/in/janedoe", secret)
433 with mock.patch.object(telegram.http, "get", side_effect=leaking_exc):
434 # Must catch non-HTTPError ValueError cleanly instead of crashing out of _fetch_channel_posts.
435 tg = telegram.search_telegram(
436 "ai", "2026-06-01", "2026-06-30",
437 token=secret, config={"TELEGRAM_SOURCES": "aipost"},
438 )
439 with mock.patch.object(bluesky, "_create_session", return_value=(secret, None, None)), \
440 mock.patch.object(bluesky.http, "request", side_effect=leaking_exc):
441 bs = bluesky.search_bluesky(
442 "ai", "2026-06-01", "2026-06-30",
443 config={"BSKY_HANDLE": "u.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"},
444 )
445
446 assert lip == {}
447 assert tg["items"] == []
448 assert "error" in tg
449 stderr = capsys.readouterr().err
450 for surface in (stderr, ts["error"], th["error"], pi["error"], li["error"], tg["error"], bs["error"]):
451 assert secret not in surface
452 assert "<redacted>" in surface
453 finally:
454 bluesky._reset_session_cache()
455
456 @pytest.mark.parametrize("status_code", [401, 500])
457 def test_http_request_scrubs_echoed_api_key_in_error_reason_and_body_before_recording(
458 self, status_code: int, capsys,
459 ) -> None:
460 secret = "SC_LIVE_ECHO_SECRET_987654"
461 url = "https://api.scrapecreators.com/v1/telegram/channel/posts?handle=aipost"
462
463 def fake_urlopen(req, timeout=None):
464 err_body = io.BytesIO(f'{{"error": "rejected x-api-key: {secret}"}}'.encode("utf-8"))
465 raise urllib.error.HTTPError(
466 url,
467 status_code,
468 f"Rejected key {secret}",
469 hdrs={},
470 fp=err_body,
471 )
472
473 with http.capture_failures() as failures, \
474 mock.patch("urllib.request.urlopen", side_effect=fake_urlopen), \
475 mock.patch.object(http.time, "sleep"):
476 tg = telegram.search_telegram(
477 "ai agents",
478 "2026-06-01",
479 "2026-06-30",
480 token=secret,
481 config={"TELEGRAM_SOURCES": "aipost"},
482 )
483
484 assert failures, "expected http.capture_failures to record the terminal HTTP error"
485 recorded = failures[0]
486 assert recorded.status_code == status_code
487 assert str(status_code) in str(recorded)
488 assert secret not in str(recorded)
489 assert "<redacted>" in str(recorded)
490 assert recorded.body is not None
491 assert secret not in recorded.body
492 assert "<redacted>" in recorded.body
493
494 assert tg["items"] == []
495 assert "error" in tg
496 assert str(status_code) in tg["error"]
497 assert secret not in tg["error"]
498 assert "<redacted>" in tg["error"]
499 assert secret not in capsys.readouterr().err
500
501 def test_telegram_non_http_error_sets_error_and_keeps_fetching_other_channels(self) -> None:
502 # All channels fail with a non-HTTPError (e.g. invalid UTF-8 decode).
503 decode_err = UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte")
504 with mock.patch.object(telegram.http, "get", side_effect=decode_err):
505 all_failed = telegram.search_telegram(
506 "ai agents",
507 "2026-06-01",
508 "2026-06-30",
509 token="valid-sc-key",
510 config={"TELEGRAM_SOURCES": "broken_chan"},
511 )
512 assert all_failed["items"] == []
513 assert "error" in all_failed
514 assert "UnicodeDecodeError" in all_failed["error"]
515 assert "@broken_chan" in all_failed["error"]
516
517 # First channel hits UnicodeDecodeError, second channel succeeds -> partial result.
518 def mixed_get(url, **kwargs):
519 handle = (kwargs.get("params") or {}).get("handle")
520 if handle == "broken_chan":
521 raise decode_err
522 return {
523 "success": True,
524 "channel": {"handle": "good_chan", "name": "Good", "subscriber_count": 100},
525 "posts": [{
526 "id": "1",
527 "text": "AI agents shipped",
528 "published_at": "2026-06-15T10:00:00Z",
529 "view_count": 50,
530 "reaction_count": 5,
531 }],
532 "has_more": False,
533 }
534
535 with mock.patch.object(telegram.http, "get", side_effect=mixed_get):
536 partial = telegram.search_telegram(
537 "ai agents",
538 "2026-06-01",
539 "2026-06-30",
540 token="valid-sc-key",
541 config={"TELEGRAM_SOURCES": "broken_chan,good_chan"},
542 )
543 assert len(partial["items"]) == 1
544 assert partial["items"][0]["handle"] == "good_chan"
545 assert partial.get("partial") is True
546 assert "UnicodeDecodeError" in partial.get("error", "")
547
548 def test_http_request_passes_unredacted_body_to_real_proxy_observe_error_stopping_retries(
549 self, capsys,
550 ) -> None:
551 secret = "PROXY_ECHO_SECRET_555444"
552 # "Invalid header value ..." gets truncated by auth_safety.scrub_secrets;
553 # real proxy.observe_error must still receive the raw JSON to see
554 # "code": "provider_unavailable" and stop retries on a retryable HTTP 503.
555 raw_body = json.dumps({
556 "detail": f"Invalid header value {secret}",
557 "code": "provider_unavailable",
558 })
559 attempts = 0
560
561 class _FakeRouted:
562 provider = "scrapecreators"
563 url = "https://proxy.example/v1/telegram/channel/posts"
564 headers = {"x-api-key": secret}
565
566 def fake_urlopen(req, timeout=None):
567 nonlocal attempts
568 attempts += 1
569 raise urllib.error.HTTPError(
570 _FakeRouted.url,
571 503,
572 f"Service Unavailable ({secret})",
573 hdrs={},
574 fp=io.BytesIO(raw_body.encode("utf-8")),
575 )
576
577 with http.proxy._lock:
578 http.proxy._unavailable.discard("scrapecreators")
579 try:
580 with http.capture_failures() as failures, \
581 mock.patch.object(http.proxy, "route", return_value=_FakeRouted()), \
582 mock.patch.object(http.proxy, "new_idempotency_key", return_value="k1"), \
583 mock.patch.object(http.proxy, "ensure_open"), \
584 mock.patch.object(http.proxy, "deadline_value", return_value="30"), \
585 mock.patch.object(http.time, "sleep"), \
586 mock.patch("urllib.request.urlopen", side_effect=fake_urlopen):
587 with pytest.raises(http.HTTPError) as exc_info:
588 http.get(
589 "https://api.scrapecreators.com/v1/telegram/channel/posts",
590 headers={"x-api-key": secret},
591 retries=3,
592 )
593
594 # Real proxy.observe_error saw "provider_unavailable" and stopped retries after 1 attempt,
595 # even though scrubbing truncated the JSON body after "Invalid header value ".
596 assert attempts == 1
597 assert http.proxy.provider_unavailable("scrapecreators") is True
598 # Raised HTTPError, captured failure sink, and logs remain scrubbed.
599 assert exc_info.value.status_code == 503
600 assert secret not in str(exc_info.value)
601 assert secret not in (exc_info.value.body or "")
602 assert "provider_unavailable" not in (exc_info.value.body or "")
603 assert failures and secret not in str(failures[0]) and secret not in (failures[0].body or "")
604 assert secret not in capsys.readouterr().err
605 finally:
606 with http.proxy._lock:
607 http.proxy._unavailable.discard("scrapecreators")
608
609 @pytest.mark.parametrize(
610 ("first_exc", "second_exc", "expected_channel", "expected_marker"),
611 [
612 (
613 http.HTTPError("Request timed out"),
614 http.HTTPError("HTTP 429: Too Many Requests", status_code=429),
615 "@chan_second",
616 "429",
617 ),
618 (
619 http.HTTPError("Request timed out"),
620 http.HTTPError("Too Many Requests", status_code=429),
621 "@chan_second",
622 "429",
623 ),
624 (
625 http.HTTPError("Request timed out"),
626 http.HTTPError("HTTP 401: Unauthorized", status_code=401),
627 "@chan_second",
628 "401",
629 ),
630 (
631 http.HTTPError("Request timed out"),
632 http.HTTPError("HTTP 402: Payment Required", status_code=402),
633 "@chan_second",
634 "402",
635 ),
636 # health.FAILURE_SPECIFICITY ranks AUTH_FAILED (401) ahead of PAYMENT_REQUIRED (402).
637 (
638 http.HTTPError("HTTP 402: Payment Required", status_code=402),
639 http.HTTPError("HTTP 401: Unauthorized", status_code=401),
640 "@chan_second",
641 "401",
642 ),
643 ],
644 )
645 def test_telegram_prioritizes_failures_by_health_specificity(
646 self,
647 first_exc: http.HTTPError,
648 second_exc: http.HTTPError,
649 expected_channel: str,
650 expected_marker: str,
651 ) -> None:
652 def fake_get(url, **kwargs):
653 handle = (kwargs.get("params") or {}).get("handle")
654 if handle == "chan_first":
655 raise first_exc
656 raise second_exc
657
658 with mock.patch.object(telegram.http, "get", side_effect=fake_get):
659 res = telegram.search_telegram(
660 "ai agents",
661 "2026-06-01",
662 "2026-06-30",
663 token="valid-sc-key",
664 config={"TELEGRAM_SOURCES": "chan_first,chan_second"},
665 )
666
667 assert res["items"] == []
668 assert expected_channel in res["error"]
669 assert expected_marker in res["error"]
670
671 def test_real_http_client_putheader_error_shape_is_scrubbed(self) -> None:
672 """Exercise Python's real http.client.HTTPConnection.putheader ValueError."""
673 conn = http_client.HTTPConnection("example.invalid")
674 conn.putrequest("GET", "/")
675 secret = "REAL_PUTHEADER_SECRET_999"
676 with pytest.raises(ValueError) as exc_info:
677 conn.putheader("Authorization", f"Bearer {secret}\n")
678 assert secret in str(exc_info.value) # Confirm stdlib leaks it raw.
679 scrubbed = auth_safety.scrub_secrets(str(exc_info.value), (f"{secret}\n",))
680 assert secret not in scrubbed
681 assert "<redacted>" in scrubbed
682
683
684 # ---------------------------------------------------------------------------
685 # HIGH-184 & HIGH-186: xiaohongshu_api.py SSRF / base URL & null-data crashes
686 # ---------------------------------------------------------------------------
687
688
689 class TestHigh184XiaohongshuBaseUrlValidation:
690 @pytest.mark.parametrize(
691 "bad_base",
692 [
693 "",
694 " ",
695 None,
696 "file:///etc/passwd",
697 "file://localhost/etc/passwd",
698 "ftp://localhost:21/xhs",
699 "gopher://127.0.0.1:6379/_INFO",
700 "data:application/json,{}",
701 "javascript:alert(1)",
702 "http://169.254.169.254",
703 "https://169.254.169.254",
704 "http://169.254.170.2",
705 "http://2852039166",
706 "http://0xa9fea9fe",
707 "http://0251.0376.0251.0376",
708 "http://[::ffff:169.254.169.254]:80",
709 "http://[64:ff9b::169.254.169.254]",
710 "http://[fe80::1]:18060",
711 "http://[fd00:ec2::254]",
712 "http://100.100.100.200",
713 "http://0.0.0.0:18060",
714 "http://[::]:18060",
715 "http://224.0.0.1:18060",
716 "http://metadata.google.internal",
717 "https://metadata.google.internal",
718 "http://metadata",
719 "http://instance-data",
720 "http://evil.example:18060",
721 "http://8.8.8.8:18060",
722 "http://localhost:18060?foo=bar",
723 "http://localhost:18060#frag",
724 "http://user:pass@localhost:18060",
725 "http://localhost@evil.example:18060",
726 "http://localhost:18060/api/../etc",
727 "http://localhost:18060/%2e%2e/etc",
728 "http://localhost\\@evil.example:18060",
729 "http://localhost:18060\r\nX-Injected: 1",
730 "http://localhost:99999",
731 "/relative/path",
732 ],
733 )
734 def test_disallowed_base_urls_rejected_before_network(self, bad_base: Any) -> None:
735 with mock.patch.object(xiaohongshu_api.http, "get") as get_mock, \
736 mock.patch.object(xiaohongshu_api.http, "post") as post_mock:
737 with pytest.raises(ValueError):
738 xiaohongshu_api.search_feeds("matcha", "2026-06-01", "2026-07-01", bad_base)
739 get_mock.assert_not_called()
740 post_mock.assert_not_called()
741
742 @pytest.mark.parametrize(
743 ("good_base", "expected_local", "expected_normalized"),
744 [
745 ("http://localhost:18060/", True, "http://localhost:18060"),
746 ("http://127.0.0.1:18060", True, "http://127.0.0.1:18060"),
747 ("http://[::1]:18060/", True, "http://[::1]:18060"),
748 ("http://host.docker.internal:18060", True, "http://host.docker.internal:18060"),
749 ("http://custom.local:18060/", True, "http://custom.local:18060"),
750 ("http://192.168.1.50:18060", True, "http://192.168.1.50:18060"),
751 ("http://10.0.0.12:18060", True, "http://10.0.0.12:18060"),
752 ("http://xhs-mcp:18060", True, "http://xhs-mcp:18060"),
753 ("https://xhs.example.com/bridge/", False, "https://xhs.example.com/bridge"),
754 ],
755 )
756 def test_legitimate_local_and_https_bridges_allowed_with_correct_guards(
757 self, good_base: str, expected_local: bool, expected_normalized: str,
758 ) -> None:
759 normalized, is_local = xiaohongshu_api._validate_base_url(good_base)
760 assert normalized == expected_normalized
761 assert is_local is expected_local
762
763 with mock.patch.object(xiaohongshu_api.http, "get", return_value={"data": {"is_logged_in": True}}) as get_mock, \
764 mock.patch.object(xiaohongshu_api.http, "post", return_value={"data": {"feeds": []}}) as post_mock:
765 items = xiaohongshu_api.search_feeds("matcha", "2026-06-01", "2026-07-01", good_base)
766
767 assert items == []
768 for m in (get_mock, post_mock):
769 guard = m.call_args.kwargs.get("redirect_guard")
770 assert callable(guard)
771 assert guard(f"{expected_normalized}/api/v1/login/status") is True
772 assert guard("http://169.254.169.254/latest/meta-data/") is False
773 assert guard("file:///etc/passwd") is False
774 assert guard("https://evil.example/steal") is False
775 if expected_local:
776 assert m.call_args.kwargs.get("local_bridge_only") is True
777 assert "public_only" not in m.call_args.kwargs
778 else:
779 assert m.call_args.kwargs.get("public_only") is True
780 assert "local_bridge_only" not in m.call_args.kwargs
781
782 def test_redirect_to_other_origin_is_blocked_unmocked(self) -> None:
783 secret_hits: list[str] = []
784
785 class SecretHandler(BaseHTTPRequestHandler):
786 def log_message(self, *args):
787 pass
788
789 def do_GET(self):
790 secret_hits.append(self.path)
791 body = b'{"data":{"is_logged_in":true}}'
792 self.send_response(200)
793 self.send_header("Content-Length", str(len(body)))
794 self.end_headers()
795 self.wfile.write(body)
796
797 secret_srv = ThreadingHTTPServer(("127.0.0.1", 0), SecretHandler)
798 secret_thread = threading.Thread(target=secret_srv.serve_forever, daemon=True)
799 secret_thread.start()
800
801 class RedirectHandler(BaseHTTPRequestHandler):
802 def log_message(self, *args):
803 pass
804
805 def do_GET(self):
806 self.send_response(302)
807 self.send_header("Location", f"http://127.0.0.1:{secret_srv.server_port}/api/v1/login/status")
808 self.send_header("Content-Length", "0")
809 self.end_headers()
810
811 front_srv = ThreadingHTTPServer(("127.0.0.1", 0), RedirectHandler)
812 front_thread = threading.Thread(target=front_srv.serve_forever, daemon=True)
813 front_thread.start()
814 try:
815 with pytest.raises(http.HTTPError) as exc_info:
816 xiaohongshu_api.search_feeds(
817 "matcha", "2026-06-01", "2026-07-01",
818 f"http://127.0.0.1:{front_srv.server_port}",
819 )
820 assert exc_info.value.status_code == 403
821 assert secret_hits == []
822 finally:
823 front_srv.shutdown()
824 front_srv.server_close()
825 front_thread.join(2)
826 secret_srv.shutdown()
827 secret_srv.server_close()
828 secret_thread.join(2)
829
830 def test_remote_https_bridge_blocks_private_dns_rebinding(self, monkeypatch) -> None:
831 def private_dns(host, port, *_args, **_kwargs):
832 return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("169.254.169.254", port))]
833
834 monkeypatch.setattr(public_host.socket, "getaddrinfo", private_dns)
835 with pytest.raises(http.HTTPError):
836 xiaohongshu_api.search_feeds(
837 "matcha", "2026-06-01", "2026-07-01", "https://rebind.example.com",
838 )
839
840 @pytest.mark.parametrize(
841 "rebound_ips",
842 [
843 ["169.254.169.254"],
844 ["100.100.100.200"],
845 ["fd00:ec2::254"],
846 ["0.0.0.0"],
847 ["93.184.216.34"],
848 ["192.168.1.50", "169.254.169.254"],
849 ["127.0.0.1", "93.184.216.34"],
850 ],
851 )
852 @pytest.mark.parametrize("bridge_base", ["http://custom.local:18060", "http://xhs-mcp:18060"])
853 def test_local_bridge_blocks_connect_time_dns_rebinding_to_disallowed_ips(
854 self, monkeypatch, bridge_base: str, rebound_ips: list[str],
855 ) -> None:
856 def fake_getaddrinfo(host, port, *_args, **_kwargs):
857 out = []
858 for ip in rebound_ips:
859 af = socket.AF_INET6 if ":" in ip else socket.AF_INET
860 sockaddr = (ip, port, 0, 0) if af == socket.AF_INET6 else (ip, port)
861 out.append((af, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr))
862 return out
863
864 monkeypatch.setattr(http.socket, "getaddrinfo", fake_getaddrinfo)
865 with pytest.raises(http.HTTPError):
866 xiaohongshu_api.search_feeds("matcha", "2026-06-01", "2026-07-01", bridge_base)
867 # env.is_xiaohongshu_available must also fail closed on the exact same DNS rebinding.
868 cfg = {"XIAOHONGSHU_API_BASE": bridge_base}
869 assert env.is_xiaohongshu_available(cfg) is False
870 assert env.XIAOHONGSHU_RESOLVED_API_BASE_KEY not in cfg
871
872 @pytest.mark.parametrize(
873 "allowed_ip",
874 ["127.0.0.1", "::1", "10.0.0.5", "172.16.4.2", "192.168.1.50", "fd12:3456:789a::1"],
875 )
876 def test_local_bridge_resolver_accepts_loopback_rfc1918_and_ula(
877 self, monkeypatch, allowed_ip: str,
878 ) -> None:
879 af = socket.AF_INET6 if ":" in allowed_ip else socket.AF_INET
880 sockaddr = (allowed_ip, 18060, 0, 0) if af == socket.AF_INET6 else (allowed_ip, 18060)
881 monkeypatch.setattr(
882 http.socket,
883 "getaddrinfo",
884 lambda host, port, *a, **kw: [(af, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", sockaddr)],
885 )
886 verified = http._resolve_local_bridge_addresses("custom.local", 18060)
887 assert len(verified) == 1
888 assert verified[0][4][0] == allowed_ip
889
890 def test_local_bridge_resolver_preserves_trailing_dot_for_dns_lookup(self, monkeypatch) -> None:
891 seen_hosts: list[str] = []
892
893 def fake_getaddrinfo(host, port, *a, **kw):
894 seen_hosts.append(host)
895 return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("192.168.1.50", port))]
896
897 monkeypatch.setattr(http.socket, "getaddrinfo", fake_getaddrinfo)
898 verified = http._resolve_local_bridge_addresses("bridge.local.", 18060)
899 assert seen_hosts == ["bridge.local."]
900 assert verified[0][4] == ("192.168.1.50", 18060)
901
902 with pytest.raises(public_host.NonPublicAddressError):
903 http._resolve_local_bridge_addresses("bridge.local..", 18060)
904
905 def test_http_request_rejects_mutually_exclusive_pinning_flags(self) -> None:
906 with pytest.raises(ValueError, match="mutually exclusive"):
907 http.request("GET", "https://example.com", public_only=True, local_bridge_only=True)
908
909 @pytest.mark.parametrize(
910 "bad_base",
911 [
912 "file:///etc/passwd",
913 "ftp://localhost:21/xhs",
914 "http://169.254.169.254",
915 "http://metadata.google.internal",
916 "http://evil.example:18060",
917 "http://localhost:18060?x=1",
918 "http://localhost:18060#frag",
919 "http://user:pass@localhost:18060",
920 "http://localhost..:18060",
921 ],
922 )
923 def test_env_is_xiaohongshu_available_blocks_unsafe_base_urls_before_network(
924 self, bad_base: str,
925 ) -> None:
926 with mock.patch.object(http, "get") as get_mock:
927 cfg = {"XIAOHONGSHU_API_BASE": bad_base}
928 assert env.is_xiaohongshu_available(cfg) is False
929 assert env._xiaohongshu_base_logged_in(bad_base, http) is False
930 get_mock.assert_not_called()
931 assert env.XIAOHONGSHU_RESOLVED_API_BASE_KEY not in cfg
932
933 def test_env_is_xiaohongshu_available_passes_pinning_and_caches_normalized_base(self) -> None:
934 seen_kwargs: list[dict[str, Any]] = []
935
936 def fake_get(url, **kwargs):
937 seen_kwargs.append(kwargs)
938 if url.endswith("/health"):
939 return {"success": True}
940 if url.endswith("/api/v1/login/status"):
941 return {"data": {"is_logged_in": True}}
942 raise AssertionError(f"unexpected URL: {url}")
943
944 with mock.patch.object(http, "get", side_effect=fake_get):
945 cfg_local = {"XIAOHONGSHU_API_BASE": " HTTP://custom.local:18060/ "}
946 assert env.is_xiaohongshu_available(cfg_local) is True
947 assert cfg_local[env.XIAOHONGSHU_RESOLVED_API_BASE_KEY] == "http://custom.local:18060"
948
949 cfg_remote = {"XIAOHONGSHU_API_BASE": "https://xhs.example.com/bridge/"}
950 assert env.is_xiaohongshu_available(cfg_remote) is True
951 assert cfg_remote[env.XIAOHONGSHU_RESOLVED_API_BASE_KEY] == "https://xhs.example.com/bridge"
952
953 assert len(seen_kwargs) == 4
954 for kw in seen_kwargs[:2]:
955 assert kw.get("local_bridge_only") is True
956 assert callable(kw.get("redirect_guard"))
957 assert "public_only" not in kw
958 for kw in seen_kwargs[2:]:
959 assert kw.get("public_only") is True
960 assert callable(kw.get("redirect_guard"))
961 assert "local_bridge_only" not in kw
962
963 def test_env_is_xiaohongshu_available_blocks_cross_origin_redirect_unmocked(self) -> None:
964 secret_hits: list[str] = []
965
966 class SecretHandler(BaseHTTPRequestHandler):
967 def log_message(self, *args):
968 pass
969
970 def do_GET(self):
971 secret_hits.append(self.path)
972 body = b'{"success":true,"data":{"is_logged_in":true}}'
973 self.send_response(200)
974 self.send_header("Content-Length", str(len(body)))
975 self.end_headers()
976 self.wfile.write(body)
977
978 secret_srv = ThreadingHTTPServer(("127.0.0.1", 0), SecretHandler)
979 secret_thread = threading.Thread(target=secret_srv.serve_forever, daemon=True)
980 secret_thread.start()
981
982 class RedirectHandler(BaseHTTPRequestHandler):
983 def log_message(self, *args):
984 pass
985
986 def do_GET(self):
987 self.send_response(302)
988 self.send_header("Location", f"http://127.0.0.1:{secret_srv.server_port}{self.path}")
989 self.send_header("Content-Length", "0")
990 self.end_headers()
991
992 front_srv = ThreadingHTTPServer(("127.0.0.1", 0), RedirectHandler)
993 front_thread = threading.Thread(target=front_srv.serve_forever, daemon=True)
994 front_thread.start()
995 try:
996 cfg = {"XIAOHONGSHU_API_BASE": f"http://127.0.0.1:{front_srv.server_port}"}
997 assert env.is_xiaohongshu_available(cfg) is False
998 assert secret_hits == []
999 finally:
1000 front_srv.shutdown()
1001 front_srv.server_close()
1002 front_thread.join(2)
1003 secret_srv.shutdown()
1004 secret_srv.server_close()
1005 secret_thread.join(2)
1006
1007 @pytest.mark.parametrize(
1008 "login_payload",
1009 [
1010 {"code": -1, "data": None},
1011 {"code": -1, "data": []},
1012 {"code": -1, "data": "err"},
1013 None,
1014 ],
1015 )
1016 def test_env_xiaohongshu_probe_handles_null_or_non_dict_data_without_crashing(
1017 self, login_payload: Any,
1018 ) -> None:
1019 def fake_get(url, **kwargs):
1020 if url.endswith("/health"):
1021 return {"success": True}
1022 return login_payload
1023
1024 with mock.patch.object(http, "get", side_effect=fake_get):
1025 assert env._xiaohongshu_base_logged_in("http://localhost:18060", http) is False
1026 assert env.is_xiaohongshu_available({"XIAOHONGSHU_API_BASE": "http://localhost:18060"}) is False
1027
1028
1029 class TestHigh186XiaohongshuNullDataPayloads:
1030 @pytest.mark.parametrize(
1031 "login_payload",
1032 [
1033 {"code": -1, "data": None},
1034 {"code": -1, "data": []},
1035 {"code": -1, "data": "not-a-dict"},
1036 {"code": -1, "data": 123},
1037 None,
1038 [],
1039 ],
1040 )
1041 def test_login_null_or_non_dict_data_raises_http_error_not_attribute_error(
1042 self, login_payload: Any,
1043 ) -> None:
1044 with mock.patch.object(xiaohongshu_api.http, "get", return_value=login_payload):
1045 with pytest.raises(http.HTTPError, match="not logged in"):
1046 xiaohongshu_api.search_feeds(
1047 "matcha", "2026-06-01", "2026-07-01", "http://localhost:18060",
1048 )
1049
1050 @pytest.mark.parametrize(
1051 "search_payload",
1052 [
1053 {"code": -1, "data": None},
1054 {"code": -1, "data": []},
1055 {"code": -1, "data": "err"},
1056 {"data": {"feeds": None}},
1057 {"data": {"feeds": "not-a-list"}},
1058 None,
1059 [],
1060 ],
1061 )
1062 def test_search_null_or_non_dict_data_returns_empty_list_without_crashing(
1063 self, search_payload: Any,
1064 ) -> None:
1065 with mock.patch.object(xiaohongshu_api.http, "get", return_value={"data": {"is_logged_in": True}}), \
1066 mock.patch.object(xiaohongshu_api.http, "post", return_value=search_payload):
1067 items = xiaohongshu_api.search_feeds(
1068 "matcha", "2026-06-01", "2026-07-01", "http://localhost:18060",
1069 )
1070 assert items == []
1071
1072
1073 # ---------------------------------------------------------------------------
1074 # HIGH-185: linkedin.py author_url / profile_url SSRF & paid-API abuse defense
1075 # ---------------------------------------------------------------------------
1076
1077
1078 class TestHigh185LinkedInAuthorUrlValidation:
1079 @pytest.mark.parametrize(
1080 "bad_url",
1081 [
1082 "",
1083 " ",
1084 None,
1085 "http://www.linkedin.com/in/janedoe",
1086 "http://169.254.169.254/latest/meta-data/",
1087 "https://169.254.169.254/in/janedoe",
1088 "file:///in/etc/passwd",
1089 "https://evil.example/in/janedoe",
1090 "https://evil-linkedin.com/in/janedoe",
1091 "https://linkedin.com.evil.com/in/janedoe",
1092 "https://www.linkedin.com/company/new-york-times",
1093 "https://www.linkedin.com/posts/janedoe_123",
1094 "https://www.linkedin.com/in/",
1095 "https://www.linkedin.com/in///",
1096 "https://www.linkedin.com/in/.",
1097 "https://www.linkedin.com/in/./",
1098 "https://www.linkedin.com/in/%2e",
1099 "https://www.linkedin.com/in/janedoe/details/",
1100 "https://www.linkedin.com/in/janedoe/recent-activity/all/",
1101 "https://www.linkedin.com/in/janedoe//",
1102 "https://www.linkedin.com/in/janedoe%2fdetails",
1103 "https://www.linkedin.com/in/janedoe%5cdetails",
1104 "https://www.linkedin.com/in/../company/acme",
1105 "https://www.linkedin.com/in/%2e%2e/company/acme",
1106 "https://www.linkedin.com../in/janedoe",
1107 "https://user:pass@www.linkedin.com/in/janedoe",
1108 "https://evil.com\\@www.linkedin.com/in/janedoe",
1109 "https://www.linkedin.com:8443/in/janedoe",
1110 "https://.linkedin.com/in/janedoe",
1111 "https://a..linkedin.com/in/janedoe",
1112 "https://www.linkedin.com/in/janedoe\r\nX-Evil: 1",
1113 ],
1114 )
1115 def test_disallowed_profile_urls_rejected_across_all_boundaries(self, bad_url: Any) -> None:
1116 assert linkedin._is_valid_linkedin_profile_url(bad_url) is False
1117
1118 with mock.patch.object(linkedin.http, "get") as get_mock, \
1119 mock.patch.object(linkedin.http, "request") as req_mock:
1120 # 1. parse_linkedin_response clears untrusted author_url
1121 parsed = linkedin.parse_linkedin_response({
1122 "posts": [{
1123 "description": "hello world",
1124 "author": {"name": "New York Times", "url": bad_url},
1125 }],
1126 })
1127 assert parsed[0]["author_url"] == ""
1128
1129 # 2. _best_author_match skips untrusted author_url even if passed directly
1130 assert linkedin._best_author_match(
1131 [{"author": "New York Times", "author_url": bad_url}], "New York",
1132 ) == ""
1133
1134 # 3. search_profile refuses without network call
1135 assert linkedin.search_profile(bad_url, "valid-token") == {}
1136
1137 # 4. read_profile refuses without network call
1138 rp = linkedin.read_profile(bad_url, "valid-token")
1139 assert rp["status"] == "failed"
1140 assert rp["data"] is None
1141
1142 get_mock.assert_not_called()
1143 req_mock.assert_not_called()
1144
1145 @pytest.mark.parametrize(
1146 "good_url",
1147 [
1148 "https://www.linkedin.com/in/janedoe",
1149 "https://linkedin.com/in/janedoe/",
1150 "https://uk.linkedin.com/in/jane-doe-123",
1151 "https://www.linkedin.com:443/in/janedoe",
1152 "https://www.linkedin.com/in/janedoe?trk=public_post",
1153 ],
1154 )
1155 def test_valid_linkedin_profile_urls_accepted(self, good_url: str) -> None:
1156 assert linkedin._is_valid_linkedin_profile_url(good_url) is True
1157
1158 def test_company_author_skipped_in_favor_of_person_profile(self) -> None:
1159 items = [
1160 {
1161 "author": "New York Times",
1162 "author_url": "https://www.linkedin.com/company/the-new-york-times",
1163 },
1164 {
1165 "author": "Jane Doe",
1166 "author_url": "https://evil.example/in/janedoe",
1167 },
1168 {
1169 "author": "Jane Doe",
1170 "author_url": "https://www.linkedin.com/in/janedoe",
1171 },
1172 ]
1173 assert linkedin._best_author_match(items, "New York") == ""
1174 assert linkedin._best_author_match(items, "Jane Doe") == "https://www.linkedin.com/in/janedoe"
1175
1176
1177 # ---------------------------------------------------------------------------
1178 # HIGH-189: github.py .removesuffix(".git") / _normalize_repo_slug
1179 # ---------------------------------------------------------------------------
1180
1181
1182 @dataclass
1183 class _StubCandidate:
1184 url: str = ""
1185 title: str = ""
1186 evidence: str = ""
1187 metadata: dict[str, Any] = field(default_factory=dict)
1188
1189
1190 class TestHigh189GitHubRepoSlugNormalization:
1191 @pytest.mark.parametrize(
1192 ("url", "expected_slug"),
1193 [
1194 ("https://github.com/facebook/react", "facebook/react"),
1195 ("https://github.com/rust-lang/rust", "rust-lang/rust"),
1196 ("https://github.com/tiangolo/fastapi", "tiangolo/fastapi"),
1197 ("https://github.com/vercel/ai", "vercel/ai"),
1198 ("https://github.com/microsoft/TypeScript", "microsoft/TypeScript"),
1199 ("https://github.com/git/git", "git/git"),
1200 ("https://github.com/foo/bar.git", "foo/bar"),
1201 ("https://github.com/facebook/react.git", "facebook/react"),
1202 ("https://github.com/foo/bar.GIT", "foo/bar"),
1203 ("https://github.com/facebook/react.", "facebook/react"),
1204 ("https://github.com/foo/bar.git.", "foo/bar"),
1205 ("https://github.com/vercel/next.js", "vercel/next.js"),
1206 ],
1207 )
1208 def test_extract_and_apply_star_map_preserve_trailing_g_i_t_and_strip_git_suffix(
1209 self, url: str, expected_slug: str,
1210 ) -> None:
1211 cand = _StubCandidate(url=url, title="check repo", evidence="repo ref")
1212 refs = github.extract_repo_refs([cand])
1213 assert refs == [expected_slug]
1214
1215 fetched: list[str] = []
1216
1217 def fake_info(repo: str, token: str):
1218 fetched.append(repo)
1219 return {"stars": 4200, "forks": 10, "description": "", "language": "", "open_issues": 1}
1220
1221 with mock.patch.object(github, "_resolve_token", return_value="tok"), \
1222 mock.patch.object(github, "_fetch_repo_info", side_effect=fake_info):
1223 annotated = github.enrich_candidates_with_stars([cand])
1224
1225 assert fetched == [expected_slug]
1226 assert annotated == 1
1227 assert cand.metadata["github_stars"] == {expected_slug: 4200}
1228 assert "(live: 4.2K stars)" in cand.evidence
1229
1230 def test_distinct_repos_differing_by_t_do_not_collide_and_dot_git_dedupes(self) -> None:
1231 cands = [
1232 _StubCandidate(url="https://github.com/foo/react"),
1233 _StubCandidate(url="https://github.com/foo/reac"),
1234 _StubCandidate(url="https://github.com/foo/react.git"),
1235 _StubCandidate(url="https://github.com/foo/.git"),
1236 ]
1237 assert github.extract_repo_refs(cands) == ["foo/react", "foo/reac"]
1238
1239 def test_refetch_datum_strips_case_insensitive_git_suffix(self) -> None:
1240 item = github.schema.SourceItem(
1241 item_id="GH1",
1242 source="github",
1243 title="t",
1244 body="",
1245 url="https://github.com/facebook/react.GIT",
1246 )
1247 seen_urls: list[str] = []
1248
1249 def fake_req(method, url, **kwargs):
1250 seen_urls.append(url)
1251 return {"visibility": "public", "private": False, "stargazers_count": 200000}
1252
1253 with mock.patch.object(github, "_resolve_token", return_value="tok"), \
1254 mock.patch.object(github.http, "request", side_effect=fake_req):
1255 out = github.refetch_datum(item, "stars")
1256
1257 assert seen_urls == ["https://api.github.com/repos/facebook/react"]
1258 assert out["value"] == 200000
1259
1260
1261 # ---------------------------------------------------------------------------
1262 # HIGH-190: GitHub negated qualifiers, missing keys, & unbalanced quotes
1263 # ---------------------------------------------------------------------------
1264
1265
1266 class TestHigh190GitHubQualifierSanitization:
1267 @pytest.mark.parametrize(
1268 ("raw_topic", "expected"),
1269 [
1270 ("auth -is:public", "auth"),
1271 ("react -created:>2020-01-01", "react"),
1272 ("foo -is:issue", "foo"),
1273 ("foo -is:pull-request", "foo"),
1274 ("(-is:public) auth", "auth"),
1275 ('"-is:public" auth', "auth"),
1276 ("'-is:public' auth", "auth"),
1277 ("[-is:public] auth", "auth"),
1278 ("auth,-is:public", "auth,"),
1279 ("auth --is:public", "auth"),
1280 ("auth -org:secret-org -repo:secret/repo", "auth"),
1281 ('auth -org:"secret org" -label:"bug fix"', "auth"),
1282 ("auth visibility:private -visibility:public", "auth"),
1283 ("auth draft:true status:pending reason:completed", "auth"),
1284 ("auth parent-issue:12 sub-issue:34 category:general answered:true", "auth"),
1285 ("auth sha:deadbeef owner:acme", "auth"),
1286 # Wrapper-boundary bypasses: closing paren/bracket before qualifier.
1287 ("(auth)-is:public", "(auth)"),
1288 ("(auth)is:private", "(auth)"),
1289 ("[auth]-is:public", "[auth]"),
1290 ("[auth]org:secret", "[auth]"),
1291 # Parenthesized qualifier values.
1292 ("auth -is:(public)", "auth"),
1293 ("auth is:(private)", "auth"),
1294 ("auth label:(bug OR feat)", "auth"),
1295 ("auth -org:(acme OR corp)", "auth"),
1296 ("auth -is:(public", "auth"),
1297 ("(auth)-is:(public)", "(auth)"),
1298 # Negated wrapped qualifiers leave no stray '-'.
1299 ('auth -"is:public"', "auth"),
1300 ("auth -(is:public)", "auth"),
1301 ("auth -[-is:public]", "auth"),
1302 # Wrapper-smuggling attempts where empty wrappers split qualifier tokens.
1303 ("auth is:()private", "auth"),
1304 ("auth -is:()public", "auth"),
1305 ("auth -()is:public", "auth"),
1306 ("auth is:[]private", "auth"),
1307 ('auth is:""private', "auth"),
1308 # Adjacent quoted phrases remain distinct (never merged).
1309 ('"foo" "bar" -is:public', '"foo" "bar"'),
1310 # Qualifier-only negated inputs collapse to empty string.
1311 ("-is:public", ""),
1312 ("(-is:public)", ""),
1313 ("-(is:public)", ""),
1314 ('"-is:public"', ""),
1315 # Unbalanced and backslash-escaped quotes cannot swallow engine qualifiers.
1316 ('say "hello world', "say hello world"),
1317 ('say "hello\\" world', 'say "hello" world'),
1318 ('say "hello\\"', 'say "hello"'),
1319 ('"exact phrase" and "unclosed', '"exact phrase" and unclosed'),
1320 ('auth "-is:public', "auth"),
1321 ('"', ""),
1322 ('"""', ""),
1323 ],
1324 )
1325 def test_strip_search_qualifiers_blocks_negation_smuggling_and_unbalanced_quotes(
1326 self, raw_topic: str, expected: str,
1327 ) -> None:
1328 assert github.strip_search_qualifiers(raw_topic) == expected
1329
1330 def test_strip_search_qualifiers_linear_time_on_deeply_nested_wrappers(self) -> None:
1331 payload = "(" * 5000 + "is:private" + ")" * 5000
1332 start = time.monotonic()
1333 result = github.strip_search_qualifiers(payload)
1334 elapsed = time.monotonic() - start
1335 assert result == ""
1336 assert elapsed < 1.0, f"deeply nested wrappers took {elapsed:.3f}s (expected linear O(N) < 1.0s)"
1337
1338 mixed = "[(" * 2500 + "-is:public" + ")]" * 2500
1339 start2 = time.monotonic()
1340 assert github.strip_search_qualifiers(mixed) == ""
1341 assert time.monotonic() - start2 < 1.0
1342
1343 def test_strip_search_qualifiers_linear_time_on_long_backslash_run(self) -> None:
1344 slashes = "\\" * 50000
1345 start = time.monotonic()
1346 result = github.strip_search_qualifiers(slashes)
1347 elapsed = time.monotonic() - start
1348 assert result == slashes
1349 assert elapsed < 1.0, f"50k backslashes took {elapsed:.3f}s (expected linear O(N) < 1.0s)"
1350
1351 start2 = time.monotonic()
1352 res2 = github.strip_search_qualifiers(f"auth {slashes} -is:public")
1353 elapsed2 = time.monotonic() - start2
1354 assert res2 == f"auth {slashes}"
1355 assert elapsed2 < 1.0
1356
1357 @pytest.mark.parametrize(
1358 "adversarial_topic",
1359 [
1360 "auth -is:public",
1361 "(auth)-is:public",
1362 "(auth)is:private",
1363 "auth -is:(public)",
1364 "auth label:(bug OR feat)",
1365 'auth -"is:public"',
1366 "react -created:>2020-01-01",
1367 "foo -is:issue -is:pull-request",
1368 "(-is:public) auth -org:private-org -repo:acme/secret",
1369 'say "hello world',
1370 'say "hello\\"',
1371 "auth -is:()public visibility:private",
1372 ],
1373 )
1374 @pytest.mark.parametrize("token", [None, "test-token"])
1375 def test_search_github_preserves_public_and_date_boundaries_against_breakout(
1376 self, adversarial_topic: str, token: str | None,
1377 ) -> None:
1378 captured_queries: list[str] = []
1379
1380 def fake_fetch(url, *args, **kwargs):
1381 q = urllib.parse.parse_qs(urllib.parse.urlparse(url).query)["q"][0]
1382 captured_queries.append(q)
1383 return {"items": []}
1384
1385 with mock.patch.object(github, "_resolve_token", return_value=token), \
1386 mock.patch.object(github, "_fetch_json", side_effect=fake_fetch):
1387 github.search_github(adversarial_topic, "2026-07-01", "2026-07-31")
1388
1389 assert captured_queries
1390 for q in captured_queries:
1391 assert q.startswith("is:public ")
1392 assert "-is:" not in q
1393 assert "-created:" not in q
1394 assert "-org:" not in q
1395 assert "-repo:" not in q
1396 assert "visibility:" not in q
1397 assert q.count("created:") == 1
1398 assert "created:2026-07-01..2026-07-31" in q
1399 # Balanced quotes guarantee engine-added created:/is:issue are outside any quote.
1400 assert q.count('"') % 2 == 0
1401 assert '\\"' not in q
1402
1403 @pytest.mark.parametrize("qualifier_only", ["-is:public", "(-is:public)", "-(is:public)", '"'])
1404 def test_negated_qualifier_only_topic_skips_network(self, qualifier_only: str) -> None:
1405 with mock.patch.object(github, "_resolve_token", return_value="test-token"), \
1406 mock.patch.object(github, "_fetch_json") as fetch_mock:
1407 res = github.search_github(qualifier_only, "2026-07-01", "2026-07-31")
1408 fetch_mock.assert_not_called()
1409 assert res["items"] == []
1410 assert "error" not in res
1411
1411 lines PYTHON