| 1 | """Modules that build their own Request must not leak credentials on redirect. |
| 2 | |
| 3 | ``lib/http.py`` installs a redirect handler that drops credential headers when a |
| 4 | 3xx changes origin, but that only protects callers that go through it. Several |
| 5 | modules build a ``urllib.request.Request`` themselves; ``github.py`` and |
| 6 | ``transcribe.py`` attach a bearer token to theirs, so they must use |
| 7 | ``http.open_request`` rather than ``urllib.request.urlopen``. |
| 8 | """ |
| 9 | |
| 10 | import ast |
| 11 | import http.server |
| 12 | import pathlib |
| 13 | import socketserver |
| 14 | import threading |
| 15 | from urllib.request import Request |
| 16 | |
| 17 | import pytest |
| 18 | |
| 19 | from lib import github, transcribe |
| 20 | from lib import http as l30d_http |
| 21 | |
| 22 | |
| 23 | class _CaptureHandler(http.server.BaseHTTPRequestHandler): |
| 24 | captured: dict = {} |
| 25 | |
| 26 | def do_GET(self): |
| 27 | type(self).captured = {k.lower(): v for k, v in self.headers.items()} |
| 28 | body = b'{"ok":true}' |
| 29 | self.send_response(200) |
| 30 | self.send_header("Content-Type", "application/json") |
| 31 | self.send_header("Content-Length", str(len(body))) |
| 32 | self.end_headers() |
| 33 | self.wfile.write(body) |
| 34 | |
| 35 | def log_message(self, *_args): |
| 36 | pass |
| 37 | |
| 38 | |
| 39 | def _serve(handler): |
| 40 | httpd = socketserver.TCPServer(("127.0.0.1", 0), handler) |
| 41 | threading.Thread(target=httpd.serve_forever, daemon=True).start() |
| 42 | return httpd |
| 43 | |
| 44 | |
| 45 | def test_open_request_strips_bearer_across_origin(): |
| 46 | attacker = _serve(_CaptureHandler) |
| 47 | _CaptureHandler.captured = {} |
| 48 | |
| 49 | class Victim(http.server.BaseHTTPRequestHandler): |
| 50 | def do_GET(self): |
| 51 | self.send_response(302) |
| 52 | self.send_header( |
| 53 | "Location", f"http://127.0.0.1:{attacker.server_address[1]}/steal" |
| 54 | ) |
| 55 | self.send_header("Content-Length", "0") |
| 56 | self.end_headers() |
| 57 | |
| 58 | def log_message(self, *_args): |
| 59 | pass |
| 60 | |
| 61 | victim = _serve(Victim) |
| 62 | req = Request( |
| 63 | f"http://127.0.0.1:{victim.server_address[1]}/start", |
| 64 | headers={"Authorization": "Bearer ghp_sentinel_token"}, |
| 65 | ) |
| 66 | try: |
| 67 | with l30d_http.open_request(req, 10) as resp: |
| 68 | resp.read() |
| 69 | finally: |
| 70 | victim.shutdown() |
| 71 | attacker.shutdown() |
| 72 | victim.server_close() |
| 73 | attacker.server_close() |
| 74 | |
| 75 | assert "authorization" not in _CaptureHandler.captured, ( |
| 76 | "bearer token survived a cross-origin redirect: " |
| 77 | f"{_CaptureHandler.captured.get('authorization')!r}" |
| 78 | ) |
| 79 | |
| 80 | |
| 81 | @pytest.mark.parametrize("caller", ["github_json", "github_readme", "transcribe"]) |
| 82 | @pytest.mark.parametrize("cross_origin", [False, True], ids=["same_origin", "cross_origin"]) |
| 83 | def test_credential_callers_handle_redirects(caller, cross_origin, monkeypatch, tmp_path): |
| 84 | captured = [] |
| 85 | payload = b'{"ok":true,"text":"loopback transcript"}' |
| 86 | token = "dummy_redirect_caller_token" |
| 87 | |
| 88 | class Handler(http.server.BaseHTTPRequestHandler): |
| 89 | def do_GET(self): |
| 90 | captured.append((self.path, dict(self.headers.items()))) |
| 91 | if self.path == "/start": |
| 92 | self.send_response(302) |
| 93 | self.send_header("Location", destination) |
| 94 | self.send_header("Content-Length", "0") |
| 95 | self.end_headers() |
| 96 | else: |
| 97 | self.send_response(200) |
| 98 | self.send_header("Content-Type", "application/json") |
| 99 | self.send_header("Content-Length", str(len(payload))) |
| 100 | self.end_headers() |
| 101 | self.wfile.write(payload) |
| 102 | |
| 103 | def do_POST(self): |
| 104 | self.rfile.read(int(self.headers.get("Content-Length", "0"))) |
| 105 | self.do_GET() |
| 106 | |
| 107 | def log_message(self, *_args): |
| 108 | pass |
| 109 | |
| 110 | origin = _serve(Handler) |
| 111 | target = _serve(Handler) if cross_origin else origin |
| 112 | start = f"http://127.0.0.1:{origin.server_address[1]}/start" |
| 113 | destination = f"http://127.0.0.1:{target.server_address[1]}/result" |
| 114 | try: |
| 115 | if caller == "github_json": |
| 116 | assert github._fetch_json(start, token=token) == { |
| 117 | "ok": True, "text": "loopback transcript", |
| 118 | } |
| 119 | elif caller == "github_readme": |
| 120 | def loopback_request(url, *args, **kwargs): |
| 121 | if url == "https://api.github.com/repos/owner/repo/readme": |
| 122 | url = start |
| 123 | return Request(url, *args, **kwargs) |
| 124 | |
| 125 | monkeypatch.setattr(github.urllib.request, "Request", loopback_request) |
| 126 | assert github._fetch_readme_snippet("owner/repo") == payload.decode() |
| 127 | else: |
| 128 | monkeypatch.setitem(transcribe._PROVIDER_ENDPOINTS, "groq", start) |
| 129 | audio = tmp_path / "audio.mp3" |
| 130 | audio.write_bytes(b"dummy audio") |
| 131 | assert transcribe._post_audio("groq", str(audio), token, 10) == "loopback transcript" |
| 132 | finally: |
| 133 | origin.shutdown() |
| 134 | origin.server_close() |
| 135 | if target is not origin: |
| 136 | target.shutdown() |
| 137 | target.server_close() |
| 138 | |
| 139 | assert [path for path, _ in captured] == ["/start", "/result"] |
| 140 | original_headers, final_headers = ( |
| 141 | {key.lower(): value for key, value in headers.items()} |
| 142 | for _, headers in captured |
| 143 | ) |
| 144 | expected_auth = None if caller == "github_readme" else f"Bearer {token}" |
| 145 | assert original_headers.get("authorization") == expected_auth |
| 146 | assert final_headers.get("authorization") == (None if cross_origin else expected_auth) |
| 147 | assert final_headers["user-agent"] == original_headers["user-agent"] |
| 148 | |
| 149 | |
| 150 | def _dotted_name(node) -> str: |
| 151 | """Render a dotted attribute chain (``urllib.request``) or "" if not one.""" |
| 152 | parts = [] |
| 153 | while isinstance(node, ast.Attribute): |
| 154 | parts.append(node.attr) |
| 155 | node = node.value |
| 156 | if not isinstance(node, ast.Name): |
| 157 | return "" |
| 158 | parts.append(node.id) |
| 159 | return ".".join(reversed(parts)) |
| 160 | |
| 161 | |
| 162 | def _direct_urlopen_calls(source: str) -> list[int]: |
| 163 | """Line numbers of calls that reach ``urllib.request.urlopen`` in ``source``. |
| 164 | |
| 165 | Resolved through the module's imports rather than by text match. Searching |
| 166 | for the literal ``urllib.request.urlopen(`` would miss |
| 167 | ``from urllib.request import urlopen``, a form this repository already uses |
| 168 | in four other modules, so a future edit to a credential-bearing module could |
| 169 | reintroduce the bypass while keeping the guard green. |
| 170 | """ |
| 171 | tree = ast.parse(source) |
| 172 | |
| 173 | # Names bound to the urlopen function itself. |
| 174 | urlopen_names: set[str] = set() |
| 175 | # Names bound to the urllib.request module. |
| 176 | module_names: set[str] = {"urllib.request"} |
| 177 | |
| 178 | for node in ast.walk(tree): |
| 179 | if isinstance(node, ast.ImportFrom): |
| 180 | if node.module == "urllib.request": |
| 181 | for alias in node.names: |
| 182 | if alias.name == "urlopen": |
| 183 | urlopen_names.add(alias.asname or alias.name) |
| 184 | elif node.module == "urllib": |
| 185 | for alias in node.names: |
| 186 | if alias.name == "request": |
| 187 | module_names.add(alias.asname or alias.name) |
| 188 | elif isinstance(node, ast.Import): |
| 189 | for alias in node.names: |
| 190 | if alias.name == "urllib.request": |
| 191 | # `import urllib.request` binds "urllib"; an asname binds that. |
| 192 | module_names.add(alias.asname or "urllib.request") |
| 193 | elif alias.name == "urllib": |
| 194 | module_names.add(f"{alias.asname or 'urllib'}.request") |
| 195 | |
| 196 | hits: list[int] = [] |
| 197 | for node in ast.walk(tree): |
| 198 | if not isinstance(node, ast.Call): |
| 199 | continue |
| 200 | func = node.func |
| 201 | if isinstance(func, ast.Name) and func.id in urlopen_names: |
| 202 | hits.append(node.lineno) |
| 203 | elif isinstance(func, ast.Attribute) and func.attr == "urlopen": |
| 204 | if _dotted_name(func.value) in module_names: |
| 205 | hits.append(node.lineno) |
| 206 | return sorted(hits) |
| 207 | |
| 208 | |
| 209 | def test_credential_bearing_modules_do_not_call_urlopen_directly(): |
| 210 | """Regression guard: these modules attach a bearer token to their Request.""" |
| 211 | lib = pathlib.Path(l30d_http.__file__).parent |
| 212 | for name in ("github.py", "transcribe.py"): |
| 213 | source = (lib / name).read_text(encoding="utf-8") |
| 214 | hits = _direct_urlopen_calls(source) |
| 215 | assert hits == [], ( |
| 216 | f"{name} calls urllib.request.urlopen directly at line(s) " |
| 217 | f"{hits}, bypassing the cross-origin credential strip in " |
| 218 | "http.open_request" |
| 219 | ) |
| 220 | |
| 221 | |
| 222 | def test_urlopen_guard_detects_aliased_forms(): |
| 223 | """The guard itself must not be fooled by an import alias. |
| 224 | |
| 225 | Without this, the guard could silently stop working: a text search for |
| 226 | ``urllib.request.urlopen(`` passes on every aliased form below. |
| 227 | """ |
| 228 | detected = ( |
| 229 | "import urllib.request\nurllib.request.urlopen(req)\n", |
| 230 | "from urllib.request import urlopen\nurlopen(req)\n", |
| 231 | "from urllib.request import urlopen as uo\nuo(req)\n", |
| 232 | "from urllib import request\nrequest.urlopen(req)\n", |
| 233 | "from urllib import request as r\nr.urlopen(req)\n", |
| 234 | "import urllib.request as ur\nur.urlopen(req)\n", |
| 235 | ) |
| 236 | for source in detected: |
| 237 | assert _direct_urlopen_calls(source), f"missed: {source!r}" |
| 238 | |
| 239 | ignored = ( |
| 240 | # Routed through the protected wrapper — the whole point of the fix. |
| 241 | "from . import http\nhttp.open_request(req, timeout=10)\n", |
| 242 | # An unrelated urlopen on some other object must not trip the guard. |
| 243 | "session.urlopen(req)\n", |
| 244 | "from urllib.request import Request\nRequest(url)\n", |
| 245 | ) |
| 246 | for source in ignored: |
| 247 | assert not _direct_urlopen_calls(source), f"false positive: {source!r}" |
| 248 |