| 1 | """Regression tests for PR06: HTTP response bounds, entity/keyless SSRF, and robots ReDoS.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import http.client as http_client |
| 6 | import io |
| 7 | import json |
| 8 | import os |
| 9 | import socket |
| 10 | import tempfile |
| 11 | import threading |
| 12 | import time |
| 13 | import urllib.error |
| 14 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 15 | from unittest.mock import MagicMock, patch |
| 16 | from urllib.request import Request |
| 17 | |
| 18 | import pytest |
| 19 | |
| 20 | from lib import bounded_get, company_resolve, http, public_host, resolve, subproc, web_fetch_keyless |
| 21 | from lib.job_boards import robots |
| 22 | |
| 23 | |
| 24 | # --------------------------------------------------------------------------- |
| 25 | # HIGH-061: Bounded reads in http.py and bounded_get.py + 3xx no-drain |
| 26 | # --------------------------------------------------------------------------- |
| 27 | |
| 28 | |
| 29 | def _start_server(handler_cls): |
| 30 | server = ThreadingHTTPServer(("127.0.0.1", 0), handler_cls) |
| 31 | server.daemon_threads = True |
| 32 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 33 | thread.start() |
| 34 | return server, thread, f"http://127.0.0.1:{server.server_port}" |
| 35 | |
| 36 | |
| 37 | def _stop_server(server, thread): |
| 38 | server.shutdown() |
| 39 | server.server_close() |
| 40 | thread.join(2) |
| 41 | |
| 42 | |
| 43 | def test_http_request_rejects_oversized_body_by_content_length_without_retrying(): |
| 44 | hits = [] |
| 45 | |
| 46 | class Handler(BaseHTTPRequestHandler): |
| 47 | def log_message(self, *_args): |
| 48 | pass |
| 49 | |
| 50 | def do_GET(self): |
| 51 | hits.append(self.path) |
| 52 | payload = b"A" * 4096 |
| 53 | self.send_response(200) |
| 54 | self.send_header("Content-Length", str(len(payload))) |
| 55 | self.end_headers() |
| 56 | try: |
| 57 | self.wfile.write(payload) |
| 58 | except (BrokenPipeError, ConnectionResetError): |
| 59 | pass |
| 60 | |
| 61 | server, thread, base = _start_server(Handler) |
| 62 | try: |
| 63 | with pytest.raises(http.ResponseTooLarge) as exc_info: |
| 64 | http.request("GET", f"{base}/big", raw=True, retries=3, max_bytes=1024) |
| 65 | assert isinstance(exc_info.value, http.HTTPError) |
| 66 | assert len(hits) == 1 |
| 67 | assert http.get_text(f"{base}/big", retries=2, max_bytes=1024) is None |
| 68 | finally: |
| 69 | _stop_server(server, thread) |
| 70 | |
| 71 | |
| 72 | def test_http_request_rejects_oversized_chunked_stream_without_reading_all(): |
| 73 | bytes_sent = [0] |
| 74 | |
| 75 | class Handler(BaseHTTPRequestHandler): |
| 76 | protocol_version = "HTTP/1.1" |
| 77 | |
| 78 | def log_message(self, *_args): |
| 79 | pass |
| 80 | |
| 81 | def do_GET(self): |
| 82 | self.send_response(200) |
| 83 | self.send_header("Transfer-Encoding", "chunked") |
| 84 | self.end_headers() |
| 85 | chunk = b"x" * 1024 |
| 86 | try: |
| 87 | for _ in range(512): |
| 88 | self.wfile.write(f"{len(chunk):x}\r\n".encode() + chunk + b"\r\n") |
| 89 | self.wfile.flush() |
| 90 | bytes_sent[0] += len(chunk) |
| 91 | self.wfile.write(b"0\r\n\r\n") |
| 92 | except (BrokenPipeError, ConnectionResetError, OSError): |
| 93 | pass |
| 94 | |
| 95 | server, thread, base = _start_server(Handler) |
| 96 | try: |
| 97 | with pytest.raises(http.ResponseTooLarge): |
| 98 | http.request("GET", f"{base}/stream", raw=True, retries=3, max_bytes=2048) |
| 99 | finally: |
| 100 | _stop_server(server, thread) |
| 101 | |
| 102 | |
| 103 | def test_http_request_passes_bounded_read_size_and_never_falls_back_unbounded(): |
| 104 | observed_sizes: list[int] = [] |
| 105 | |
| 106 | class SizedResp: |
| 107 | status = 200 |
| 108 | headers = {} |
| 109 | |
| 110 | def __init__(self, payload: bytes): |
| 111 | self._payload = payload |
| 112 | |
| 113 | def __enter__(self): |
| 114 | return self |
| 115 | |
| 116 | def __exit__(self, *_args): |
| 117 | return False |
| 118 | |
| 119 | def read(self, size=-1): |
| 120 | observed_sizes.append(size) |
| 121 | return self._payload[:size] if size >= 0 else self._payload |
| 122 | |
| 123 | with patch("lib.http.urllib.request.urlopen", return_value=SizedResp(b"hello")): |
| 124 | assert http.request("GET", "https://example.com/ok", raw=True, retries=1, max_bytes=10) == "hello" |
| 125 | assert observed_sizes == [11] |
| 126 | |
| 127 | with patch("lib.http.urllib.request.urlopen", return_value=SizedResp(b"0123456789X")): |
| 128 | with pytest.raises(http.ResponseTooLarge): |
| 129 | http.request("GET", "https://example.com/big", raw=True, retries=3, max_bytes=10) |
| 130 | |
| 131 | class ZeroArgResp: |
| 132 | status = 200 |
| 133 | headers = {} |
| 134 | unbounded_called = False |
| 135 | |
| 136 | def __enter__(self): |
| 137 | return self |
| 138 | |
| 139 | def __exit__(self, *_args): |
| 140 | return False |
| 141 | |
| 142 | def read(self): |
| 143 | self.unbounded_called = True |
| 144 | return b"should-not-run" |
| 145 | |
| 146 | zero_arg = ZeroArgResp() |
| 147 | with patch("lib.http.urllib.request.urlopen", return_value=zero_arg): |
| 148 | with pytest.raises(TypeError): |
| 149 | http.request("GET", "https://example.com/zero", raw=True, retries=1, max_bytes=10) |
| 150 | assert zero_arg.unbounded_called is False |
| 151 | |
| 152 | |
| 153 | def test_http_head_request_allows_large_content_length_header(): |
| 154 | class HeadHandler(BaseHTTPRequestHandler): |
| 155 | def log_message(self, *_args): |
| 156 | pass |
| 157 | |
| 158 | def do_HEAD(self): |
| 159 | self.send_response(200) |
| 160 | self.send_header("Content-Length", "999999999") |
| 161 | self.send_header("Content-Type", "application/octet-stream") |
| 162 | self.end_headers() |
| 163 | |
| 164 | server, thread, base = _start_server(HeadHandler) |
| 165 | try: |
| 166 | body, headers = http.request( |
| 167 | "HEAD", f"{base}/large.bin", raw=True, retries=1, max_bytes=1024, return_headers=True, |
| 168 | ) |
| 169 | assert body == "" |
| 170 | assert headers.get("content-length") == "999999999" |
| 171 | finally: |
| 172 | _stop_server(server, thread) |
| 173 | |
| 174 | |
| 175 | def test_http_request_truncates_oversized_error_body_and_preserves_status(): |
| 176 | huge_error = b"E" * (http.MAX_ERROR_BODY_BYTES + 20_000) |
| 177 | err = urllib.error.HTTPError( |
| 178 | "https://example.com/fail", 500, "Server Error", {}, io.BytesIO(huge_error), |
| 179 | ) |
| 180 | with patch("lib.http.urllib.request.urlopen", side_effect=err): |
| 181 | with pytest.raises(http.HTTPError) as exc_info: |
| 182 | http.request("GET", "https://example.com/fail", retries=1) |
| 183 | assert exc_info.value.status_code == 500 |
| 184 | assert exc_info.value.body is not None |
| 185 | assert len(exc_info.value.body.encode("utf-8")) == http.MAX_ERROR_BODY_BYTES |
| 186 | |
| 187 | |
| 188 | def test_http_redirect_handler_closes_without_draining_3xx_body(): |
| 189 | class TrapFP: |
| 190 | def __init__(self): |
| 191 | self.closed = False |
| 192 | |
| 193 | def read(self, *_args, **_kwargs): |
| 194 | raise AssertionError("redirect handler must not call fp.read()") |
| 195 | |
| 196 | def close(self): |
| 197 | self.closed = True |
| 198 | |
| 199 | handler = http._StripAuthOnCrossOriginRedirect() |
| 200 | parent = MagicMock() |
| 201 | parent.open.return_value = "redirected-response" |
| 202 | handler.parent = parent |
| 203 | |
| 204 | for code in (301, 302, 303, 307, 308): |
| 205 | fp = TrapFP() |
| 206 | req = Request("https://example.com/start") |
| 207 | req.timeout = 5 |
| 208 | method = getattr(handler, f"http_error_{code}") |
| 209 | out = method(req, fp, code, "Redirect", {"location": "https://example.com/dest"}) |
| 210 | assert out == "redirected-response" |
| 211 | assert fp.closed is True |
| 212 | |
| 213 | |
| 214 | def test_http_redirect_live_server_does_not_hang_on_stalled_302_body(): |
| 215 | release = threading.Event() |
| 216 | |
| 217 | class Handler(BaseHTTPRequestHandler): |
| 218 | def log_message(self, *_args): |
| 219 | pass |
| 220 | |
| 221 | def do_GET(self): |
| 222 | if self.path == "/redir": |
| 223 | self.send_response(302) |
| 224 | self.send_header("Location", "/final") |
| 225 | self.send_header("Content-Length", "104857600") |
| 226 | self.end_headers() |
| 227 | release.wait(5) |
| 228 | return |
| 229 | body = b'{"ok":true}' |
| 230 | self.send_response(200) |
| 231 | self.send_header("Content-Length", str(len(body))) |
| 232 | self.end_headers() |
| 233 | self.wfile.write(body) |
| 234 | |
| 235 | server, thread, base = _start_server(Handler) |
| 236 | try: |
| 237 | started = time.monotonic() |
| 238 | assert http.get(f"{base}/redir", timeout=3, retries=1) == {"ok": True} |
| 239 | assert time.monotonic() - started < 1.5 |
| 240 | finally: |
| 241 | release.set() |
| 242 | _stop_server(server, thread) |
| 243 | |
| 244 | |
| 245 | def test_http_and_bounded_get_reject_non_positive_max_bytes(): |
| 246 | with pytest.raises(ValueError): |
| 247 | http.request("GET", "https://example.com/", max_bytes=0) |
| 248 | with pytest.raises(ValueError): |
| 249 | http.request("GET", "https://example.com/", max_bytes=-5) |
| 250 | with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: |
| 251 | sock.bind(("127.0.0.1", 0)) |
| 252 | port = sock.getsockname()[1] |
| 253 | with pytest.raises(ValueError): |
| 254 | bounded_get.get( |
| 255 | Request(f"http://127.0.0.1:{port}/"), |
| 256 | timeout=1, |
| 257 | deadline_monotonic=time.monotonic() + 2, |
| 258 | max_bytes=0, |
| 259 | ) |
| 260 | |
| 261 | |
| 262 | def test_http_and_bounded_get_allow_exact_max_bytes_boundary(): |
| 263 | exact = b"X" * 1024 |
| 264 | |
| 265 | class Handler(BaseHTTPRequestHandler): |
| 266 | def log_message(self, *_args): |
| 267 | pass |
| 268 | |
| 269 | def do_GET(self): |
| 270 | self.send_response(200) |
| 271 | self.send_header("Content-Length", str(len(exact))) |
| 272 | self.end_headers() |
| 273 | self.wfile.write(exact) |
| 274 | |
| 275 | server, thread, base = _start_server(Handler) |
| 276 | try: |
| 277 | assert http.request("GET", f"{base}/exact", raw=True, retries=1, max_bytes=1024) == exact.decode() |
| 278 | status, body, err = bounded_get.get( |
| 279 | Request(f"{base}/exact"), |
| 280 | timeout=3, |
| 281 | deadline_monotonic=time.monotonic() + 5, |
| 282 | max_bytes=1024, |
| 283 | ) |
| 284 | assert (status, body, err) == (200, exact, None) |
| 285 | finally: |
| 286 | _stop_server(server, thread) |
| 287 | |
| 288 | |
| 289 | def test_bounded_get_streams_body_via_temp_file_caps_size_and_cleans_up(tmp_path, monkeypatch): |
| 290 | monkeypatch.setenv("TMPDIR", str(tmp_path)) |
| 291 | monkeypatch.setenv("TMP", str(tmp_path)) |
| 292 | monkeypatch.setenv("TEMP", str(tmp_path)) |
| 293 | monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) |
| 294 | |
| 295 | class Handler(BaseHTTPRequestHandler): |
| 296 | protocol_version = "HTTP/1.1" |
| 297 | |
| 298 | def log_message(self, *_args): |
| 299 | pass |
| 300 | |
| 301 | def do_GET(self): |
| 302 | if self.path == "/ok": |
| 303 | body = b'{"payload":"' + (b"x" * 2048) + b'"}' |
| 304 | self.send_response(200) |
| 305 | self.send_header("Content-Length", str(len(body))) |
| 306 | self.end_headers() |
| 307 | self.wfile.write(body) |
| 308 | return |
| 309 | if self.path == "/too-big-cl": |
| 310 | body = b"B" * 8192 |
| 311 | self.send_response(200) |
| 312 | self.send_header("Content-Length", str(len(body))) |
| 313 | self.end_headers() |
| 314 | try: |
| 315 | self.wfile.write(body) |
| 316 | except (BrokenPipeError, ConnectionResetError): |
| 317 | pass |
| 318 | return |
| 319 | if self.path == "/too-big-chunked": |
| 320 | self.send_response(200) |
| 321 | self.send_header("Transfer-Encoding", "chunked") |
| 322 | self.end_headers() |
| 323 | chunk = b"C" * 1024 |
| 324 | try: |
| 325 | for _ in range(16): |
| 326 | self.wfile.write(f"{len(chunk):x}\r\n".encode() + chunk + b"\r\n") |
| 327 | self.wfile.flush() |
| 328 | self.wfile.write(b"0\r\n\r\n") |
| 329 | except (BrokenPipeError, ConnectionResetError, OSError): |
| 330 | pass |
| 331 | return |
| 332 | if self.path == "/huge-error": |
| 333 | # Split a 3-byte UTF-8 character across the 64 KiB truncation boundary. |
| 334 | body = (b"Z" * (bounded_get.MAX_ERROR_BODY_BYTES - 1)) + "€".encode("utf-8") + (b"Z" * 1024) |
| 335 | self.send_response(403) |
| 336 | self.send_header("Content-Length", str(len(body))) |
| 337 | self.end_headers() |
| 338 | try: |
| 339 | self.wfile.write(body) |
| 340 | except (BrokenPipeError, ConnectionResetError): |
| 341 | pass |
| 342 | return |
| 343 | if self.path == "/truncated-error": |
| 344 | self.send_response(500) |
| 345 | self.send_header("Content-Length", "500") |
| 346 | self.end_headers() |
| 347 | self.wfile.write(b"partial-err") |
| 348 | self.close_connection = True |
| 349 | return |
| 350 | |
| 351 | server, thread, base = _start_server(Handler) |
| 352 | capture_limits = [] |
| 353 | stdout_sizes = [] |
| 354 | real_run = subproc.run_with_timeout |
| 355 | |
| 356 | def spy_run(*args, **kwargs): |
| 357 | capture_limits.append(kwargs.get("capture_limit_bytes")) |
| 358 | res = real_run(*args, **kwargs) |
| 359 | stdout_sizes.append(len(res.stdout)) |
| 360 | return res |
| 361 | |
| 362 | try: |
| 363 | with patch.object(bounded_get.subproc, "run_with_timeout", side_effect=spy_run): |
| 364 | status, body, err = bounded_get.get( |
| 365 | Request(f"{base}/ok"), |
| 366 | timeout=3, |
| 367 | deadline_monotonic=time.monotonic() + 5, |
| 368 | max_bytes=4096, |
| 369 | ) |
| 370 | assert status == 200 |
| 371 | assert err is None |
| 372 | assert body is not None and len(body) > 2048 |
| 373 | assert capture_limits[-1] == bounded_get.MAX_META_BYTES |
| 374 | # Metadata JSON on stdout must not embed the 2 KiB+ body. |
| 375 | assert stdout_sizes[-1] < 512 |
| 376 | |
| 377 | with pytest.raises(bounded_get.ResponseTooLarge): |
| 378 | bounded_get.get( |
| 379 | Request(f"{base}/too-big-cl"), |
| 380 | timeout=3, |
| 381 | deadline_monotonic=time.monotonic() + 5, |
| 382 | max_bytes=1024, |
| 383 | ) |
| 384 | |
| 385 | with pytest.raises(bounded_get.ResponseTooLarge): |
| 386 | bounded_get.get( |
| 387 | Request(f"{base}/too-big-chunked"), |
| 388 | timeout=3, |
| 389 | deadline_monotonic=time.monotonic() + 5, |
| 390 | max_bytes=1024, |
| 391 | ) |
| 392 | |
| 393 | # Owned GET through http.request fails fast with ResponseTooLarge without retrying. |
| 394 | with pytest.raises(http.ResponseTooLarge): |
| 395 | http.get( |
| 396 | f"{base}/too-big-chunked", |
| 397 | retries=3, |
| 398 | deadline_monotonic=time.monotonic() + 5, |
| 399 | owned_get=True, |
| 400 | max_bytes=1024, |
| 401 | ) |
| 402 | |
| 403 | # Oversized error bodies are truncated to MAX_ERROR_BODY_BYTES, preserving status |
| 404 | # and decoding cleanly with replacement even if truncated mid-UTF-8 codepoint. |
| 405 | status, err_body, http_err = bounded_get.get( |
| 406 | Request(f"{base}/huge-error"), |
| 407 | timeout=3, |
| 408 | deadline_monotonic=time.monotonic() + 5, |
| 409 | ) |
| 410 | assert status == 403 |
| 411 | assert isinstance(http_err, urllib.error.HTTPError) |
| 412 | assert err_body is not None |
| 413 | assert len(err_body) == bounded_get.MAX_ERROR_BODY_BYTES |
| 414 | |
| 415 | with pytest.raises(http.HTTPError) as owned_err: |
| 416 | http.get( |
| 417 | f"{base}/huge-error", |
| 418 | retries=1, |
| 419 | deadline_monotonic=time.monotonic() + 5, |
| 420 | owned_get=True, |
| 421 | ) |
| 422 | assert owned_err.value.status_code == 403 |
| 423 | assert owned_err.value.body is not None |
| 424 | assert owned_err.value.body.startswith("ZZZ") |
| 425 | |
| 426 | # Truncated 500 error body preserves HTTP 500 rather than failing as OSError. |
| 427 | status, trunc_body, trunc_err = bounded_get.get( |
| 428 | Request(f"{base}/truncated-error"), |
| 429 | timeout=3, |
| 430 | deadline_monotonic=time.monotonic() + 5, |
| 431 | ) |
| 432 | assert status == 500 |
| 433 | assert isinstance(trunc_err, urllib.error.HTTPError) |
| 434 | assert trunc_body == b"partial-err" |
| 435 | |
| 436 | assert list(tmp_path.iterdir()) == [] |
| 437 | finally: |
| 438 | _stop_server(server, thread) |
| 439 | |
| 440 | |
| 441 | @pytest.mark.parametrize( |
| 442 | "declared_len,sent_len", |
| 443 | [ |
| 444 | (100, 0), |
| 445 | (bounded_get._STREAM_CHUNK_BYTES + 4096, bounded_get._STREAM_CHUNK_BYTES), |
| 446 | ], |
| 447 | ) |
| 448 | def test_premature_eof_raises_incomplete_read_for_http_and_bounded_get( |
| 449 | declared_len: int, sent_len: int, tmp_path, monkeypatch, |
| 450 | ): |
| 451 | monkeypatch.setenv("TMPDIR", str(tmp_path)) |
| 452 | monkeypatch.setenv("TMP", str(tmp_path)) |
| 453 | monkeypatch.setenv("TEMP", str(tmp_path)) |
| 454 | monkeypatch.setattr(tempfile, "tempdir", str(tmp_path)) |
| 455 | |
| 456 | class TruncatingHandler(BaseHTTPRequestHandler): |
| 457 | protocol_version = "HTTP/1.1" |
| 458 | |
| 459 | def log_message(self, *_args): |
| 460 | pass |
| 461 | |
| 462 | def do_GET(self): |
| 463 | self.send_response(200) |
| 464 | self.send_header("Content-Length", str(declared_len)) |
| 465 | self.end_headers() |
| 466 | if sent_len: |
| 467 | self.wfile.write(b"A" * sent_len) |
| 468 | self.wfile.flush() |
| 469 | self.close_connection = True |
| 470 | |
| 471 | server, thread, base = _start_server(TruncatingHandler) |
| 472 | try: |
| 473 | with pytest.raises(http.HTTPError) as exc_info: |
| 474 | http.request("GET", f"{base}/eof", raw=True, retries=1) |
| 475 | assert "IncompleteRead" in str(exc_info.value) |
| 476 | |
| 477 | with pytest.raises(http_client.IncompleteRead): |
| 478 | bounded_get.get( |
| 479 | Request(f"{base}/eof"), |
| 480 | timeout=3, |
| 481 | deadline_monotonic=time.monotonic() + 5, |
| 482 | ) |
| 483 | assert list(tmp_path.iterdir()) == [] |
| 484 | finally: |
| 485 | _stop_server(server, thread) |
| 486 | |
| 487 | |
| 488 | def test_bounded_get_serialize_headers_caps_control_char_expansion(): |
| 489 | hostile = {"X-Evil": "\x00" * 40_000, "X-Other": "\x01" * 40_000} |
| 490 | serialized = bounded_get._serialize_headers(hostile) |
| 491 | encoded = json.dumps({"headers": serialized}) |
| 492 | assert encoded.isascii() |
| 493 | assert len(encoded) < bounded_get.MAX_META_BYTES |
| 494 | |
| 495 | |
| 496 | def test_bounded_get_serialize_headers_preserves_priority_headers_after_junk(): |
| 497 | raw_headers = {f"X-Junk-{i}": "J" * 1024 for i in range(300)} |
| 498 | raw_headers["Retry-After"] = "42" |
| 499 | raw_headers["X-L30D-Charge-Credits"] = "1.5" |
| 500 | raw_headers["X-RateLimit-Reset"] = "30" |
| 501 | serialized = dict(bounded_get._serialize_headers(raw_headers)) |
| 502 | assert serialized.get("Retry-After") == "42" |
| 503 | assert serialized.get("X-L30D-Charge-Credits") == "1.5" |
| 504 | assert serialized.get("X-RateLimit-Reset") == "30" |
| 505 | assert len(serialized) <= bounded_get._MAX_HEADER_COUNT |
| 506 | assert len(json.dumps(list(serialized.items()))) <= bounded_get._MAX_HEADER_BYTES + 16 |
| 507 | |
| 508 | |
| 509 | def test_bounded_get_main_writes_pure_ascii_json_safe_for_windows_cp1252(monkeypatch): |
| 510 | class NonCp1252Response: |
| 511 | status = 200 |
| 512 | headers = {"X-Raw": "ok\x81\x8d\x8f\x90\x9d", "X-Uni": "snow-\u2603"} |
| 513 | |
| 514 | def __enter__(self): |
| 515 | return self |
| 516 | |
| 517 | def __exit__(self, *_args): |
| 518 | return False |
| 519 | |
| 520 | def geturl(self): |
| 521 | return "https://example.com/\u2603" |
| 522 | |
| 523 | def read(self, *_args): |
| 524 | return b"ok" |
| 525 | |
| 526 | payload = { |
| 527 | "url": "https://example.com/\u2603", |
| 528 | "headers": {}, |
| 529 | "unredirected_headers": {}, |
| 530 | "origin_req_host": "example.com", |
| 531 | "timeout": 2, |
| 532 | "read_body": False, |
| 533 | "read_error_body": False, |
| 534 | "with_headers": True, |
| 535 | "max_bytes": 1024, |
| 536 | "body_path": None, |
| 537 | } |
| 538 | raw_out = io.BytesIO() |
| 539 | cp1252_stdout = io.TextIOWrapper(raw_out, encoding="cp1252") |
| 540 | monkeypatch.setattr(bounded_get.sys, "stdin", io.StringIO(json.dumps(payload))) |
| 541 | monkeypatch.setattr(bounded_get.sys, "stdout", cp1252_stdout) |
| 542 | with patch.object(http, "open_request", return_value=NonCp1252Response()): |
| 543 | bounded_get._main() |
| 544 | cp1252_stdout.flush() |
| 545 | written = raw_out.getvalue() |
| 546 | assert written.isascii() |
| 547 | assert len(written) <= bounded_get.MAX_META_BYTES |
| 548 | parsed = json.loads(written.decode("ascii")) |
| 549 | assert parsed["status"] == 200 |
| 550 | assert dict(parsed["headers"])["X-Raw"] == "ok\x81\x8d\x8f\x90\x9d" |
| 551 | assert dict(parsed["headers"])["X-Uni"] == "snow-\u2603" |
| 552 | |
| 553 | |
| 554 | # --------------------------------------------------------------------------- |
| 555 | # HIGH-086: resolve.py official-site SSRF, ccSLD, redirects & decode safety |
| 556 | # --------------------------------------------------------------------------- |
| 557 | |
| 558 | |
| 559 | @pytest.mark.parametrize( |
| 560 | "bad_site", |
| 561 | [ |
| 562 | "127.0.0.1", |
| 563 | "127.0.0.1:8080", |
| 564 | "http://127.0.0.1:8080/", |
| 565 | "169.254.169.254", |
| 566 | "http://169.254.169.254/latest/meta-data/", |
| 567 | "10.0.0.1", |
| 568 | "8.8.8.8", |
| 569 | "http://[::1]/", |
| 570 | "http://0177.0.0.1/", |
| 571 | "http://2130706433/", |
| 572 | "localhost", |
| 573 | "stripe.localhost", |
| 574 | "https://stripe.localhost/", |
| 575 | "printer.local", |
| 576 | "metadata.google.internal", |
| 577 | "service.localdomain", |
| 578 | "1.0.0.127.in-addr.arpa", |
| 579 | "foo.com:99999", |
| 580 | "foo.com:8080", |
| 581 | "https://foo.com:8443/", |
| 582 | "https://foo.com:80/", |
| 583 | "https://user:pass@stripe.com/", |
| 584 | "https://stripe.com@evil.com/", |
| 585 | "ftp://stripe.com/", |
| 586 | "file:///etc/passwd", |
| 587 | "javascript:alert(1)", |
| 588 | "data:text/html,stripe.com", |
| 589 | "https://stripe.com/\r\nX-Injected: 1", |
| 590 | "//stripe.com", |
| 591 | ], |
| 592 | ) |
| 593 | def test_resolve_official_site_url_rejects_unsafe_inputs(bad_site: str): |
| 594 | assert resolve._official_site_url(bad_site) == "" |
| 595 | |
| 596 | |
| 597 | @pytest.mark.parametrize( |
| 598 | "good_site,expected", |
| 599 | [ |
| 600 | ("typesafe.ai", "https://typesafe.ai/"), |
| 601 | ("https://www.TypeSafe.ai/pricing?x=1", "https://www.typesafe.ai/"), |
| 602 | ("https://example.com:443/about", "https://example.com/"), |
| 603 | ("http://example.com:80/about", "https://example.com/"), |
| 604 | ("stripe.co.uk", "https://stripe.co.uk/"), |
| 605 | ], |
| 606 | ) |
| 607 | def test_resolve_official_site_url_accepts_valid_domains(good_site: str, expected: str): |
| 608 | assert resolve._official_site_url(good_site) == expected |
| 609 | |
| 610 | |
| 611 | def test_resolve_extract_official_domain_rejects_internal_spoofed_and_non_cctld(): |
| 612 | bad_items = [ |
| 613 | {"url": "https://stripe.localhost/", "title": "", "snippet": ""}, |
| 614 | {"url": "https://stripe.local/", "title": "", "snippet": ""}, |
| 615 | {"url": "https://stripe.internal/", "title": "", "snippet": ""}, |
| 616 | {"url": "https://stripe.co.evil/", "title": "", "snippet": ""}, |
| 617 | {"url": "https://stripe.co.com/", "title": "", "snippet": ""}, |
| 618 | {"url": "https://stripe.com.evil/", "title": "", "snippet": ""}, |
| 619 | {"url": "https://stripe.com@attacker.com/", "title": "", "snippet": ""}, |
| 620 | {"url": "https://stripe.com:8080/", "title": "", "snippet": ""}, |
| 621 | {"url": "http://127.0.0.1/", "title": "", "snippet": ""}, |
| 622 | ] |
| 623 | assert resolve._extract_official_domain("Stripe", bad_items) == "" |
| 624 | |
| 625 | good_uk = [{"url": "https://www.stripe.co.uk/pricing", "title": "", "snippet": ""}] |
| 626 | assert resolve._extract_official_domain("Stripe", good_uk) == "stripe.co.uk" |
| 627 | |
| 628 | |
| 629 | def test_resolve_official_site_socials_uses_public_only_redirect_guard_and_handles_decode(): |
| 630 | with patch.object(resolve.http, "get_text", return_value="<html></html>") as mock_get: |
| 631 | resolve.official_site_socials("typesafe.ai") |
| 632 | assert mock_get.call_args.kwargs.get("public_only") is True |
| 633 | guard = mock_get.call_args.kwargs.get("redirect_guard") |
| 634 | assert callable(guard) |
| 635 | assert guard("https://www.typesafe.ai/home") is True |
| 636 | assert guard("http://169.254.169.254/latest/meta-data/") is False |
| 637 | assert guard("http://127.0.0.1:8080/") is False |
| 638 | assert guard("http://metadata.google.internal/") is False |
| 639 | assert guard("https://user:pass@typesafe.ai/") is False |
| 640 | assert guard("file:///etc/passwd") is False |
| 641 | |
| 642 | # Non-UTF-8 homepage bytes or ValueError must return empty socials, not crash. |
| 643 | bad_resp = MagicMock() |
| 644 | bad_resp.__enter__.return_value = bad_resp |
| 645 | bad_resp.__exit__.return_value = False |
| 646 | bad_resp.status = 200 |
| 647 | bad_resp.headers = {} |
| 648 | bad_resp.read.return_value = b"\xff\xfe\x80\x81" |
| 649 | with patch.object(resolve.http, "_open_request", return_value=bad_resp): |
| 650 | assert resolve.official_site_socials("typesafe.ai") == {"x_handle": "", "github_user": ""} |
| 651 | |
| 652 | with patch.object(resolve.http, "get_text", side_effect=ValueError("invalid port")): |
| 653 | assert resolve.official_site_socials("typesafe.ai") == {"x_handle": "", "github_user": ""} |
| 654 | |
| 655 | |
| 656 | def test_resolve_official_site_socials_blocks_private_dns_and_private_redirect(monkeypatch): |
| 657 | def fake_getaddrinfo(name, port, *_args, **_kwargs): |
| 658 | return [(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("169.254.169.254", port or 443))] |
| 659 | |
| 660 | monkeypatch.setattr(public_host.socket, "getaddrinfo", fake_getaddrinfo) |
| 661 | assert resolve.official_site_socials("stripe.xyz") == {"x_handle": "", "github_user": ""} |
| 662 | |
| 663 | # Verify redirect handler refuses private/metadata targets when public_only + guard are attached. |
| 664 | handler = http._StripAuthOnCrossOriginRedirect() |
| 665 | req = Request("https://stripe.xyz/") |
| 666 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 667 | setattr(req, http._REDIRECT_GUARD_ATTR, resolve._official_site_redirect_guard) |
| 668 | for bad_target in ( |
| 669 | "http://169.254.169.254/latest/meta-data/", |
| 670 | "http://127.0.0.1:8080/admin", |
| 671 | "http://metadata.google.internal/computeMetadata/v1/", |
| 672 | ): |
| 673 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 674 | handler.redirect_request(req, None, 302, "Found", {}, bad_target) |
| 675 | assert exc_info.value.code == 403 |
| 676 | |
| 677 | |
| 678 | # --------------------------------------------------------------------------- |
| 679 | # HIGH-087: company_resolve.py _site_host, _registrable_label, _official_site |
| 680 | # --------------------------------------------------------------------------- |
| 681 | |
| 682 | |
| 683 | def test_company_resolve_site_host_blocks_query_fragment_userinfo_ssrf_spoofing(): |
| 684 | assert company_resolve._site_host("https://attacker.com?x=.stripe.com") == "attacker.com" |
| 685 | assert company_resolve._site_host("https://attacker.com#.stripe.com") == "attacker.com" |
| 686 | assert company_resolve._site_host("https://linkedin.com?ref=.stripe.com") == "linkedin.com" |
| 687 | assert company_resolve._site_host("https://stripe.com?utm=1") == "stripe.com" |
| 688 | assert company_resolve._exa_homepage("https://stripe.com?utm=1") == "https://stripe.com/" |
| 689 | |
| 690 | for bad_url in ( |
| 691 | "https://127.0.0.1?x=.stripe.com", |
| 692 | "http://169.254.169.254/latest/meta-data/", |
| 693 | "https://[::1]/", |
| 694 | "https://0x7f.0.0.1/", |
| 695 | "https://stripe.com@attacker.com/", |
| 696 | "https://user:pass@stripe.com/", |
| 697 | "https://stripe.localhost/", |
| 698 | "https://stripe.local/", |
| 699 | "https://stripe.internal/", |
| 700 | "https://stripe.com:8080/", |
| 701 | "https://www.com/", |
| 702 | "ftp://stripe.com/", |
| 703 | "javascript:alert(1)", |
| 704 | "file:///etc/passwd", |
| 705 | "https://stripe.com/\r\nBad: 1", |
| 706 | ): |
| 707 | assert company_resolve._site_host(bad_url) == "", f"expected rejection for {bad_url}" |
| 708 | |
| 709 | for spoofed in ( |
| 710 | "https://attacker.com?x=.stripe.com", |
| 711 | "https://127.0.0.1?x=.stripe.com", |
| 712 | "https://linkedin.com?ref=.stripe.com", |
| 713 | "https://attacker.com#.stripe.com", |
| 714 | "https://stripe.com@attacker.com/", |
| 715 | "https://stripe.co.com/", |
| 716 | "https://stripe.com.evil/", |
| 717 | ): |
| 718 | assert company_resolve._exa_site_matches_topic("Stripe", spoofed) is False |
| 719 | |
| 720 | assert company_resolve._exa_site_matches_topic("Stripe", "https://stripe.co.uk/") is True |
| 721 | assert company_resolve._exa_site_matches_topic("Stripe", "https://stripe.com?utm=1") is True |
| 722 | |
| 723 | |
| 724 | def test_company_resolve_official_site_validates_single_wikidata_p856(): |
| 725 | def stmt(val): |
| 726 | return {"rank": "normal", "mainsnak": {"snaktype": "value", "datavalue": {"value": val}}} |
| 727 | |
| 728 | for bad_p856 in ( |
| 729 | "javascript:alert(1)", |
| 730 | "ftp://stripe.com/", |
| 731 | "file:///etc/passwd", |
| 732 | "http://169.254.169.254/latest/meta-data/", |
| 733 | "http://127.0.0.1:8080/", |
| 734 | "https://user:pass@stripe.com/", |
| 735 | "https://stripe.localhost/", |
| 736 | "https://stripe.local/", |
| 737 | "https://metadata.google.internal/", |
| 738 | "https://stripe.com:8443/", |
| 739 | "https://stripe.com/\r\nX: 1", |
| 740 | "https://www.com/", |
| 741 | ): |
| 742 | assert company_resolve._official_site([stmt(bad_p856)]) == "", f"expected rejection for {bad_p856}" |
| 743 | |
| 744 | assert company_resolve._official_site([stmt("https://stripe.com/en")]) == "https://stripe.com/en" |
| 745 | assert company_resolve._official_site([stmt("https://www.com/a"), stmt("https://www.com/b")]) == "" |
| 746 | # Poisoned private entries must not tip a minority valid host into a majority. |
| 747 | assert ( |
| 748 | company_resolve._official_site([ |
| 749 | stmt("http://127.0.0.1/"), |
| 750 | stmt("http://169.254.169.254/"), |
| 751 | stmt("https://stripe.com/"), |
| 752 | ]) |
| 753 | == "" |
| 754 | ) |
| 755 | |
| 756 | |
| 757 | # --------------------------------------------------------------------------- |
| 758 | # HIGH-170: robots.py linear-time wildcard matching & parser bounds |
| 759 | # --------------------------------------------------------------------------- |
| 760 | |
| 761 | |
| 762 | def test_robots_wildcard_matcher_is_linear_on_adversarial_redos_input(): |
| 763 | evil_pattern = "/" + "a*" * 35 + "z" |
| 764 | evil_anchored = evil_pattern + "$" |
| 765 | evil_path = "/" + "a" * 40 |
| 766 | |
| 767 | started = time.monotonic() |
| 768 | assert robots._matches(evil_pattern, evil_path) is False |
| 769 | assert robots._matches(evil_anchored, evil_path) is False |
| 770 | rules = robots.Rules(f"User-agent: *\nDisallow: {evil_pattern}\nDisallow: {evil_anchored}\n") |
| 771 | assert rules.allows(evil_path) is True |
| 772 | elapsed = time.monotonic() - started |
| 773 | assert elapsed < 0.05, f"robots wildcard matching took {elapsed:.4f}s (possible ReDoS)" |
| 774 | |
| 775 | |
| 776 | @pytest.mark.parametrize( |
| 777 | "pattern,path,expected", |
| 778 | [ |
| 779 | ("/", "/anything", True), |
| 780 | ("/jobs", "/jobs/123", True), |
| 781 | ("/jobs$", "/jobs", True), |
| 782 | ("/jobs$", "/jobs/", False), |
| 783 | ("/*?q=", "/en/jobs?q=engineer", True), |
| 784 | ("/*?q=", "/en/jobs", False), |
| 785 | ("/a*a$", "/a", False), |
| 786 | ("/a*a$", "/aa", True), |
| 787 | ("/a*a$", "/abca", True), |
| 788 | ("/a*a$", "/abcb", False), |
| 789 | ("/a**b*c$", "/axxxbyyyc", True), |
| 790 | ("/a**b*c$", "/axxxbyyy", False), |
| 791 | ("/*$", "/", True), |
| 792 | ("/*$", "/foo/bar", True), |
| 793 | ("/a*b*", "/a123b456", True), |
| 794 | ("/a*b*", "/a123", False), |
| 795 | ("$", "", True), |
| 796 | ("$", "/", False), |
| 797 | ], |
| 798 | ) |
| 799 | def test_robots_matches_semantics(pattern: str, path: str, expected: bool): |
| 800 | assert robots._matches(pattern, path) is expected |
| 801 | |
| 802 | |
| 803 | def test_robots_parser_enforces_rule_sitemap_and_line_length_caps(): |
| 804 | long_comment_rule = "Disallow: /private # " + ("c" * (robots.MAX_LINE_LENGTH + 500)) |
| 805 | overlong = "Disallow: /" + ("x" * (robots.MAX_LINE_LENGTH + 50)) |
| 806 | many_rules = "\n".join(f"Disallow: /p{i}" for i in range(robots.MAX_RULES + 250)) |
| 807 | many_sitemaps = "\n".join( |
| 808 | f"Sitemap: https://example.com/s{i}.xml" for i in range(robots.MAX_SITEMAPS + 50) |
| 809 | ) |
| 810 | text = f"User-agent: *\n{long_comment_rule}\n{overlong}\n{many_rules}\n{many_sitemaps}\n" |
| 811 | rules = robots.Rules(text) |
| 812 | assert rules.allows("/private/data") is False |
| 813 | assert len(rules.rules) <= robots.MAX_RULES |
| 814 | assert len(rules.paths) <= robots.MAX_PATHS |
| 815 | assert len(rules.sitemaps) <= robots.MAX_SITEMAPS |
| 816 | assert all(len(pat) <= robots.MAX_LINE_LENGTH for _, pat in rules.rules) |
| 817 | |
| 818 | |
| 819 | def test_robots_parser_discards_incomplete_trailing_line_cut_by_max_chars(monkeypatch): |
| 820 | # Cut lands right in the middle of "Disallow: /private/secret" -> ".../pri". |
| 821 | # The incomplete line must be discarded rather than blocking "/pricing". |
| 822 | prefix = "User-agent: *\nDisallow: /admin\n" |
| 823 | cut_line = "Disallow: /private/secret\n" |
| 824 | monkeypatch.setattr(robots, "MAX_ROBOTS_CHARS", len(prefix) + len("Disallow: /pri")) |
| 825 | rules = robots.Rules(prefix + cut_line) |
| 826 | assert rules.allows("/admin/panel") is False |
| 827 | assert rules.allows("/pricing") is True |
| 828 | assert all(pat != "/pri" for _, pat in rules.rules) |
| 829 | |
| 830 | # A complete line ending right at MAX_ROBOTS_CHARS (next char is '\n') is kept. |
| 831 | monkeypatch.setattr(robots, "MAX_ROBOTS_CHARS", len(prefix) + len("Disallow: /private/secret")) |
| 832 | exact_rules = robots.Rules(prefix + cut_line) |
| 833 | assert exact_rules.allows("/private/secret") is False |
| 834 | assert exact_rules.allows("/pricing") is True |
| 835 | |
| 836 | |
| 837 | # --------------------------------------------------------------------------- |
| 838 | # HIGH-201: web_fetch_keyless.py SSRF, userinfo, redirect_guard, decode safety |
| 839 | # --------------------------------------------------------------------------- |
| 840 | |
| 841 | |
| 842 | @pytest.mark.parametrize( |
| 843 | "bad_url", |
| 844 | [ |
| 845 | "http://127.0.0.1/secret", |
| 846 | "http://127.0.0.1:8080/admin", |
| 847 | "http://localhost:3000/", |
| 848 | "http://sub.localhost/", |
| 849 | "http://169.254.169.254/latest/meta-data/", |
| 850 | "http://10.0.0.1/internal", |
| 851 | "http://192.168.1.1/", |
| 852 | "http://[::1]/", |
| 853 | "http://2130706433/", |
| 854 | "http://[64:ff9b::127.0.0.1]/", |
| 855 | "https://93.184.216.34/", |
| 856 | "https://169.254.169.254\\x.com/", |
| 857 | "http://localhost\\.example.com/", |
| 858 | "http://example.com%2f127.0.0.1/", |
| 859 | "https://example.com:8080/", |
| 860 | "https://example.com:80/", |
| 861 | "http://example.com:443/", |
| 862 | "https://exämple.com/", |
| 863 | "http://printer.local/status", |
| 864 | "http://metadata.google.internal/computeMetadata/v1/", |
| 865 | "http://intranet/secret", |
| 866 | "https://user:pass@example.com/private", |
| 867 | "https://example.com/\r\nX-Injected: 1", |
| 868 | "https://example.com/with space", |
| 869 | "file:///etc/passwd", |
| 870 | "ftp://example.com/file", |
| 871 | "javascript:alert(1)", |
| 872 | ], |
| 873 | ) |
| 874 | def test_web_fetch_keyless_rejects_private_internal_userinfo_and_non_http(bad_url: str): |
| 875 | with patch.object(web_fetch_keyless.http, "get_text") as mock_get: |
| 876 | res = web_fetch_keyless.fetch_markdown(bad_url) |
| 877 | assert res.ok is False |
| 878 | assert res.reason == "invalid-url" |
| 879 | mock_get.assert_not_called() |
| 880 | |
| 881 | |
| 882 | def test_web_fetch_keyless_enforces_public_only_redirect_guard_and_decode_handling(): |
| 883 | with patch.object(web_fetch_keyless.http, "get_text", return_value="# OK") as mock_get: |
| 884 | res = web_fetch_keyless.fetch_markdown("https://example.com/article") |
| 885 | assert res.ok is True |
| 886 | assert mock_get.call_args.kwargs.get("public_only") is True |
| 887 | guard = mock_get.call_args.kwargs.get("redirect_guard") |
| 888 | assert callable(guard) |
| 889 | assert guard("https://r.jina.ai/https://example.com/article") is True |
| 890 | assert guard("http://r.jina.ai/https://example.com/article") is False |
| 891 | assert guard("http://127.0.0.1/secret") is False |
| 892 | assert guard("http://169.254.169.254/latest/meta-data/") is False |
| 893 | assert guard("https://evil.example/redirect") is False |
| 894 | assert guard("file:///etc/passwd") is False |
| 895 | |
| 896 | # Redirect handler refuses private/off-host redirect with these guards. |
| 897 | handler = http._StripAuthOnCrossOriginRedirect() |
| 898 | req = Request("https://r.jina.ai/https://example.com/article") |
| 899 | setattr(req, http._PUBLIC_ONLY_ATTR, True) |
| 900 | setattr(req, http._REDIRECT_GUARD_ATTR, guard) |
| 901 | for bad_target in ( |
| 902 | "http://169.254.169.254/latest/meta-data/", |
| 903 | "http://127.0.0.1:8080/", |
| 904 | "https://evil.example/x", |
| 905 | ): |
| 906 | with pytest.raises(urllib.error.HTTPError) as exc_info: |
| 907 | handler.redirect_request(req, None, 302, "Found", {}, bad_target) |
| 908 | assert exc_info.value.code == 403 |
| 909 | |
| 910 | # Non-UTF-8 response from reader returns a clean failed result, never raises. |
| 911 | with patch.object( |
| 912 | web_fetch_keyless.http, |
| 913 | "get_text", |
| 914 | side_effect=UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid"), |
| 915 | ): |
| 916 | res = web_fetch_keyless.fetch_markdown("https://example.com/binary") |
| 917 | assert res.ok is False |
| 918 | assert res.markdown == "" |
| 919 | assert res.reason == "decode-error" |
| 920 |