| 1 | """Security regression tests for PR07: media & social fetcher hardening. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-175: YouTube direct-transcript baseUrl SSRF / file:// / redirect / unbounded read |
| 5 | - HIGH-176: transcribe.py remote URL validation, yt-dlp isolation/caps, ffmpeg whitelist |
| 6 | - HIGH-178: YouTube video_id validation, VTT path-traversal/glob/collision/symlink isolation |
| 7 | - HIGH-181: Bluesky BSKY_SEARCH_HOST validation, redirect guard, and JWT exfiltration protection |
| 8 | """ |
| 9 | |
| 10 | from __future__ import annotations |
| 11 | |
| 12 | import ast |
| 13 | import io |
| 14 | import json |
| 15 | import os |
| 16 | import shutil |
| 17 | import socket |
| 18 | import threading |
| 19 | import time |
| 20 | import urllib.error |
| 21 | import urllib.request |
| 22 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 23 | from pathlib import Path |
| 24 | from unittest import mock |
| 25 | |
| 26 | import pytest |
| 27 | |
| 28 | from lib import bluesky, bounded_get, http, public_host, subproc, transcribe, youtube_yt |
| 29 | |
| 30 | |
| 31 | # --------------------------------------------------------------------------- |
| 32 | # HIGH-175: youtube_yt.py direct transcript baseUrl & read bounds |
| 33 | # --------------------------------------------------------------------------- |
| 34 | |
| 35 | |
| 36 | def _watch_html_with_base_url(base_url: str) -> str: |
| 37 | player = { |
| 38 | "captions": { |
| 39 | "playerCaptionsTracklistRenderer": { |
| 40 | "captionTracks": [ |
| 41 | {"languageCode": "en", "baseUrl": base_url}, |
| 42 | ] |
| 43 | } |
| 44 | } |
| 45 | } |
| 46 | return f"<html><script>var ytInitialPlayerResponse = {json.dumps(player)};</script></html>" |
| 47 | |
| 48 | |
| 49 | class TestHigh175YouTubeDirectTranscriptSSRF: |
| 50 | @pytest.mark.parametrize( |
| 51 | "bad_url", |
| 52 | [ |
| 53 | "file:///etc/passwd", |
| 54 | "file://localhost/etc/passwd", |
| 55 | "http://169.254.169.254/latest/meta-data/", |
| 56 | "http://127.0.0.1:8080/captions", |
| 57 | "http://www.youtube.com/api/timedtext?v=abc123", |
| 58 | "https://evil.example/api/timedtext?v=abc123", |
| 59 | "https://evil-youtube.com/api/timedtext?v=abc123", |
| 60 | "https://youtube.com.evil.com/api/timedtext?v=abc123", |
| 61 | "https://googlevideo.com/api/timedtext?v=abc123", |
| 62 | "https://ytimg.com/captions.vtt", |
| 63 | "https://user:pass@www.youtube.com/api/timedtext?v=abc123", |
| 64 | "https://@www.youtube.com/api/timedtext?v=abc123", |
| 65 | "https://www.youtube.com:8443/api/timedtext?v=abc123", |
| 66 | "https://169.254.169.254/api/timedtext", |
| 67 | "https://[::1]/api/timedtext", |
| 68 | "https://www.youtube.com/api/timedtext\r\nX-Injected: 1", |
| 69 | "https://evil.com\\@www.youtube.com/api/timedtext", |
| 70 | "/api/timedtext?v=abc123", |
| 71 | "ftp://www.youtube.com/captions", |
| 72 | "data:text/vtt,WEBVTT", |
| 73 | " https://www.youtube.com/api/timedtext ", |
| 74 | "", |
| 75 | ], |
| 76 | ) |
| 77 | def test_disallowed_caption_base_urls_rejected_before_fetch(self, bad_url: str) -> None: |
| 78 | assert youtube_yt._is_allowed_youtube_transcript_url(bad_url) is False |
| 79 | |
| 80 | seen_urls: list[str] = [] |
| 81 | |
| 82 | def fake_urlopen(req, timeout=None): |
| 83 | seen_urls.append(req.full_url) |
| 84 | if "/watch?" in req.full_url: |
| 85 | return io.BytesIO(_watch_html_with_base_url(bad_url).encode("utf-8")) |
| 86 | raise AssertionError(f"Disallowed caption URL was fetched: {req.full_url}") |
| 87 | |
| 88 | with mock.patch("urllib.request.urlopen", side_effect=fake_urlopen): |
| 89 | result = youtube_yt._fetch_transcript_direct("abc12345678") |
| 90 | |
| 91 | assert result is None |
| 92 | assert len(seen_urls) == 1 |
| 93 | assert seen_urls[0] == "https://www.youtube.com/watch?v=abc12345678" |
| 94 | |
| 95 | @pytest.mark.parametrize( |
| 96 | "good_url", |
| 97 | [ |
| 98 | "https://www.youtube.com/api/timedtext?v=abc123&lang=en", |
| 99 | "https://youtube.com/api/timedtext?v=abc123", |
| 100 | "https://m.youtube.com/api/timedtext?v=abc123", |
| 101 | "https://music.youtube.com/api/timedtext?v=abc123", |
| 102 | "https://video.google.com/timedtext?v=abc123", |
| 103 | "https://rr1---sn-ab5l6nzy.googlevideo.com/timedtext?v=abc123", |
| 104 | "https://i.ytimg.com/vi/abc123/captions.vtt", |
| 105 | "https://www.youtube.com:443/api/timedtext?v=abc123", |
| 106 | ], |
| 107 | ) |
| 108 | def test_allowed_youtube_caption_urls_accepted(self, good_url: str) -> None: |
| 109 | assert youtube_yt._is_allowed_youtube_transcript_url(good_url) is True |
| 110 | |
| 111 | def test_read_transcript_url_uses_http_open_request_with_guards(self) -> None: |
| 112 | captured_reqs: list[urllib.request.Request] = [] |
| 113 | |
| 114 | def fake_open_request(req, timeout): |
| 115 | captured_reqs.append(req) |
| 116 | return io.BytesIO(b"WEBVTT\n\nok\n") |
| 117 | |
| 118 | req = urllib.request.Request("https://www.youtube.com/api/timedtext?v=abc123&fmt=vtt") |
| 119 | with mock.patch.object(http, "open_request", side_effect=fake_open_request): |
| 120 | body = youtube_yt._read_transcript_url(req, timeout=10) |
| 121 | |
| 122 | assert "WEBVTT" in body |
| 123 | assert len(captured_reqs) == 1 |
| 124 | sent = captured_reqs[0] |
| 125 | assert getattr(sent, http._PUBLIC_ONLY_ATTR, False) is True |
| 126 | guard = getattr(sent, http._REDIRECT_GUARD_ATTR, None) |
| 127 | assert guard is youtube_yt._is_allowed_youtube_transcript_url |
| 128 | |
| 129 | def test_youtube_yt_has_no_direct_urlopen_calls(self) -> None: |
| 130 | source = Path(youtube_yt.__file__).read_text(encoding="utf-8") |
| 131 | tree = ast.parse(source) |
| 132 | direct_calls = [ |
| 133 | node.lineno |
| 134 | for node in ast.walk(tree) |
| 135 | if isinstance(node, ast.Call) |
| 136 | and isinstance(node.func, ast.Attribute) |
| 137 | and node.func.attr == "urlopen" |
| 138 | ] |
| 139 | assert direct_calls == [] |
| 140 | |
| 141 | @pytest.mark.parametrize( |
| 142 | "redirect_target", |
| 143 | [ |
| 144 | "file:///etc/passwd", |
| 145 | "http://169.254.169.254/latest/meta-data/", |
| 146 | "https://127.0.0.1/secret", |
| 147 | "https://evil.example/steal", |
| 148 | "http://www.youtube.com/api/timedtext?v=abc", |
| 149 | "https://www.youtube.com:8443/api/timedtext?v=abc", |
| 150 | "https://user@www.youtube.com/api/timedtext?v=abc", |
| 151 | ], |
| 152 | ) |
| 153 | def test_redirect_handler_blocks_disallowed_targets(self, redirect_target: str) -> None: |
| 154 | handler = http._StripAuthOnCrossOriginRedirect() |
| 155 | req = urllib.request.Request("https://www.youtube.com/api/timedtext?v=abc123") |
| 156 | setattr(req, http._REDIRECT_GUARD_ATTR, youtube_yt._is_allowed_youtube_transcript_url) |
| 157 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 158 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 159 | handler.redirect_request(req, io.BytesIO(), 302, "Found", {}, redirect_target) |
| 160 | assert exc_info.value.code == 403 |
| 161 | |
| 162 | def test_public_only_blocks_private_dns_resolution(self, monkeypatch) -> None: |
| 163 | def fake_getaddrinfo(host, port, *_args, **_kwargs): |
| 164 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", port))] |
| 165 | |
| 166 | monkeypatch.setattr(public_host.socket, "getaddrinfo", fake_getaddrinfo) |
| 167 | req = urllib.request.Request("https://www.youtube.com/api/timedtext?v=abc123") |
| 168 | with pytest.raises(urllib.error.URLError) as exc_info: |
| 169 | youtube_yt._read_transcript_url(req, timeout=5) |
| 170 | assert isinstance(exc_info.value.reason, public_host.NonPublicAddressError) |
| 171 | |
| 172 | def test_response_exceeding_max_bytes_is_rejected_no_deadline(self, monkeypatch) -> None: |
| 173 | monkeypatch.setattr(youtube_yt, "_MAX_TRANSCRIPT_RESPONSE_BYTES", 64) |
| 174 | oversized = b"A" * 65 |
| 175 | |
| 176 | with mock.patch("urllib.request.urlopen", return_value=io.BytesIO(oversized)): |
| 177 | result = youtube_yt._fetch_transcript_direct("abc12345678") |
| 178 | |
| 179 | assert result is None |
| 180 | |
| 181 | def test_response_exceeding_max_bytes_is_rejected_with_deadline(self, monkeypatch) -> None: |
| 182 | monkeypatch.setattr(youtube_yt, "_MAX_TRANSCRIPT_RESPONSE_BYTES", 64) |
| 183 | oversized = b"A" * 65 |
| 184 | |
| 185 | with mock.patch.object(bounded_get, "get", return_value=(200, oversized, None)), \ |
| 186 | youtube_yt.sc_spend_until(lambda: False, deadline=youtube_yt.time.monotonic() + 60): |
| 187 | result = youtube_yt._fetch_transcript_direct("abc12345678") |
| 188 | |
| 189 | assert result is None |
| 190 | |
| 191 | def test_fragment_in_base_url_stripped_before_fmt_param(self) -> None: |
| 192 | seen_urls: list[str] = [] |
| 193 | |
| 194 | def fake_urlopen(req, timeout=None): |
| 195 | seen_urls.append(req.full_url) |
| 196 | if "/watch?" in req.full_url: |
| 197 | html = _watch_html_with_base_url("https://www.youtube.com/api/timedtext?v=abc123#frag") |
| 198 | return io.BytesIO(html.encode("utf-8")) |
| 199 | return io.BytesIO(b"WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nhello\n") |
| 200 | |
| 201 | with mock.patch("urllib.request.urlopen", side_effect=fake_urlopen): |
| 202 | result = youtube_yt._fetch_transcript_direct("abc12345678") |
| 203 | |
| 204 | assert result is not None and "hello" in result |
| 205 | assert seen_urls[1] == "https://www.youtube.com/api/timedtext?v=abc123&fmt=vtt" |
| 206 | |
| 207 | def test_read_transcript_url_propagates_guards_and_max_bytes_under_deadline(self) -> None: |
| 208 | captured: list[tuple[urllib.request.Request, dict]] = [] |
| 209 | |
| 210 | def fake_bounded(req, **kwargs): |
| 211 | captured.append((req, kwargs)) |
| 212 | return 200, b"WEBVTT\n\nok\n", None |
| 213 | |
| 214 | req = urllib.request.Request("https://www.youtube.com/api/timedtext?v=abc123&fmt=vtt") |
| 215 | with mock.patch.object(bounded_get, "get", side_effect=fake_bounded), \ |
| 216 | youtube_yt.sc_spend_until(lambda: False, deadline=time.monotonic() + 60): |
| 217 | body = youtube_yt._read_transcript_url(req, timeout=10) |
| 218 | |
| 219 | assert "WEBVTT" in body |
| 220 | assert len(captured) == 1 |
| 221 | sent_req, kwargs = captured[0] |
| 222 | assert getattr(sent_req, http._PUBLIC_ONLY_ATTR, False) is True |
| 223 | assert getattr(sent_req, bounded_get._REDIRECT_POLICY_ATTR, None) == youtube_yt._YT_TRANSCRIPT_REDIRECT_POLICY |
| 224 | assert kwargs["max_bytes"] == youtube_yt._MAX_TRANSCRIPT_RESPONSE_BYTES |
| 225 | |
| 226 | def test_bounded_get_worker_enforces_public_only_on_loopback(self) -> None: |
| 227 | hits: list[str] = [] |
| 228 | |
| 229 | class Handler(BaseHTTPRequestHandler): |
| 230 | def log_message(self, *args): |
| 231 | pass |
| 232 | |
| 233 | def do_GET(self): |
| 234 | hits.append(self.path) |
| 235 | self.send_response(200) |
| 236 | self.end_headers() |
| 237 | self.wfile.write(b"secret") |
| 238 | |
| 239 | server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 240 | server.daemon_threads = True |
| 241 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 242 | thread.start() |
| 243 | try: |
| 244 | url = f"http://127.0.0.1:{server.server_port}/secret" |
| 245 | req = urllib.request.Request(url) |
| 246 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 247 | with pytest.raises(urllib.error.URLError) as exc_info: |
| 248 | bounded_get.get(req, timeout=5, deadline_monotonic=time.monotonic() + 5) |
| 249 | assert isinstance(exc_info.value.reason, public_host.NonPublicAddressError) |
| 250 | |
| 251 | req_kw = urllib.request.Request(url) |
| 252 | with pytest.raises(urllib.error.URLError) as exc_info_kw: |
| 253 | bounded_get.get( |
| 254 | req_kw, timeout=5, deadline_monotonic=time.monotonic() + 5, public_only=True, |
| 255 | ) |
| 256 | assert isinstance(exc_info_kw.value.reason, public_host.NonPublicAddressError) |
| 257 | assert hits == [] |
| 258 | finally: |
| 259 | server.shutdown() |
| 260 | server.server_close() |
| 261 | thread.join(2) |
| 262 | |
| 263 | @pytest.mark.parametrize( |
| 264 | ("target_kind", "expected_code"), |
| 265 | [ |
| 266 | ("metadata", 403), |
| 267 | ("secret_loopback", 403), |
| 268 | ("evil_host", 403), |
| 269 | ("ftp_scheme", 403), |
| 270 | ("file_scheme", 403), |
| 271 | ], |
| 272 | ) |
| 273 | def test_bounded_get_worker_blocks_disallowed_redirects_unmocked( |
| 274 | self, target_kind: str, expected_code: int, |
| 275 | ) -> None: |
| 276 | secret_hits: list[str] = [] |
| 277 | |
| 278 | class SecretHandler(BaseHTTPRequestHandler): |
| 279 | def log_message(self, *args): |
| 280 | pass |
| 281 | |
| 282 | def do_GET(self): |
| 283 | secret_hits.append(self.path) |
| 284 | self.send_response(200) |
| 285 | self.end_headers() |
| 286 | self.wfile.write(b"TOP_SECRET") |
| 287 | |
| 288 | secret_srv = ThreadingHTTPServer(("127.0.0.1", 0), SecretHandler) |
| 289 | secret_srv.daemon_threads = True |
| 290 | secret_thread = threading.Thread(target=secret_srv.serve_forever, daemon=True) |
| 291 | secret_thread.start() |
| 292 | |
| 293 | redirect_targets = { |
| 294 | "metadata": "http://169.254.169.254/latest/meta-data/", |
| 295 | "secret_loopback": f"http://127.0.0.1:{secret_srv.server_port}/secret", |
| 296 | "evil_host": "https://evil.example/steal", |
| 297 | "ftp_scheme": "ftp://evil.example/secret", |
| 298 | "file_scheme": "file:///etc/passwd", |
| 299 | } |
| 300 | location = redirect_targets[target_kind] |
| 301 | |
| 302 | class RedirectHandler(BaseHTTPRequestHandler): |
| 303 | def log_message(self, *args): |
| 304 | pass |
| 305 | |
| 306 | def do_GET(self): |
| 307 | self.send_response(302) |
| 308 | self.send_header("Location", location) |
| 309 | self.send_header("Content-Length", "0") |
| 310 | self.end_headers() |
| 311 | |
| 312 | front_srv = ThreadingHTTPServer(("127.0.0.1", 0), RedirectHandler) |
| 313 | front_srv.daemon_threads = True |
| 314 | front_thread = threading.Thread(target=front_srv.serve_forever, daemon=True) |
| 315 | front_thread.start() |
| 316 | try: |
| 317 | policy = { |
| 318 | "https_only": False, |
| 319 | "require_public_syntax": False, |
| 320 | "exact_hosts": ["127.0.0.1"], |
| 321 | "allowed_ports": [front_srv.server_port], |
| 322 | } |
| 323 | req = urllib.request.Request(f"http://127.0.0.1:{front_srv.server_port}/start") |
| 324 | setattr(req, bounded_get._REDIRECT_POLICY_ATTR, policy) |
| 325 | status, body, error = bounded_get.get( |
| 326 | req, timeout=5, deadline_monotonic=time.monotonic() + 5, read_error_body=False, |
| 327 | ) |
| 328 | assert status == expected_code |
| 329 | assert body is None |
| 330 | assert isinstance(error, urllib.error.HTTPError) |
| 331 | assert error.code == expected_code |
| 332 | assert secret_hits == [] |
| 333 | finally: |
| 334 | front_srv.shutdown() |
| 335 | front_srv.server_close() |
| 336 | front_thread.join(2) |
| 337 | secret_srv.shutdown() |
| 338 | secret_srv.server_close() |
| 339 | secret_thread.join(2) |
| 340 | |
| 341 | def test_bounded_get_worker_enforces_max_bytes_mid_stream_under_sc_spend_until( |
| 342 | self, monkeypatch, |
| 343 | ) -> None: |
| 344 | bytes_written = [0] |
| 345 | total_stream_bytes = 4 * 1024 * 1024 |
| 346 | |
| 347 | class StreamHandler(BaseHTTPRequestHandler): |
| 348 | def log_message(self, *args): |
| 349 | pass |
| 350 | |
| 351 | def do_GET(self): |
| 352 | self.send_response(200) |
| 353 | self.send_header("Content-Type", "text/html") |
| 354 | self.send_header("Content-Length", str(total_stream_bytes)) |
| 355 | self.end_headers() |
| 356 | chunk = b"X" * 16384 |
| 357 | remaining = total_stream_bytes |
| 358 | try: |
| 359 | while remaining > 0: |
| 360 | piece = chunk[:remaining] |
| 361 | self.wfile.write(piece) |
| 362 | self.wfile.flush() |
| 363 | bytes_written[0] += len(piece) |
| 364 | remaining -= len(piece) |
| 365 | except (BrokenPipeError, ConnectionResetError, OSError): |
| 366 | pass |
| 367 | |
| 368 | server = ThreadingHTTPServer(("127.0.0.1", 0), StreamHandler) |
| 369 | server.daemon_threads = True |
| 370 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 371 | thread.start() |
| 372 | |
| 373 | original_bounded = bounded_get.get |
| 374 | monkeypatch.setattr(youtube_yt, "_MAX_TRANSCRIPT_RESPONSE_BYTES", 4096) |
| 375 | |
| 376 | def local_bounded(req, **kwargs): |
| 377 | local_req = urllib.request.Request( |
| 378 | f"http://127.0.0.1:{server.server_port}/watch", |
| 379 | headers=dict(req.header_items()), |
| 380 | ) |
| 381 | return original_bounded(local_req, **kwargs) |
| 382 | |
| 383 | monkeypatch.setattr(bounded_get, "get", local_bounded) |
| 384 | try: |
| 385 | with youtube_yt.sc_spend_until(lambda: False, deadline=time.monotonic() + 20): |
| 386 | result = youtube_yt._fetch_transcript_direct("abc12345678", timeout=5) |
| 387 | assert result is None |
| 388 | assert bytes_written[0] < total_stream_bytes |
| 389 | finally: |
| 390 | server.shutdown() |
| 391 | server.server_close() |
| 392 | thread.join(2) |
| 393 | |
| 394 | def test_redirect_handler_closes_without_draining_redirect_body(self) -> None: |
| 395 | handler = http._StripAuthOnCrossOriginRedirect() |
| 396 | followed: list[urllib.request.Request] = [] |
| 397 | |
| 398 | class _FakeParent: |
| 399 | def open(self, new_req, timeout=None): |
| 400 | followed.append(new_req) |
| 401 | return io.BytesIO(b"destination-ok") |
| 402 | |
| 403 | class _SpyFP: |
| 404 | def __init__(self): |
| 405 | self.closed = False |
| 406 | |
| 407 | def read(self, *args, **kwargs): |
| 408 | raise AssertionError("redirect handler must not drain redirect body via fp.read()") |
| 409 | |
| 410 | def close(self): |
| 411 | self.closed = True |
| 412 | |
| 413 | handler.parent = _FakeParent() |
| 414 | req = urllib.request.Request("https://www.youtube.com/watch?v=abc123") |
| 415 | req.timeout = 5 |
| 416 | fp = _SpyFP() |
| 417 | resp = handler.http_error_302( |
| 418 | req, fp, 302, "Found", {"location": "https://www.youtube.com/api/timedtext?v=abc123"}, |
| 419 | ) |
| 420 | assert fp.closed is True |
| 421 | assert resp.read() == b"destination-ok" |
| 422 | assert len(followed) == 1 |
| 423 | |
| 424 | def test_redirect_with_oversized_body_followed_without_draining_unmocked(self) -> None: |
| 425 | redirect_body_bytes = 16 * 1024 * 1024 |
| 426 | bytes_written = [0] |
| 427 | stop_event = threading.Event() |
| 428 | |
| 429 | class Handler(BaseHTTPRequestHandler): |
| 430 | def log_message(self, *args): |
| 431 | pass |
| 432 | |
| 433 | def do_GET(self): |
| 434 | if self.path == "/start": |
| 435 | self.send_response(302) |
| 436 | self.send_header("Location", "/dest") |
| 437 | self.send_header("Content-Length", str(redirect_body_bytes)) |
| 438 | self.end_headers() |
| 439 | chunk = b"R" * 32768 |
| 440 | remaining = redirect_body_bytes |
| 441 | try: |
| 442 | while remaining > 0 and not stop_event.is_set(): |
| 443 | piece = chunk[:remaining] |
| 444 | self.wfile.write(piece) |
| 445 | self.wfile.flush() |
| 446 | bytes_written[0] += len(piece) |
| 447 | remaining -= len(piece) |
| 448 | except (BrokenPipeError, ConnectionResetError, OSError): |
| 449 | pass |
| 450 | else: |
| 451 | body = b"final-destination" |
| 452 | self.send_response(200) |
| 453 | self.send_header("Content-Length", str(len(body))) |
| 454 | self.end_headers() |
| 455 | self.wfile.write(body) |
| 456 | |
| 457 | server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 458 | server.daemon_threads = True |
| 459 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 460 | thread.start() |
| 461 | try: |
| 462 | req = urllib.request.Request(f"http://127.0.0.1:{server.server_port}/start") |
| 463 | with http.open_request(req, 5) as resp: |
| 464 | assert resp.read() == b"final-destination" |
| 465 | assert bytes_written[0] < redirect_body_bytes |
| 466 | finally: |
| 467 | stop_event.set() |
| 468 | server.shutdown() |
| 469 | server.server_close() |
| 470 | thread.join(2) |
| 471 | |
| 472 | |
| 473 | # --------------------------------------------------------------------------- |
| 474 | # HIGH-178: youtube_yt.py video_id traversal, glob, collision, URL injection |
| 475 | # --------------------------------------------------------------------------- |
| 476 | |
| 477 | |
| 478 | class TestHigh178YouTubeVideoIdValidation: |
| 479 | @pytest.mark.parametrize( |
| 480 | "bad_id", |
| 481 | [ |
| 482 | "", |
| 483 | "../outside", |
| 484 | "../../etc/passwd", |
| 485 | "..\\outside", |
| 486 | "sub/vid", |
| 487 | "sub\\vid", |
| 488 | "*", |
| 489 | "abc*", |
| 490 | "abc?", |
| 491 | "[a-z]bc", |
| 492 | "abc&list=PLevil", |
| 493 | "abc#frag", |
| 494 | "abc?x=1", |
| 495 | "abc%26x=1", |
| 496 | "abc def", |
| 497 | "abc\ndef", |
| 498 | "abc.en", |
| 499 | "a" * 65, |
| 500 | None, |
| 501 | 12345, |
| 502 | ], |
| 503 | ) |
| 504 | def test_invalid_video_ids_rejected(self, bad_id) -> None: |
| 505 | assert youtube_yt._is_valid_video_id(bad_id) is False |
| 506 | |
| 507 | @pytest.mark.parametrize( |
| 508 | "good_id", |
| 509 | [ |
| 510 | "dQw4w9WgXcQ", |
| 511 | "-_abc123XYZ", |
| 512 | "abc123", |
| 513 | "YT1", |
| 514 | "YT10", |
| 515 | "video-00", |
| 516 | ], |
| 517 | ) |
| 518 | def test_valid_video_ids_accepted(self, good_id: str) -> None: |
| 519 | assert youtube_yt._is_valid_video_id(good_id) is True |
| 520 | |
| 521 | def test_pick_ytdlp_vtt_blocks_parent_directory_traversal(self, tmp_path: Path) -> None: |
| 522 | (tmp_path / "secret.en.vtt").write_text("WEBVTT\n\nSECRET\n", encoding="utf-8") |
| 523 | work = tmp_path / "work" |
| 524 | work.mkdir() |
| 525 | |
| 526 | assert youtube_yt._pick_ytdlp_vtt("../secret", str(work), ["en"]) is None |
| 527 | assert youtube_yt._pick_ytdlp_vtt("../*", str(work), ["en"]) is None |
| 528 | assert youtube_yt._pick_ytdlp_vtt("*", str(work), ["en"]) is None |
| 529 | |
| 530 | def test_pick_ytdlp_vtt_blocks_prefix_collision_between_yt1_and_yt10(self, tmp_path: Path) -> None: |
| 531 | (tmp_path / "YT10.en.vtt").write_text("WEBVTT\n\nVideo ten\n", encoding="utf-8") |
| 532 | |
| 533 | assert youtube_yt._pick_ytdlp_vtt("YT1", str(tmp_path), ["en"]) is None |
| 534 | |
| 535 | (tmp_path / "YT1.en.vtt").write_text("WEBVTT\n\nVideo one\n", encoding="utf-8") |
| 536 | picked = youtube_yt._pick_ytdlp_vtt("YT1", str(tmp_path), ["en"]) |
| 537 | assert picked is not None |
| 538 | assert picked.name == "YT1.en.vtt" |
| 539 | |
| 540 | def test_pick_ytdlp_vtt_blocks_symlink_escape(self, tmp_path: Path) -> None: |
| 541 | outside = tmp_path / "outside.vtt" |
| 542 | outside.write_text("WEBVTT\n\nLEAKED\n", encoding="utf-8") |
| 543 | work = tmp_path / "work" |
| 544 | work.mkdir() |
| 545 | link = work / "abc12345678.en.vtt" |
| 546 | link.symlink_to(outside) |
| 547 | |
| 548 | assert youtube_yt._pick_ytdlp_vtt("abc12345678", str(work), ["en"]) is None |
| 549 | |
| 550 | def test_parallel_transcripts_isolate_worker_temp_dirs(self) -> None: |
| 551 | seen_dirs: dict[str, str] = {} |
| 552 | |
| 553 | def fake_fetch(vid, temp_dir, status=None, token=None, rescue_budget=None): |
| 554 | seen_dirs[vid] = temp_dir |
| 555 | return f"ok-{vid}" |
| 556 | |
| 557 | with mock.patch.object(youtube_yt, "fetch_transcript", side_effect=fake_fetch): |
| 558 | out = youtube_yt.fetch_transcripts_parallel(["YT1", "YT10"], max_workers=2) |
| 559 | |
| 560 | assert out == {"YT1": "ok-YT1", "YT10": "ok-YT10"} |
| 561 | assert seen_dirs["YT1"] != seen_dirs["YT10"] |
| 562 | assert Path(seen_dirs["YT1"]).parent == Path(seen_dirs["YT10"]).parent |
| 563 | |
| 564 | @pytest.mark.parametrize("bad_id", ["../secret", "abc&list=1", "abc#frag", "*"]) |
| 565 | def test_all_entrypoints_reject_invalid_video_id_without_side_effects( |
| 566 | self, tmp_path: Path, bad_id: str, |
| 567 | ) -> None: |
| 568 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 569 | mock.patch.object(youtube_yt.subproc, "run_with_timeout") as run_mock, \ |
| 570 | mock.patch.object(youtube_yt.http, "get") as http_get, \ |
| 571 | mock.patch.object(http, "open_request") as open_req: |
| 572 | assert youtube_yt.fetch_transcript(bad_id, str(tmp_path), token="k") is None |
| 573 | assert youtube_yt._fetch_transcript_direct(bad_id) is None |
| 574 | assert youtube_yt._fetch_transcript_ytdlp(bad_id, str(tmp_path)) is None |
| 575 | assert youtube_yt._fetch_transcript_ytdlp_via_ssh(bad_id, "macmini") is None |
| 576 | assert youtube_yt._ytdlp_comments_result(bad_id) == ([], False) |
| 577 | assert youtube_yt._fetch_video_comments(bad_id, token="k") == [] |
| 578 | assert youtube_yt._sc_fetch_transcript(bad_id, token="k") is None |
| 579 | |
| 580 | run_mock.assert_not_called() |
| 581 | http_get.assert_not_called() |
| 582 | open_req.assert_not_called() |
| 583 | |
| 584 | def test_search_parsers_drop_poisoned_video_ids(self) -> None: |
| 585 | stdout = "\n".join([ |
| 586 | json.dumps({"id": "../evil", "title": "Bad", "upload_date": "20260601"}), |
| 587 | json.dumps({"id": "abc&foo=bar", "title": "Bad2", "upload_date": "20260601"}), |
| 588 | json.dumps({"id": "dQw4w9WgXcQ", "title": "Good", "upload_date": "20260601"}), |
| 589 | ]) |
| 590 | items = youtube_yt._parse_search_stdout(stdout, "topic") |
| 591 | assert [i["video_id"] for i in items] == ["dQw4w9WgXcQ"] |
| 592 | |
| 593 | sc_raw = [ |
| 594 | {"id": "../evil", "title": "Bad", "views": 100, "upload_date": "2026-06-15"}, |
| 595 | {"id": "dQw4w9WgXcQ", "title": "Good", "views": 50, "upload_date": "2026-06-15"}, |
| 596 | ] |
| 597 | with mock.patch.object(youtube_yt, "_sc_youtube_search", return_value=sc_raw), \ |
| 598 | mock.patch.object(youtube_yt, "_sc_fetch_transcript", return_value="ok"): |
| 599 | out = youtube_yt.search_youtube_sc( |
| 600 | "topic", "2026-06-01", "2026-06-30", depth="default", token="dummy", |
| 601 | ) |
| 602 | assert [i["video_id"] for i in out["items"]] == ["dQw4w9WgXcQ"] |
| 603 | |
| 604 | def test_leading_dash_video_id_and_proxy_stay_before_option_terminator( |
| 605 | self, tmp_path: Path, monkeypatch, |
| 606 | ) -> None: |
| 607 | monkeypatch.setenv("YOUTUBE_PROXY", "socks5://127.0.0.1:1080") |
| 608 | monkeypatch.delenv("LAST30DAYS_YOUTUBE_SSH_HOST", raising=False) |
| 609 | fake_res = subproc.SubprocResult(returncode=0, stdout='{"comments": []}', stderr="") |
| 610 | |
| 611 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 612 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=fake_res) as run_mock: |
| 613 | youtube_yt._fetch_transcript_ytdlp("-_abc123XYZ", str(tmp_path)) |
| 614 | youtube_yt._ytdlp_comments_result("-_abc123XYZ") |
| 615 | |
| 616 | for call in run_mock.call_args_list: |
| 617 | cmd = call.args[0] |
| 618 | dash_idx = cmd.index("--") |
| 619 | assert cmd[dash_idx + 1] == "https://www.youtube.com/watch?v=-_abc123XYZ" |
| 620 | assert cmd.index("--proxy") < dash_idx |
| 621 | assert cmd.index("--extractor-args") < dash_idx |
| 622 | assert "--ignore-config" in cmd[:dash_idx] |
| 623 | assert "--no-cookies-from-browser" in cmd[:dash_idx] |
| 624 | |
| 625 | def test_leading_dash_video_id_on_ssh_transcript_uses_option_terminator(self) -> None: |
| 626 | fake_vtt = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nssh transcript\n" |
| 627 | fake_res = subproc.SubprocResult(returncode=0, stdout=fake_vtt, stderr="") |
| 628 | with mock.patch.object(youtube_yt, "_run_ytdlp", return_value=fake_res) as run_mock: |
| 629 | out = youtube_yt._fetch_transcript_ytdlp_via_ssh("-_abc123XYZ", "macmini") |
| 630 | |
| 631 | assert out == fake_vtt |
| 632 | remote_script = run_mock.call_args.args[0][-1] |
| 633 | assert "-- 'https://www.youtube.com/watch?v=-_abc123XYZ'" in remote_script |
| 634 | |
| 635 | |
| 636 | # --------------------------------------------------------------------------- |
| 637 | # HIGH-176: transcribe.py URL SSRF, yt-dlp isolation/caps, ffmpeg whitelist |
| 638 | # --------------------------------------------------------------------------- |
| 639 | |
| 640 | |
| 641 | class TestHigh176TranscribeHardening: |
| 642 | @pytest.mark.parametrize( |
| 643 | "bad_source", |
| 644 | [ |
| 645 | "http://127.0.0.1:8080/audio.mp3", |
| 646 | "http://169.254.169.254/latest/meta-data/", |
| 647 | "http://10.0.0.1/internal.mp3", |
| 648 | "http://[::1]/audio.mp3", |
| 649 | "http://2130706433/audio.mp3", |
| 650 | "http://0177.0.0.1/audio.mp3", |
| 651 | "https://localhost/audio.mp3", |
| 652 | "https://user:pass@example.com/audio.mp3", |
| 653 | "https://127.0.0.1\\@media.example.com/audio.mp3", |
| 654 | "https://evil.com\\@media.example.com/audio.mp3", |
| 655 | "file:///etc/passwd", |
| 656 | "ftp://example.com/audio.mp3", |
| 657 | "gopher://127.0.0.1:6379/", |
| 658 | "concat:/etc/passwd|/etc/shadow", |
| 659 | "pipe:0", |
| 660 | "subfile,,start,0,,:/etc/passwd", |
| 661 | "--exec=id", |
| 662 | "https://example.com/a\nb", |
| 663 | " https://127.0.0.1/a", |
| 664 | "", |
| 665 | ], |
| 666 | ) |
| 667 | def test_unsafe_sources_rejected_without_spawning_subprocesses( |
| 668 | self, tmp_path: Path, bad_source: str, |
| 669 | ) -> None: |
| 670 | with mock.patch.object(transcribe, "_run") as run_mock: |
| 671 | result = transcribe._acquire_audio(bad_source, str(tmp_path), timeout=30.0) |
| 672 | assert result is None |
| 673 | run_mock.assert_not_called() |
| 674 | |
| 675 | def test_url_syntax_check_does_not_block_on_dns_and_proxy_rejects_private_dns( |
| 676 | self, monkeypatch, |
| 677 | ) -> None: |
| 678 | # _is_safe_remote_media_url must stay syntax-only so slow DNS stays inside yt-dlp's timeout. |
| 679 | with mock.patch.object( |
| 680 | public_host.socket, |
| 681 | "getaddrinfo", |
| 682 | side_effect=AssertionError("syntax check must not block on DNS"), |
| 683 | ): |
| 684 | assert transcribe._is_safe_remote_media_url("https://rebind.example/media.mp4") is True |
| 685 | |
| 686 | # _PublicMediaProxy enforces fresh public DNS resolution at connect time. |
| 687 | orig_getaddrinfo = public_host.socket.getaddrinfo |
| 688 | |
| 689 | def private_dns(host, port, *args, **kwargs): |
| 690 | if host == "rebind.example": |
| 691 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("169.254.169.254", port))] |
| 692 | return orig_getaddrinfo(host, port, *args, **kwargs) |
| 693 | |
| 694 | monkeypatch.setattr(public_host.socket, "getaddrinfo", private_dns) |
| 695 | with transcribe._PublicMediaProxy(max_bytes=1024 * 1024) as proxy: |
| 696 | with socket.create_connection(("127.0.0.1", proxy.port), timeout=5) as sock: |
| 697 | sock.sendall( |
| 698 | b"GET http://rebind.example/media.mp4 HTTP/1.1\r\nHost: rebind.example\r\n\r\n" |
| 699 | ) |
| 700 | reply = sock.recv(1024).decode("latin-1") |
| 701 | assert reply.startswith("HTTP/1.1 403") |
| 702 | assert proxy.blocked_count == 1 |
| 703 | |
| 704 | with socket.create_connection(("127.0.0.1", proxy.port), timeout=5) as sock: |
| 705 | sock.sendall( |
| 706 | b"CONNECT rebind.example:443 HTTP/1.1\r\nHost: rebind.example:443\r\n\r\n" |
| 707 | ) |
| 708 | reply = sock.recv(1024).decode("latin-1") |
| 709 | assert reply.startswith("HTTP/1.1 403") |
| 710 | assert proxy.blocked_count == 2 |
| 711 | |
| 712 | @pytest.mark.parametrize( |
| 713 | "url", |
| 714 | [ |
| 715 | "https://media.example.com/clip.mp4", |
| 716 | "HTTP://media.example.com/clip.mp4", |
| 717 | "HTTPS://media.example.com/clip.mp4", |
| 718 | ], |
| 719 | ) |
| 720 | def test_public_remote_url_uses_hardened_ytdlp_and_ffmpeg_flags( |
| 721 | self, tmp_path: Path, monkeypatch, url: str, |
| 722 | ) -> None: |
| 723 | monkeypatch.setenv("NO_PROXY", "169.254.169.254,127.0.0.1,localhost") |
| 724 | monkeypatch.setenv("ALL_PROXY", "socks5://attacker.example:1080") |
| 725 | cmds: list[tuple[list[str], dict | None]] = [] |
| 726 | |
| 727 | def fake_run(cmd, timeout=120.0, *, env=None): |
| 728 | cmds.append((cmd, env)) |
| 729 | if cmd[0] == "yt-dlp": |
| 730 | out_path = cmd[cmd.index("-o") + 1] |
| 731 | # Minimal valid ISO BMFF M4A header so container demuxer validation passes. |
| 732 | Path(out_path).write_bytes(b"\x00\x00\x00\x18ftypM4A \x00\x00\x00\x00M4A ") |
| 733 | elif cmd[0] == "ffmpeg": |
| 734 | Path(cmd[-1]).write_bytes(b"ID3\x03\x00fake-mp3") |
| 735 | return True |
| 736 | |
| 737 | with mock.patch.object(transcribe, "_run", side_effect=fake_run): |
| 738 | out = transcribe._acquire_audio(url, str(tmp_path), timeout=30.0) |
| 739 | |
| 740 | assert out is not None and out.endswith("audio.mp3") |
| 741 | assert len(cmds) == 2 |
| 742 | |
| 743 | (ytdlp_cmd, ytdlp_env), (ffmpeg_cmd, _ffmpeg_env) = cmds |
| 744 | assert ytdlp_cmd[0] == "yt-dlp" |
| 745 | dash_idx = ytdlp_cmd.index("--") |
| 746 | assert ytdlp_cmd[dash_idx + 1] == url |
| 747 | flags = ytdlp_cmd[:dash_idx] |
| 748 | assert "--ignore-config" in flags |
| 749 | assert "--no-plugin-dirs" in flags |
| 750 | assert "--no-cookies-from-browser" in flags |
| 751 | assert "--no-playlist" in flags |
| 752 | assert "--no-live-from-start" in flags |
| 753 | assert flags[flags.index("--match-filter") + 1] == "!is_live" |
| 754 | assert flags[flags.index("--max-filesize") + 1] == transcribe.MAX_DOWNLOAD_SIZE_ARG |
| 755 | assert flags[flags.index("--downloader") + 1] == "dash,m3u8:native" |
| 756 | proxy_url = flags[flags.index("--proxy") + 1] |
| 757 | assert proxy_url.startswith("http://127.0.0.1:") |
| 758 | assert ytdlp_env is not None |
| 759 | assert ytdlp_env["HTTP_PROXY"] == proxy_url |
| 760 | assert ytdlp_env["HTTPS_PROXY"] == proxy_url |
| 761 | assert ytdlp_env["NO_PROXY"] == "" |
| 762 | assert ytdlp_env["no_proxy"] == "" |
| 763 | assert "ALL_PROXY" not in ytdlp_env |
| 764 | |
| 765 | assert ffmpeg_cmd[0] == "ffmpeg" |
| 766 | assert "-nostdin" in ffmpeg_cmd |
| 767 | wl_idx = ffmpeg_cmd.index("-protocol_whitelist") |
| 768 | f_idx = ffmpeg_cmd.index("-f") |
| 769 | i_idx = ffmpeg_cmd.index("-i") |
| 770 | assert ffmpeg_cmd[wl_idx + 1] == "file" |
| 771 | assert ffmpeg_cmd[f_idx + 1] == "mov,mp4,m4a,3gp,3g2,mj2" |
| 772 | assert wl_idx < i_idx |
| 773 | assert f_idx < i_idx |
| 774 | assert "-vn" in ffmpeg_cmd |
| 775 | assert ffmpeg_cmd[ffmpeg_cmd.index("-map_metadata") + 1] == "-1" |
| 776 | assert os.path.isabs(ffmpeg_cmd[i_idx + 1]) |
| 777 | |
| 778 | @pytest.mark.parametrize( |
| 779 | ("payload", "expected"), |
| 780 | [ |
| 781 | (b"\x00\x00\x00\x18ftypM4A \x00\x00\x00\x00", "mov,mp4,m4a,3gp,3g2,mj2"), |
| 782 | (b"\x1a\x45\xdf\xa3\x01\x00\x00\x00", "matroska,webm"), |
| 783 | (b"OggS\x00\x02\x00\x00", "ogg"), |
| 784 | (b"fLaC\x00\x00\x00\x22", "flac"), |
| 785 | (b"RIFF\x24\x00\x00\x00WAVEfmt ", "wav"), |
| 786 | (b"FORM\x00\x00\x00\x10AIFFCOMM", "aiff"), |
| 787 | (b"ID3\x03\x00\x00\x00\x00", "mp3"), |
| 788 | (b"\xff\xfb\x90\x00\x00\x00\x00\x00", "mp3"), |
| 789 | (b"\xff\xf1\x50\x80\x00\x1f\xfc\x00", "aac"), |
| 790 | (transcribe._ASF_GUID + b"\x00\x00", "asf"), |
| 791 | (b"#EXTM3U\n#EXTINF:1,\n/etc/passwd\n", None), |
| 792 | (b"ffconcat version 1.0\nfile '/tmp/secret.wav'\n", None), |
| 793 | (b"<?xml version='1.0'?><MPD/>", None), |
| 794 | (b"v=0\r\no=- 0 0 IN IP4 127.0.0.1\r\n", None), |
| 795 | (b"plain text file", None), |
| 796 | ], |
| 797 | ) |
| 798 | def test_detect_safe_audio_demuxer_allowlist( |
| 799 | self, tmp_path: Path, payload: bytes, expected: str | None, |
| 800 | ) -> None: |
| 801 | sample = tmp_path / "sample.bin" |
| 802 | sample.write_bytes(payload) |
| 803 | assert transcribe._detect_safe_audio_demuxer(str(sample)) == expected |
| 804 | |
| 805 | @pytest.mark.parametrize( |
| 806 | "playlist_payload", |
| 807 | [ |
| 808 | b"#EXTM3U\n#EXT-X-VERSION:3\n#EXTINF:1.0,\n{secret}\n#EXT-X-ENDLIST\n", |
| 809 | b"ffconcat version 1.0\nfile '{secret}'\n", |
| 810 | ], |
| 811 | ) |
| 812 | def test_remote_downloaded_playlist_referencing_local_file_rejected_before_ffmpeg( |
| 813 | self, tmp_path: Path, playlist_payload: bytes, |
| 814 | ) -> None: |
| 815 | secret_wav = tmp_path / "secret.wav" |
| 816 | secret_wav.write_bytes(b"RIFF\x24\x00\x00\x00WAVEfmt ") |
| 817 | workdir = tmp_path / "work" |
| 818 | workdir.mkdir() |
| 819 | cmds: list[list[str]] = [] |
| 820 | |
| 821 | def fake_run(cmd, timeout=120.0, *, env=None): |
| 822 | cmds.append(cmd) |
| 823 | if cmd[0] == "yt-dlp": |
| 824 | out_path = cmd[cmd.index("-o") + 1] |
| 825 | Path(out_path).write_bytes( |
| 826 | playlist_payload.replace(b"{secret}", str(secret_wav).encode("utf-8")) |
| 827 | ) |
| 828 | return True |
| 829 | |
| 830 | with mock.patch.object(transcribe, "_run", side_effect=fake_run): |
| 831 | out = transcribe._acquire_audio( |
| 832 | "https://media.example.com/disguised.m4a", str(workdir), timeout=30.0, |
| 833 | ) |
| 834 | |
| 835 | assert out is None |
| 836 | assert [c[0] for c in cmds] == ["yt-dlp"] |
| 837 | |
| 838 | def test_oversized_ytdlp_download_rejected_before_ffmpeg( |
| 839 | self, tmp_path: Path, monkeypatch, |
| 840 | ) -> None: |
| 841 | monkeypatch.setattr(transcribe, "MAX_DOWNLOAD_BYTES", 10) |
| 842 | cmds: list[list[str]] = [] |
| 843 | |
| 844 | def fake_run(cmd, timeout=120.0, *, env=None): |
| 845 | cmds.append(cmd) |
| 846 | if cmd[0] == "yt-dlp": |
| 847 | Path(cmd[cmd.index("-o") + 1]).write_bytes(b"X" * 11) |
| 848 | return True |
| 849 | |
| 850 | with mock.patch.object(transcribe, "_run", side_effect=fake_run): |
| 851 | out = transcribe._acquire_audio( |
| 852 | "https://media.example.com/huge.mp4", str(tmp_path), timeout=30.0, |
| 853 | ) |
| 854 | |
| 855 | assert out is None |
| 856 | assert [c[0] for c in cmds] == ["yt-dlp"] |
| 857 | |
| 858 | @pytest.mark.parametrize("mode", ["http", "connect"]) |
| 859 | def test_media_proxy_closes_and_untracks_upstream_socket_on_relay_error( |
| 860 | self, mode: str, |
| 861 | ) -> None: |
| 862 | upstream_srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 863 | upstream_srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 864 | upstream_srv.bind(("127.0.0.1", 0)) |
| 865 | upstream_srv.listen(4) |
| 866 | upstream_port = upstream_srv.getsockname()[1] |
| 867 | |
| 868 | def serve_one() -> None: |
| 869 | upstream_srv.settimeout(2.0) |
| 870 | try: |
| 871 | conn, _ = upstream_srv.accept() |
| 872 | except OSError: |
| 873 | return |
| 874 | with conn: |
| 875 | if mode == "http": |
| 876 | try: |
| 877 | conn.recv(4096) |
| 878 | except OSError: |
| 879 | pass |
| 880 | conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello") |
| 881 | else: |
| 882 | conn.sendall(b"hello") |
| 883 | |
| 884 | thread = threading.Thread(target=serve_one, daemon=True) |
| 885 | thread.start() |
| 886 | |
| 887 | def hybrid_resolver(host: str, port: int): |
| 888 | if host == "relay.test": |
| 889 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", upstream_port))] |
| 890 | return public_host.resolve_public_addresses(host, port) |
| 891 | |
| 892 | created_upstreams: list[socket.socket] = [] |
| 893 | |
| 894 | try: |
| 895 | with transcribe._PublicMediaProxy(max_bytes=1024 * 1024, resolver=hybrid_resolver) as proxy: |
| 896 | orig_connect = proxy._connect_public |
| 897 | |
| 898 | def spy_connect(host: str, port: int) -> socket.socket: |
| 899 | sock = orig_connect(host, port) |
| 900 | created_upstreams.append(sock) |
| 901 | return sock |
| 902 | |
| 903 | proxy._connect_public = spy_connect # type: ignore[method-assign] |
| 904 | |
| 905 | class _FailingClient: |
| 906 | def __init__(self, real_sock: socket.socket): |
| 907 | self._sock = real_sock |
| 908 | self.calls = 0 |
| 909 | |
| 910 | def fileno(self) -> int: |
| 911 | return self._sock.fileno() |
| 912 | |
| 913 | def recv(self, n: int) -> bytes: |
| 914 | return self._sock.recv(n) |
| 915 | |
| 916 | def sendall(self, data: bytes) -> None: |
| 917 | self.calls += 1 |
| 918 | if mode == "connect" and self.calls == 1: |
| 919 | # Allow 200 Connection Established, then fail on first relayed payload. |
| 920 | self._sock.sendall(data) |
| 921 | return |
| 922 | raise BrokenPipeError("simulated client disconnect mid-relay") |
| 923 | |
| 924 | def shutdown(self, how: int) -> None: |
| 925 | self._sock.shutdown(how) |
| 926 | |
| 927 | c1, c2 = socket.socketpair() |
| 928 | try: |
| 929 | failing_client = _FailingClient(c1) |
| 930 | with pytest.raises(BrokenPipeError): |
| 931 | if mode == "http": |
| 932 | proxy._handle_http( |
| 933 | failing_client, # type: ignore[arg-type] |
| 934 | "GET", |
| 935 | "http://relay.test/ok", |
| 936 | [], |
| 937 | b"", |
| 938 | ) |
| 939 | else: |
| 940 | proxy._handle_connect( |
| 941 | failing_client, # type: ignore[arg-type] |
| 942 | "relay.test:443", |
| 943 | b"", |
| 944 | ) |
| 945 | finally: |
| 946 | c1.close() |
| 947 | c2.close() |
| 948 | |
| 949 | assert len(created_upstreams) == 1 |
| 950 | assert created_upstreams[0].fileno() == -1 |
| 951 | with proxy._lock: |
| 952 | assert created_upstreams[0] not in proxy._active_sockets |
| 953 | finally: |
| 954 | upstream_srv.close() |
| 955 | thread.join(2) |
| 956 | |
| 957 | def test_media_proxy_blocks_http_and_connect_ssrf_and_redirects(self) -> None: |
| 958 | secret_hits: list[str] = [] |
| 959 | |
| 960 | class SecretHandler(BaseHTTPRequestHandler): |
| 961 | def log_message(self, *args): |
| 962 | pass |
| 963 | |
| 964 | def do_GET(self): |
| 965 | secret_hits.append(self.path) |
| 966 | self.send_response(200) |
| 967 | self.end_headers() |
| 968 | self.wfile.write(b"PRIVATE_SECRET") |
| 969 | |
| 970 | secret_srv = ThreadingHTTPServer(("127.0.0.1", 0), SecretHandler) |
| 971 | secret_srv.daemon_threads = True |
| 972 | secret_thread = threading.Thread(target=secret_srv.serve_forever, daemon=True) |
| 973 | secret_thread.start() |
| 974 | |
| 975 | class PublicHandler(BaseHTTPRequestHandler): |
| 976 | def log_message(self, *args): |
| 977 | pass |
| 978 | |
| 979 | def do_GET(self): |
| 980 | if self.path == "/redirect-secret": |
| 981 | self.send_response(302) |
| 982 | self.send_header("Location", f"http://127.0.0.1:{secret_srv.server_port}/secret") |
| 983 | self.send_header("Content-Length", "0") |
| 984 | self.end_headers() |
| 985 | elif self.path == "/playlist.m3u8": |
| 986 | body = f"#EXTM3U\n#EXTINF:1,\nhttp://127.0.0.1:{secret_srv.server_port}/seg.ts\n".encode() |
| 987 | self.send_response(200) |
| 988 | self.send_header("Content-Length", str(len(body))) |
| 989 | self.end_headers() |
| 990 | self.wfile.write(body) |
| 991 | else: |
| 992 | self.send_response(200) |
| 993 | self.send_header("Content-Length", "2") |
| 994 | self.end_headers() |
| 995 | self.wfile.write(b"ok") |
| 996 | |
| 997 | pub_srv = ThreadingHTTPServer(("127.0.0.1", 0), PublicHandler) |
| 998 | pub_srv.daemon_threads = True |
| 999 | pub_thread = threading.Thread(target=pub_srv.serve_forever, daemon=True) |
| 1000 | pub_thread.start() |
| 1001 | |
| 1002 | def hybrid_resolver(host: str, port: int): |
| 1003 | if host == "public.test": |
| 1004 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", pub_srv.server_port))] |
| 1005 | return public_host.resolve_public_addresses(host, port) |
| 1006 | |
| 1007 | try: |
| 1008 | with transcribe._PublicMediaProxy(max_bytes=1024 * 1024, resolver=hybrid_resolver) as proxy: |
| 1009 | opener = urllib.request.build_opener( |
| 1010 | urllib.request.ProxyHandler({"http": proxy.url, "https": proxy.url}) |
| 1011 | ) |
| 1012 | # Direct public.test succeeds. |
| 1013 | with opener.open("http://public.test/ok", timeout=5) as resp: |
| 1014 | assert resp.read() == b"ok" |
| 1015 | |
| 1016 | # 302 redirect from public.test to 127.0.0.1 secret is blocked with 403. |
| 1017 | with pytest.raises(urllib.error.HTTPError) as exc_redir: |
| 1018 | opener.open("http://public.test/redirect-secret", timeout=5) |
| 1019 | assert exc_redir.value.code == 403 |
| 1020 | |
| 1021 | # HLS playlist segment pointing at loopback is blocked with 403. |
| 1022 | with opener.open("http://public.test/playlist.m3u8", timeout=5) as resp: |
| 1023 | playlist = resp.read().decode("utf-8") |
| 1024 | seg_url = [line for line in playlist.splitlines() if line.startswith("http")][0] |
| 1025 | with pytest.raises(urllib.error.HTTPError) as exc_seg: |
| 1026 | opener.open(seg_url, timeout=5) |
| 1027 | assert exc_seg.value.code == 403 |
| 1028 | |
| 1029 | # Direct metadata & loopback HTTP and HTTPS CONNECT targets are refused with 403. |
| 1030 | for target in ( |
| 1031 | f"127.0.0.1:{secret_srv.server_port}", |
| 1032 | "169.254.169.254:443", |
| 1033 | "[::1]:443", |
| 1034 | "2130706433:80", |
| 1035 | ): |
| 1036 | with socket.create_connection(("127.0.0.1", proxy.port), timeout=5) as sock: |
| 1037 | sock.sendall(f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n".encode("ascii")) |
| 1038 | reply = sock.recv(1024).decode("latin-1") |
| 1039 | assert reply.startswith("HTTP/1.1 403"), (target, reply) |
| 1040 | |
| 1041 | assert secret_hits == [] |
| 1042 | finally: |
| 1043 | pub_srv.shutdown() |
| 1044 | pub_srv.server_close() |
| 1045 | pub_thread.join(2) |
| 1046 | secret_srv.shutdown() |
| 1047 | secret_srv.server_close() |
| 1048 | secret_thread.join(2) |
| 1049 | |
| 1050 | def test_media_proxy_aborts_chunked_stream_mid_transfer_at_max_bytes(self) -> None: |
| 1051 | bytes_written = [0] |
| 1052 | # 64 MiB exceeds loopback kernel TCP buffers so the server cannot finish before proxy abort. |
| 1053 | total_stream_bytes = 64 * 1024 * 1024 |
| 1054 | stop_event = threading.Event() |
| 1055 | |
| 1056 | class ChunkedHandler(BaseHTTPRequestHandler): |
| 1057 | protocol_version = "HTTP/1.1" |
| 1058 | |
| 1059 | def log_message(self, *args): |
| 1060 | pass |
| 1061 | |
| 1062 | def do_GET(self): |
| 1063 | self.send_response(200) |
| 1064 | self.send_header("Transfer-Encoding", "chunked") |
| 1065 | self.end_headers() |
| 1066 | payload = b"A" * 32768 |
| 1067 | frame = f"{len(payload):x}\r\n".encode("ascii") + payload + b"\r\n" |
| 1068 | remaining = total_stream_bytes |
| 1069 | try: |
| 1070 | while remaining > 0 and not stop_event.is_set(): |
| 1071 | self.wfile.write(frame) |
| 1072 | self.wfile.flush() |
| 1073 | bytes_written[0] += len(payload) |
| 1074 | remaining -= len(payload) |
| 1075 | if not stop_event.is_set(): |
| 1076 | self.wfile.write(b"0\r\n\r\n") |
| 1077 | except (BrokenPipeError, ConnectionResetError, OSError): |
| 1078 | pass |
| 1079 | |
| 1080 | srv = ThreadingHTTPServer(("127.0.0.1", 0), ChunkedHandler) |
| 1081 | srv.daemon_threads = True |
| 1082 | thread = threading.Thread(target=srv.serve_forever, daemon=True) |
| 1083 | thread.start() |
| 1084 | |
| 1085 | def hybrid_resolver(host: str, port: int): |
| 1086 | if host == "stream.test": |
| 1087 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", srv.server_port))] |
| 1088 | return public_host.resolve_public_addresses(host, port) |
| 1089 | |
| 1090 | try: |
| 1091 | with transcribe._PublicMediaProxy(max_bytes=4096, resolver=hybrid_resolver) as proxy: |
| 1092 | with socket.create_connection(("127.0.0.1", proxy.port), timeout=5) as sock: |
| 1093 | sock.sendall(b"GET http://stream.test/live HTTP/1.1\r\nHost: stream.test\r\n\r\n") |
| 1094 | received = bytearray() |
| 1095 | try: |
| 1096 | while True: |
| 1097 | chunk = sock.recv(4096) |
| 1098 | if not chunk: |
| 1099 | break |
| 1100 | received.extend(chunk) |
| 1101 | except OSError: |
| 1102 | pass |
| 1103 | assert proxy.limit_exceeded is True |
| 1104 | assert len(received) <= 4096 |
| 1105 | assert bytes_written[0] < total_stream_bytes |
| 1106 | |
| 1107 | # Subsequent requests after limit_exceeded return 413 immediately. |
| 1108 | with socket.create_connection(("127.0.0.1", proxy.port), timeout=5) as sock: |
| 1109 | sock.sendall(b"GET http://stream.test/next HTTP/1.1\r\nHost: stream.test\r\n\r\n") |
| 1110 | reply = sock.recv(1024).decode("latin-1") |
| 1111 | assert reply.startswith("HTTP/1.1 413") |
| 1112 | finally: |
| 1113 | stop_event.set() |
| 1114 | srv.shutdown() |
| 1115 | srv.server_close() |
| 1116 | thread.join(2) |
| 1117 | |
| 1118 | def test_media_proxy_aborts_connect_tunnel_mid_transfer_at_max_bytes(self) -> None: |
| 1119 | upstream_srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 1120 | upstream_srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 1121 | upstream_srv.bind(("127.0.0.1", 0)) |
| 1122 | upstream_srv.listen(4) |
| 1123 | upstream_port = upstream_srv.getsockname()[1] |
| 1124 | bytes_written = [0] |
| 1125 | total_bytes = 64 * 1024 * 1024 |
| 1126 | stop_event = threading.Event() |
| 1127 | |
| 1128 | def serve_stream() -> None: |
| 1129 | upstream_srv.settimeout(2.0) |
| 1130 | try: |
| 1131 | conn, _ = upstream_srv.accept() |
| 1132 | except OSError: |
| 1133 | return |
| 1134 | with conn: |
| 1135 | chunk = b"B" * 32768 |
| 1136 | remaining = total_bytes |
| 1137 | try: |
| 1138 | while remaining > 0 and not stop_event.is_set(): |
| 1139 | conn.sendall(chunk) |
| 1140 | bytes_written[0] += len(chunk) |
| 1141 | remaining -= len(chunk) |
| 1142 | except OSError: |
| 1143 | pass |
| 1144 | |
| 1145 | thread = threading.Thread(target=serve_stream, daemon=True) |
| 1146 | thread.start() |
| 1147 | |
| 1148 | def hybrid_resolver(host: str, port: int): |
| 1149 | if host == "tunnel.test": |
| 1150 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", upstream_port))] |
| 1151 | return public_host.resolve_public_addresses(host, port) |
| 1152 | |
| 1153 | try: |
| 1154 | with transcribe._PublicMediaProxy(max_bytes=4096, resolver=hybrid_resolver) as proxy: |
| 1155 | with socket.create_connection(("127.0.0.1", proxy.port), timeout=5) as sock: |
| 1156 | sock.sendall(b"CONNECT tunnel.test:443 HTTP/1.1\r\nHost: tunnel.test:443\r\n\r\n") |
| 1157 | buf = bytearray() |
| 1158 | while b"\r\n\r\n" not in buf: |
| 1159 | part = sock.recv(1024) |
| 1160 | assert part |
| 1161 | buf.extend(part) |
| 1162 | header, _, tail = bytes(buf).partition(b"\r\n\r\n") |
| 1163 | assert header.startswith(b"HTTP/1.1 200") |
| 1164 | received = bytearray(tail) |
| 1165 | try: |
| 1166 | while True: |
| 1167 | part = sock.recv(4096) |
| 1168 | if not part: |
| 1169 | break |
| 1170 | received.extend(part) |
| 1171 | except OSError: |
| 1172 | pass |
| 1173 | assert proxy.limit_exceeded is True |
| 1174 | assert len(received) <= 4096 |
| 1175 | assert bytes_written[0] < total_bytes |
| 1176 | finally: |
| 1177 | stop_event.set() |
| 1178 | upstream_srv.close() |
| 1179 | thread.join(2) |
| 1180 | |
| 1181 | @pytest.mark.skipif(shutil.which("yt-dlp") is None, reason="yt-dlp binary not installed") |
| 1182 | def test_real_ytdlp_cannot_ssrf_via_redirect_or_hls_through_media_proxy( |
| 1183 | self, tmp_path: Path, |
| 1184 | ) -> None: |
| 1185 | secret_hits: list[str] = [] |
| 1186 | public_hits: list[str] = [] |
| 1187 | |
| 1188 | class SecretHandler(BaseHTTPRequestHandler): |
| 1189 | def log_message(self, *args): |
| 1190 | pass |
| 1191 | |
| 1192 | def do_GET(self): |
| 1193 | secret_hits.append(self.path) |
| 1194 | self.send_response(200) |
| 1195 | self.end_headers() |
| 1196 | self.wfile.write(b"SECRET_AUDIO") |
| 1197 | |
| 1198 | secret_srv = ThreadingHTTPServer(("127.0.0.1", 0), SecretHandler) |
| 1199 | secret_srv.daemon_threads = True |
| 1200 | secret_thread = threading.Thread(target=secret_srv.serve_forever, daemon=True) |
| 1201 | secret_thread.start() |
| 1202 | |
| 1203 | class FrontHandler(BaseHTTPRequestHandler): |
| 1204 | def log_message(self, *args): |
| 1205 | pass |
| 1206 | |
| 1207 | def do_GET(self): |
| 1208 | public_hits.append(self.path) |
| 1209 | if self.path == "/redirect": |
| 1210 | self.send_response(302) |
| 1211 | self.send_header("Location", f"http://127.0.0.1:{secret_srv.server_port}/secret.mp3") |
| 1212 | self.send_header("Content-Length", "0") |
| 1213 | self.end_headers() |
| 1214 | elif self.path == "/evil.m3u8": |
| 1215 | body = ( |
| 1216 | "#EXTM3U\n" |
| 1217 | "#EXT-X-VERSION:3\n" |
| 1218 | f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="a",NAME="en",DEFAULT=YES,' |
| 1219 | f'URI="http://127.0.0.1:{secret_srv.server_port}/audio.m3u8"\n' |
| 1220 | '#EXT-X-STREAM-INF:BANDWIDTH=64000,CODECS="mp4a.40.2",AUDIO="a"\n' |
| 1221 | f"http://127.0.0.1:{secret_srv.server_port}/seg_list.m3u8\n" |
| 1222 | ).encode("utf-8") |
| 1223 | self.send_response(200) |
| 1224 | self.send_header("Content-Type", "application/vnd.apple.mpegurl") |
| 1225 | self.send_header("Content-Length", str(len(body))) |
| 1226 | self.end_headers() |
| 1227 | self.wfile.write(body) |
| 1228 | else: |
| 1229 | self.send_response(404) |
| 1230 | self.end_headers() |
| 1231 | |
| 1232 | front_srv = ThreadingHTTPServer(("127.0.0.1", 0), FrontHandler) |
| 1233 | front_srv.daemon_threads = True |
| 1234 | front_thread = threading.Thread(target=front_srv.serve_forever, daemon=True) |
| 1235 | front_thread.start() |
| 1236 | |
| 1237 | def hybrid_resolver(host: str, port: int): |
| 1238 | if host == "public.test": |
| 1239 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("127.0.0.1", front_srv.server_port))] |
| 1240 | return public_host.resolve_public_addresses(host, port) |
| 1241 | |
| 1242 | try: |
| 1243 | with transcribe._PublicMediaProxy(max_bytes=1024 * 1024, resolver=hybrid_resolver) as proxy: |
| 1244 | env = transcribe._sanitized_ytdlp_env(proxy.url) |
| 1245 | ytdlp_bin = shutil.which("yt-dlp") |
| 1246 | assert ytdlp_bin is not None |
| 1247 | # conftest.py overrides HOME to a temp dir; preserve user-site lookup when |
| 1248 | # yt-dlp is installed under a user prefix (e.g., ~/.local/bin/yt-dlp). |
| 1249 | prefix = Path(ytdlp_bin).resolve().parent.parent |
| 1250 | if (prefix / "lib").is_dir(): |
| 1251 | env["PYTHONUSERBASE"] = str(prefix) |
| 1252 | if not transcribe._run([ytdlp_bin, "--ignore-config", "--no-plugin-dirs", "--version"], timeout=10.0, env=env): |
| 1253 | pytest.skip("yt-dlp binary is not runnable under isolated test environment") |
| 1254 | for path in ("/redirect", "/evil.m3u8"): |
| 1255 | before_public = len(public_hits) |
| 1256 | before_blocked = proxy.blocked_count |
| 1257 | out_file = str(tmp_path / f"out_{path.strip('/').replace('.', '_')}.m4a") |
| 1258 | ok = transcribe._run([ |
| 1259 | ytdlp_bin, |
| 1260 | "--ignore-config", |
| 1261 | "--no-plugin-dirs", |
| 1262 | "--no-cookies-from-browser", |
| 1263 | "--no-playlist", |
| 1264 | "--no-live-from-start", |
| 1265 | "--match-filter", "!is_live", |
| 1266 | "--max-filesize", transcribe.MAX_DOWNLOAD_SIZE_ARG, |
| 1267 | "--downloader", "dash,m3u8:native", |
| 1268 | "--proxy", proxy.url, |
| 1269 | "-f", "bestaudio[protocol*=http]/bestaudio[protocol^=m3u8]", |
| 1270 | "-o", out_file, |
| 1271 | "--", |
| 1272 | f"http://public.test{path}", |
| 1273 | ], timeout=15.0, env=env) |
| 1274 | assert ok is False |
| 1275 | assert len(public_hits) > before_public, f"yt-dlp never reached public server for {path}" |
| 1276 | assert proxy.blocked_count > before_blocked, f"proxy never saw blocked follow-up for {path}" |
| 1277 | assert secret_hits == [] |
| 1278 | finally: |
| 1279 | front_srv.shutdown() |
| 1280 | front_srv.server_close() |
| 1281 | front_thread.join(2) |
| 1282 | secret_srv.shutdown() |
| 1283 | secret_srv.server_close() |
| 1284 | secret_thread.join(2) |
| 1285 | |
| 1286 | @pytest.mark.parametrize("filename", ["http_clip.mp3", "-leading_dash.mp3"]) |
| 1287 | def test_local_files_with_http_prefix_or_leading_dash_handled_safely( |
| 1288 | self, tmp_path: Path, monkeypatch, filename: str, |
| 1289 | ) -> None: |
| 1290 | clip = tmp_path / filename |
| 1291 | clip.write_bytes(b"local-audio") |
| 1292 | workdir = tmp_path / "work" |
| 1293 | workdir.mkdir() |
| 1294 | monkeypatch.chdir(tmp_path) |
| 1295 | cmds: list[list[str]] = [] |
| 1296 | |
| 1297 | def fake_run(cmd, timeout=120.0): |
| 1298 | cmds.append(cmd) |
| 1299 | Path(cmd[-1]).write_bytes(b"mp3") |
| 1300 | return True |
| 1301 | |
| 1302 | with mock.patch.object(transcribe, "_run", side_effect=fake_run): |
| 1303 | out = transcribe._acquire_audio(filename, str(workdir), timeout=30.0) |
| 1304 | |
| 1305 | assert out is not None |
| 1306 | assert len(cmds) == 1 |
| 1307 | assert cmds[0][0] == "ffmpeg" |
| 1308 | i_arg = cmds[0][cmds[0].index("-i") + 1] |
| 1309 | assert os.path.isabs(i_arg) |
| 1310 | assert not i_arg.startswith("-") |
| 1311 | assert Path(i_arg) == clip.resolve() |
| 1312 | |
| 1313 | def test_chunk_audio_ffmpeg_uses_nostdin_and_file_protocol_whitelist( |
| 1314 | self, tmp_path: Path, monkeypatch, |
| 1315 | ) -> None: |
| 1316 | monkeypatch.setattr(transcribe, "MAX_UPLOAD_BYTES", 5) |
| 1317 | audio = tmp_path / "audio.mp3" |
| 1318 | audio.write_bytes(b"0123456789") |
| 1319 | cmds: list[list[str]] = [] |
| 1320 | |
| 1321 | def fake_run(cmd, timeout=120.0): |
| 1322 | cmds.append(cmd) |
| 1323 | (tmp_path / "chunk_000.mp3").write_bytes(b"01234") |
| 1324 | return True |
| 1325 | |
| 1326 | with mock.patch.object(transcribe, "_run", side_effect=fake_run): |
| 1327 | chunks = transcribe._chunk_audio(str(audio), str(tmp_path)) |
| 1328 | |
| 1329 | assert len(chunks) == 1 |
| 1330 | assert len(cmds) == 1 |
| 1331 | cmd = cmds[0] |
| 1332 | assert "-nostdin" in cmd |
| 1333 | wl_idx = cmd.index("-protocol_whitelist") |
| 1334 | i_idx = cmd.index("-i") |
| 1335 | assert cmd[wl_idx + 1] == "file" |
| 1336 | assert wl_idx < i_idx |
| 1337 | |
| 1338 | |
| 1339 | # --------------------------------------------------------------------------- |
| 1340 | # HIGH-181: bluesky.py BSKY_SEARCH_HOST validation & JWT protection |
| 1341 | # --------------------------------------------------------------------------- |
| 1342 | |
| 1343 | |
| 1344 | class TestHigh181BlueskySearchHostHardening: |
| 1345 | @pytest.fixture(autouse=True) |
| 1346 | def _clean_bluesky_state(self, monkeypatch): |
| 1347 | bluesky._reset_session_cache() |
| 1348 | monkeypatch.delenv("BSKY_SEARCH_HOST", raising=False) |
| 1349 | yield |
| 1350 | bluesky._reset_session_cache() |
| 1351 | |
| 1352 | @pytest.mark.parametrize( |
| 1353 | "bad_host", |
| 1354 | [ |
| 1355 | "api.bsky.app@attacker.example", |
| 1356 | "user:pass@api.bsky.app", |
| 1357 | "attacker.example?x=1", |
| 1358 | "attacker.example#frag", |
| 1359 | "attacker.example\\evil", |
| 1360 | "api.bsky.app\t.evil.com", |
| 1361 | "api.bsky.app\r\nX-Injected: 1", |
| 1362 | "169.254.169.254", |
| 1363 | "127.0.0.1", |
| 1364 | "127.0.0.1:8080", |
| 1365 | "10.0.0.1", |
| 1366 | "8.8.8.8", |
| 1367 | "[::1]", |
| 1368 | "::1", |
| 1369 | "2130706433", |
| 1370 | "0177.0.0.1", |
| 1371 | "0x7f.0.0.1", |
| 1372 | "localhost", |
| 1373 | "sub.localhost", |
| 1374 | "printer.local", |
| 1375 | "metadata.google.internal", |
| 1376 | "host.localdomain", |
| 1377 | "router.home.arpa", |
| 1378 | "http://api.bsky.app", |
| 1379 | "file:///etc/passwd", |
| 1380 | "https://https://api.bsky.app", |
| 1381 | "api.bsky.app:8443", |
| 1382 | "api.bsky.app:443", |
| 1383 | "api.bsky.app/xrpc/evil", |
| 1384 | "https://api.bsky.app//", |
| 1385 | "аpi.bsky.app", |
| 1386 | "-bad.bsky.app", |
| 1387 | "bad-.bsky.app", |
| 1388 | "singlelabel", |
| 1389 | " ", |
| 1390 | ], |
| 1391 | ) |
| 1392 | def test_malicious_bsky_search_host_falls_back_to_default( |
| 1393 | self, monkeypatch, bad_host: str, |
| 1394 | ) -> None: |
| 1395 | monkeypatch.setenv("BSKY_SEARCH_HOST", bad_host) |
| 1396 | url = bluesky._resolve_search_url() |
| 1397 | assert url == "https://api.bsky.app/xrpc/app.bsky.feed.searchPosts" |
| 1398 | |
| 1399 | def test_invalid_bsky_search_host_warning_redacts_raw_value( |
| 1400 | self, monkeypatch, capsys, |
| 1401 | ) -> None: |
| 1402 | monkeypatch.setenv( |
| 1403 | "BSKY_SEARCH_HOST", "https://user:secretpass@evil.example/?sig=tok123", |
| 1404 | ) |
| 1405 | url = bluesky._resolve_search_url() |
| 1406 | assert url == "https://api.bsky.app/xrpc/app.bsky.feed.searchPosts" |
| 1407 | err = capsys.readouterr().err |
| 1408 | assert "BSKY_SEARCH_HOST" in err |
| 1409 | assert "api.bsky.app" in err |
| 1410 | for leaked in ("secretpass", "tok123", "evil.example", "user:"): |
| 1411 | assert leaked not in err |
| 1412 | |
| 1413 | def test_poisoned_host_never_receives_bearer_jwt_in_search(self, monkeypatch) -> None: |
| 1414 | monkeypatch.setenv("BSKY_SEARCH_HOST", "api.bsky.app@attacker.example") |
| 1415 | config = {"BSKY_HANDLE": "user.bsky.social", "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop"} |
| 1416 | |
| 1417 | with mock.patch.object( |
| 1418 | bluesky.http, |
| 1419 | "request", |
| 1420 | side_effect=[{"accessJwt": "live-jwt", "refreshJwt": "live-ref"}, {"posts": []}], |
| 1421 | ) as req_mock: |
| 1422 | result = bluesky.search_bluesky("ai", "2026-06-01", "2026-06-30", config=config) |
| 1423 | |
| 1424 | assert result == {"posts": []} |
| 1425 | search_url = req_mock.call_args_list[1].args[1] |
| 1426 | assert search_url.startswith("https://api.bsky.app/xrpc/app.bsky.feed.searchPosts?") |
| 1427 | assert "attacker.example" not in search_url |
| 1428 | |
| 1429 | def test_untrusted_third_party_fqdn_never_receives_bsky_social_jwt(self) -> None: |
| 1430 | config = { |
| 1431 | "BSKY_HANDLE": "user.bsky.social", |
| 1432 | "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop", |
| 1433 | "BSKY_SEARCH_HOST": "attacker.example", |
| 1434 | } |
| 1435 | with mock.patch.object(bluesky.http, "request", return_value={"posts": []}) as req_mock: |
| 1436 | result = bluesky.search_bluesky("ai", "2026-06-01", "2026-06-30", config=config) |
| 1437 | |
| 1438 | assert result == {"posts": []} |
| 1439 | # Must NOT call createSession and must NOT send Authorization header. |
| 1440 | assert req_mock.call_count == 1 |
| 1441 | call = req_mock.call_args_list[0] |
| 1442 | assert call.args[0] == "GET" |
| 1443 | assert call.args[1].startswith("https://attacker.example/xrpc/app.bsky.feed.searchPosts?") |
| 1444 | assert "headers" not in call.kwargs or "Authorization" not in call.kwargs["headers"] |
| 1445 | assert call.kwargs.get("public_only") is True |
| 1446 | guard = call.kwargs.get("redirect_guard") |
| 1447 | assert callable(guard) |
| 1448 | assert guard("https://attacker.example/xrpc/app.bsky.feed.searchPosts") is True |
| 1449 | assert guard("https://other.example/steal") is False |
| 1450 | assert guard("http://attacker.example/downgrade") is False |
| 1451 | assert guard("https://169.254.169.254/latest") is False |
| 1452 | |
| 1453 | def test_untrusted_host_401_does_not_trigger_bsky_session_refresh(self) -> None: |
| 1454 | config = { |
| 1455 | "BSKY_HANDLE": "user.bsky.social", |
| 1456 | "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop", |
| 1457 | "BSKY_SEARCH_HOST": "pds.example.com", |
| 1458 | } |
| 1459 | with mock.patch.object( |
| 1460 | bluesky.http, |
| 1461 | "request", |
| 1462 | side_effect=http.HTTPError("HTTP 401: Unauthorized", 401, ""), |
| 1463 | ) as req_mock: |
| 1464 | result = bluesky.search_bluesky("ai", "2026-06-01", "2026-06-30", config=config) |
| 1465 | |
| 1466 | assert req_mock.call_count == 1 |
| 1467 | assert result["posts"] == [] |
| 1468 | assert "pds.example.com" in result["error"] |
| 1469 | |
| 1470 | def test_trusted_bsky_subdomain_receives_bearer_with_redirect_guard(self) -> None: |
| 1471 | config = { |
| 1472 | "BSKY_HANDLE": "user.bsky.social", |
| 1473 | "BSKY_APP_PASSWORD": "abcd-efgh-ijkl-mnop", |
| 1474 | "BSKY_SEARCH_HOST": "staging.bsky.app", |
| 1475 | } |
| 1476 | with mock.patch.object( |
| 1477 | bluesky.http, |
| 1478 | "request", |
| 1479 | side_effect=[{"accessJwt": "tok-staging", "refreshJwt": "ref"}, {"posts": []}], |
| 1480 | ) as req_mock: |
| 1481 | result = bluesky.search_bluesky("ai", "2026-06-01", "2026-06-30", config=config) |
| 1482 | |
| 1483 | assert result == {"posts": []} |
| 1484 | assert req_mock.call_count == 2 |
| 1485 | search_call = req_mock.call_args_list[1] |
| 1486 | assert search_call.args[1].startswith("https://staging.bsky.app/xrpc/app.bsky.feed.searchPosts?") |
| 1487 | assert search_call.kwargs["headers"] == {"Authorization": "Bearer tok-staging"} |
| 1488 | guard = search_call.kwargs["redirect_guard"] |
| 1489 | assert guard("https://staging.bsky.app/next") is True |
| 1490 | assert guard("https://evil.example/steal") is False |
| 1491 | assert guard("http://staging.bsky.app/downgrade") is False |
| 1492 |