| 1 | """Response headers and the per-host retry header in the HTTP layer. |
| 2 | |
| 3 | A session token can arrive in a response header rather than the body, and a |
| 4 | 429 can name its wait in ``x-rate-limit-retry-after-seconds``. Everything here |
| 5 | is mocked at ``urllib.request.urlopen``; no test opens a socket. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import json |
| 11 | import urllib.error |
| 12 | from email.message import Message |
| 13 | from unittest.mock import MagicMock |
| 14 | |
| 15 | import pytest |
| 16 | |
| 17 | from lib import http |
| 18 | |
| 19 | |
| 20 | def _headers(pairs: dict[str, str]) -> Message: |
| 21 | message = Message() |
| 22 | for name, value in pairs.items(): |
| 23 | message[name] = value |
| 24 | return message |
| 25 | |
| 26 | |
| 27 | def _response(body: str, headers: dict[str, str] | None = None): |
| 28 | response = MagicMock() |
| 29 | response.__enter__.return_value = response |
| 30 | response.__exit__.return_value = False |
| 31 | response.read.return_value = body.encode("utf-8") |
| 32 | response.status = 200 |
| 33 | response.headers = _headers(headers or {}) |
| 34 | return response |
| 35 | |
| 36 | |
| 37 | def _no_network(*_args, **_kwargs): |
| 38 | pytest.fail("fixture replay attempted the network") |
| 39 | |
| 40 | |
| 41 | def test_request_that_asks_for_headers_gets_body_and_case_insensitive_headers(monkeypatch): |
| 42 | monkeypatch.setattr( |
| 43 | http.urllib.request, |
| 44 | "urlopen", |
| 45 | lambda *_a, **_k: _response('{"ok": true}', {"X-Request-Id": "abc-123"}), |
| 46 | ) |
| 47 | |
| 48 | body, headers = http.post( |
| 49 | "https://api.example.test/session", json_data={"q": 1}, return_headers=True |
| 50 | ) |
| 51 | |
| 52 | assert body == {"ok": True} |
| 53 | assert headers["x-request-id"] == "abc-123" |
| 54 | assert headers.get("X-REQUEST-ID") == "abc-123" |
| 55 | assert "X-Request-Id" in headers |
| 56 | assert headers.get("x-missing") is None |
| 57 | assert headers.get("x-missing", "fallback") == "fallback" |
| 58 | |
| 59 | |
| 60 | def test_raw_request_that_asks_for_headers_gets_text_and_headers(monkeypatch): |
| 61 | monkeypatch.setattr( |
| 62 | http.urllib.request, |
| 63 | "urlopen", |
| 64 | lambda *_a, **_k: _response("plain text", {"X-Request-Id": "abc-123"}), |
| 65 | ) |
| 66 | |
| 67 | body, headers = http.request( |
| 68 | "GET", "https://api.example.test/page", raw=True, return_headers=True |
| 69 | ) |
| 70 | |
| 71 | assert body == "plain text" |
| 72 | assert headers["X-Request-Id"] == "abc-123" |
| 73 | |
| 74 | |
| 75 | def test_request_that_does_not_ask_gets_only_the_body(monkeypatch): |
| 76 | monkeypatch.setattr( |
| 77 | http.urllib.request, |
| 78 | "urlopen", |
| 79 | lambda *_a, **_k: _response('{"ok": true}', {"X-Request-Id": "abc-123"}), |
| 80 | ) |
| 81 | |
| 82 | assert http.get("https://api.example.test/search") == {"ok": True} |
| 83 | assert http.post("https://api.example.test/search", json_data={"q": 1}) == {"ok": True} |
| 84 | assert http.request("GET", "https://api.example.test/search", raw=True) == '{"ok": true}' |
| 85 | |
| 86 | |
| 87 | def test_owned_get_refuses_to_promise_headers_it_cannot_read(): |
| 88 | with pytest.raises(ValueError): |
| 89 | http.request( |
| 90 | "GET", |
| 91 | "https://api.example.test/search", |
| 92 | owned_get=True, |
| 93 | deadline_monotonic=1e12, |
| 94 | return_headers=True, |
| 95 | ) |
| 96 | |
| 97 | |
| 98 | def test_429_with_retry_after_seconds_header_waits_that_long(monkeypatch): |
| 99 | sleeps: list[float] = [] |
| 100 | monkeypatch.setattr(http.time, "sleep", sleeps.append) |
| 101 | calls = iter([ |
| 102 | urllib.error.HTTPError( |
| 103 | "https://api.example.test/search", |
| 104 | 429, |
| 105 | "Too Many Requests", |
| 106 | _headers({"x-rate-limit-retry-after-seconds": "8"}), |
| 107 | None, |
| 108 | ), |
| 109 | _response('{"ok": true}'), |
| 110 | ]) |
| 111 | |
| 112 | def urlopen(*_args, **_kwargs): |
| 113 | outcome = next(calls) |
| 114 | if isinstance(outcome, Exception): |
| 115 | raise outcome |
| 116 | return outcome |
| 117 | |
| 118 | monkeypatch.setattr(http.urllib.request, "urlopen", urlopen) |
| 119 | |
| 120 | assert http.get("https://api.example.test/search") == {"ok": True} |
| 121 | assert sleeps == [8.0] |
| 122 | |
| 123 | |
| 124 | def test_retry_delay_reads_the_retry_after_seconds_header(): |
| 125 | assert http.retry_delay_from_headers( |
| 126 | {"x-rate-limit-retry-after-seconds": "8"}, 3.0 |
| 127 | ) == 8.0 |
| 128 | assert http.retry_delay_from_headers({}, 3.0) == 3.0 |
| 129 | |
| 130 | |
| 131 | def test_recorded_fixture_with_headers_replays_the_same_headers(tmp_path, monkeypatch): |
| 132 | monkeypatch.setattr( |
| 133 | http.urllib.request, |
| 134 | "urlopen", |
| 135 | lambda *_a, **_k: _response('{"ok": true}', {"X-Request-Id": "abc-123"}), |
| 136 | ) |
| 137 | fixture_dir = tmp_path / "fixture" |
| 138 | |
| 139 | with http.recording_requests(fixture_dir): |
| 140 | live_body, live_headers = http.post( |
| 141 | "https://api.example.test/session", json_data={"q": 1}, return_headers=True |
| 142 | ) |
| 143 | |
| 144 | monkeypatch.setattr(http.urllib.request, "urlopen", _no_network) |
| 145 | with http.replaying_requests(fixture_dir): |
| 146 | body, headers = http.post( |
| 147 | "https://api.example.test/session", json_data={"q": 1}, return_headers=True |
| 148 | ) |
| 149 | |
| 150 | assert body == live_body == {"ok": True} |
| 151 | assert headers["x-request-id"] == live_headers["X-Request-Id"] == "abc-123" |
| 152 | assert headers.get("X-Request-Id") == "abc-123" |
| 153 | |
| 154 | |
| 155 | def test_recorded_token_header_is_redacted_on_disk_but_still_present_on_replay( |
| 156 | tmp_path, monkeypatch |
| 157 | ): |
| 158 | monkeypatch.setattr( |
| 159 | http.urllib.request, |
| 160 | "urlopen", |
| 161 | lambda *_a, **_k: _response("{}", {"x-access-token": "dummy-session-SENTINEL"}), |
| 162 | ) |
| 163 | fixture_dir = tmp_path / "fixture" |
| 164 | |
| 165 | with http.recording_requests(fixture_dir): |
| 166 | _, live_headers = http.post( |
| 167 | "https://api.example.test/session", json_data=-1, return_headers=True |
| 168 | ) |
| 169 | assert live_headers["x-access-token"] == "dummy-session-SENTINEL" |
| 170 | |
| 171 | assert "dummy-session-SENTINEL" not in (fixture_dir / "http.json").read_text( |
| 172 | encoding="utf-8" |
| 173 | ) |
| 174 | |
| 175 | monkeypatch.setattr(http.urllib.request, "urlopen", _no_network) |
| 176 | with http.replaying_requests(fixture_dir): |
| 177 | _, headers = http.post( |
| 178 | "https://api.example.test/session", json_data=-1, return_headers=True |
| 179 | ) |
| 180 | assert headers["X-Access-Token"] == "<redacted>" |
| 181 | |
| 182 | |
| 183 | def test_request_without_headers_records_no_headers(tmp_path, monkeypatch): |
| 184 | monkeypatch.setattr( |
| 185 | http.urllib.request, |
| 186 | "urlopen", |
| 187 | lambda *_a, **_k: _response('{"ok": true}', {"X-Request-Id": "abc-123"}), |
| 188 | ) |
| 189 | fixture_dir = tmp_path / "fixture" |
| 190 | |
| 191 | with http.recording_requests(fixture_dir): |
| 192 | http.get("https://api.example.test/search") |
| 193 | |
| 194 | payload = json.loads((fixture_dir / "http.json").read_text(encoding="utf-8")) |
| 195 | assert payload["exchanges"] == [ |
| 196 | { |
| 197 | "request": { |
| 198 | "method": "GET", |
| 199 | "url": "https://api.example.test/search", |
| 200 | "raw": False, |
| 201 | }, |
| 202 | "response": {"value": {"ok": True}}, |
| 203 | } |
| 204 | ] |
| 205 | |
| 206 | |
| 207 | def test_fixture_recorded_without_headers_still_replays(tmp_path, monkeypatch): |
| 208 | fixture = tmp_path / "http.json" |
| 209 | fixture.write_text( |
| 210 | json.dumps({ |
| 211 | "format": "last30days-http-fixture/v1", |
| 212 | "exchanges": [ |
| 213 | { |
| 214 | "request": { |
| 215 | "method": "GET", |
| 216 | "url": "https://api.example.test/search", |
| 217 | "raw": False, |
| 218 | }, |
| 219 | "response": {"value": {"ok": True}}, |
| 220 | }, |
| 221 | { |
| 222 | "request": { |
| 223 | "method": "GET", |
| 224 | "url": "https://api.example.test/search", |
| 225 | "raw": False, |
| 226 | }, |
| 227 | "response": {"value": {"ok": True}}, |
| 228 | }, |
| 229 | ], |
| 230 | "source_exchanges": [], |
| 231 | }), |
| 232 | encoding="utf-8", |
| 233 | ) |
| 234 | monkeypatch.setattr(http.urllib.request, "urlopen", _no_network) |
| 235 | |
| 236 | with http.replaying_requests(fixture): |
| 237 | assert http.get("https://api.example.test/search") == {"ok": True} |
| 238 | body, headers = http.get("https://api.example.test/search", return_headers=True) |
| 239 | |
| 240 | assert body == {"ok": True} |
| 241 | assert headers.get("x-access-token") is None |
| 242 | |
| 243 | |
| 244 | def test_post_sends_a_bare_json_scalar_body(monkeypatch): |
| 245 | sent = {} |
| 246 | |
| 247 | def urlopen(req, **_kwargs): |
| 248 | sent["data"] = req.data |
| 249 | sent["content_type"] = req.get_header("Content-type") |
| 250 | return _response("{}") |
| 251 | |
| 252 | monkeypatch.setattr(http.urllib.request, "urlopen", urlopen) |
| 253 | |
| 254 | http.post("https://api.example.test/session", json_data=-1) |
| 255 | |
| 256 | assert sent == {"data": b"-1", "content_type": "application/json"} |
| 257 | |
| 258 | |
| 259 | @pytest.mark.parametrize("retry_after", [ |
| 260 | "Sat, 28 Nov 2026 12:00:30 GMT", |
| 261 | "Saturday, 28-Nov-26 12:00:30 GMT", |
| 262 | "Sat Nov 28 12:00:30 2026", |
| 263 | ]) |
| 264 | def test_429_with_http_date_waits_until_retry_time(monkeypatch, retry_after): |
| 265 | from datetime import datetime, timezone |
| 266 | |
| 267 | now = datetime(2026, 11, 28, 12, 0, tzinfo=timezone.utc).timestamp() |
| 268 | monkeypatch.setattr(http.time, "time", lambda: now) |
| 269 | sleeps = [] |
| 270 | monkeypatch.setattr(http.time, "sleep", sleeps.append) |
| 271 | outcomes = iter([ |
| 272 | urllib.error.HTTPError( |
| 273 | "https://api.example.test/search", 429, "Too Many Requests", |
| 274 | _headers({"Retry-After": retry_after}), None, |
| 275 | ), |
| 276 | _response('{"ok": true}'), |
| 277 | ]) |
| 278 | |
| 279 | def urlopen(*_args, **_kwargs): |
| 280 | outcome = next(outcomes) |
| 281 | if isinstance(outcome, Exception): |
| 282 | raise outcome |
| 283 | return outcome |
| 284 | |
| 285 | monkeypatch.setattr(http.urllib.request, "urlopen", urlopen) |
| 286 | assert http.get("https://api.example.test/search") == {"ok": True} |
| 287 | assert sleeps == [30.0] |
| 288 | |
| 289 | |
| 290 | def test_http_date_retry_delay_keeps_cap_and_header_precedence(monkeypatch): |
| 291 | from datetime import datetime, timezone |
| 292 | |
| 293 | now = datetime(2026, 11, 28, 12, 0, tzinfo=timezone.utc).timestamp() |
| 294 | monkeypatch.setattr(http.time, "time", lambda: now) |
| 295 | assert http.retry_delay_from_headers({ |
| 296 | "Retry-After": "Sat, 28 Nov 2026 12:02:00 GMT", "x-ratelimit-reset": "5", |
| 297 | }, 3.0) == http.MAX_RETRY_DELAY_SECONDS |
| 298 | assert http.retry_delay_from_headers({ |
| 299 | "Retry-After": "Sat, 28 Nov 2026 11:59:59 GMT", "x-ratelimit-reset": "5", |
| 300 | }, 3.0) == 5.0 |
| 301 | assert http.retry_delay_from_headers({ |
| 302 | "Retry-After": "not a date", "x-ratelimit-reset": "5", |
| 303 | }, 3.0) == 5.0 |
| 304 | |
| 305 | |
| 306 | @pytest.mark.parametrize(("current_year", "retry_after", "delay"), [ |
| 307 | (2069, "Thursday, 28-Nov-69 12:00:30 GMT", 30.0), |
| 308 | (2019, "Thursday, 28-Nov-69 12:00:00 GMT", http.MAX_RETRY_DELAY_SECONDS), |
| 309 | (2019, "Friday, 28-Nov-69 12:00:01 GMT", 5.0), |
| 310 | (2018, "Thursday, 28-Nov-68 12:00:01 GMT", 5.0), |
| 311 | ]) |
| 312 | def test_rfc850_retry_after_uses_rolling_fifty_year_limit(monkeypatch, current_year, retry_after, delay): |
| 313 | from datetime import datetime, timezone |
| 314 | |
| 315 | now = datetime(current_year, 11, 28, 12, 0, tzinfo=timezone.utc).timestamp() |
| 316 | monkeypatch.setattr(http.time, "time", lambda: now) |
| 317 | assert http.retry_delay_from_headers({ |
| 318 | "Retry-After": retry_after, "x-ratelimit-reset": "5", |
| 319 | }, 3.0) == delay |
| 320 | |
| 321 | |
| 322 | @pytest.mark.parametrize("value", [["bad"], {"value": "bad"}]) |
| 323 | def test_non_string_retry_after_still_falls_through(value): |
| 324 | assert http.retry_delay_from_headers({ |
| 325 | "Retry-After": value, "x-ratelimit-reset": "5", |
| 326 | }, 3.0) == 5.0 |
| 327 |