| 1 | """Security hardening regression tests for PR04 (HIGH-063, HIGH-065, HIGH-068, HIGH-078, HIGH-085).""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import ast |
| 6 | import http.server as stdlib_http |
| 7 | import io |
| 8 | import json |
| 9 | import os |
| 10 | import shlex |
| 11 | import subprocess |
| 12 | import sys |
| 13 | import threading |
| 14 | import urllib.error |
| 15 | import urllib.request |
| 16 | from contextlib import redirect_stdout |
| 17 | from pathlib import Path |
| 18 | from unittest import mock |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | from lib import env, hosted, http, setup_wizard |
| 23 | |
| 24 | |
| 25 | SCRIPTS_DIR = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts" |
| 26 | SETUP_KEYCHAIN_SH = SCRIPTS_DIR / "setup-keychain.sh" |
| 27 | SETUP_PASS_SH = SCRIPTS_DIR / "setup-pass.sh" |
| 28 | |
| 29 | |
| 30 | @pytest.fixture |
| 31 | def serve(): |
| 32 | running = [] |
| 33 | |
| 34 | def start(*, payload=None, redirect_to=None, status=200, raw_body=None): |
| 35 | requests = [] |
| 36 | |
| 37 | class Handler(stdlib_http.BaseHTTPRequestHandler): |
| 38 | def do_POST(self): |
| 39 | self._respond() |
| 40 | |
| 41 | def do_GET(self): |
| 42 | self._respond() |
| 43 | |
| 44 | def _respond(self): |
| 45 | length = int(self.headers.get("Content-Length", "0")) |
| 46 | body_in = self.rfile.read(length) if length else b"" |
| 47 | requests.append( |
| 48 | ( |
| 49 | self.command, |
| 50 | self.path, |
| 51 | {key.lower(): value for key, value in self.headers.items()}, |
| 52 | body_in, |
| 53 | ) |
| 54 | ) |
| 55 | if redirect_to is not None: |
| 56 | self.send_response(302) |
| 57 | self.send_header("Location", redirect_to) |
| 58 | self.send_header("Content-Length", "0") |
| 59 | self.end_headers() |
| 60 | return |
| 61 | if raw_body is not None: |
| 62 | data = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8") |
| 63 | else: |
| 64 | data = json.dumps(payload if payload is not None else {"ok": True}).encode("utf-8") |
| 65 | self.send_response(status) |
| 66 | self.send_header("Content-Type", "application/json") |
| 67 | self.send_header("Content-Length", str(len(data))) |
| 68 | self.end_headers() |
| 69 | self.wfile.write(data) |
| 70 | |
| 71 | def log_message(self, *_args): |
| 72 | pass |
| 73 | |
| 74 | server = stdlib_http.ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 75 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 76 | thread.start() |
| 77 | running.append((server, thread)) |
| 78 | return f"http://127.0.0.1:{server.server_port}", requests |
| 79 | |
| 80 | yield start |
| 81 | |
| 82 | for server, thread in reversed(running): |
| 83 | server.shutdown() |
| 84 | server.server_close() |
| 85 | thread.join(timeout=5) |
| 86 | |
| 87 | |
| 88 | def _enable_proxy(monkeypatch, proxy_url: str) -> None: |
| 89 | monkeypatch.setenv("HTTP_PROXY", proxy_url) |
| 90 | monkeypatch.setenv("http_proxy", proxy_url) |
| 91 | monkeypatch.delenv("NO_PROXY", raising=False) |
| 92 | monkeypatch.delenv("no_proxy", raising=False) |
| 93 | monkeypatch.setattr(http, "_opener", http._build_http_opener(bypass_proxy=False)) |
| 94 | monkeypatch.setattr(http, "_direct_opener", http._build_http_opener(bypass_proxy=True)) |
| 95 | |
| 96 | |
| 97 | # --------------------------------------------------------------------------- |
| 98 | # HIGH-063: hosted.py loopback proxy bypass, header sanitization, URL hygiene |
| 99 | # --------------------------------------------------------------------------- |
| 100 | |
| 101 | |
| 102 | @pytest.mark.parametrize("host", ["127.0.0.1", "localhost"]) |
| 103 | def test_hosted_submit_and_poll_bypass_http_proxy_on_loopback(monkeypatch, serve, host): |
| 104 | endpoint, endpoint_requests = serve( |
| 105 | payload={"search_id": "abc-123", "status": "complete", "synthesis_text": "direct"} |
| 106 | ) |
| 107 | proxy_url, proxy_requests = serve(payload={"search_id": "proxied", "status": "error"}) |
| 108 | _enable_proxy(monkeypatch, proxy_url) |
| 109 | monkeypatch.setenv("LAST30DAYS_API_BASE", endpoint.replace("127.0.0.1", host, 1) + "/api/v1") |
| 110 | monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_loopback_secret_0001") |
| 111 | |
| 112 | sub = hosted.submit("topic", "quick") |
| 113 | polled = hosted.poll("abc-123") |
| 114 | |
| 115 | assert sub["search_id"] == "abc-123" |
| 116 | assert polled["status"] == "complete" |
| 117 | assert proxy_requests == [] |
| 118 | assert len(endpoint_requests) == 2 |
| 119 | assert endpoint_requests[0][0:2] == ("POST", "/api/v1/search") |
| 120 | assert endpoint_requests[1][0:2] == ("GET", "/api/v1/search?id=abc-123") |
| 121 | for _, _, headers, _ in endpoint_requests: |
| 122 | assert headers["authorization"] == "Bearer sk_live_loopback_secret_0001" |
| 123 | |
| 124 | |
| 125 | @pytest.mark.parametrize("raw_key", ["sk_live_secret_trail\n", " sk_live_secret_trail\r\n "]) |
| 126 | def test_hosted_strips_trailing_newline_from_api_key(monkeypatch, serve, raw_key): |
| 127 | endpoint, endpoint_requests = serve(payload={"search_id": "ok-1", "status": "running"}) |
| 128 | monkeypatch.setenv("LAST30DAYS_API_BASE", f" {endpoint}/api/v1/ ") |
| 129 | monkeypatch.setenv("LAST30DAYS_API_KEY", raw_key) |
| 130 | |
| 131 | res = hosted.submit("topic", "quick") |
| 132 | |
| 133 | assert res["search_id"] == "ok-1" |
| 134 | assert endpoint_requests[0][2]["authorization"] == "Bearer sk_live_secret_trail" |
| 135 | |
| 136 | |
| 137 | @pytest.mark.parametrize( |
| 138 | "bad_key", |
| 139 | [ |
| 140 | "sk_live_SPLIT_SECRET\r\nX-Injected: 1", |
| 141 | "sk_live_SPLIT_SECRET\nsecond-line", |
| 142 | "sk_live_SPLIT_SECRET\x00tail", |
| 143 | "sk_live_SPLIT_SECRET\ttab", |
| 144 | "sk_live_SPLIT_SECRET_🔑", |
| 145 | " \n\r ", |
| 146 | ], |
| 147 | ) |
| 148 | def test_hosted_rejects_invalid_api_key_without_leaking_secret(monkeypatch, capsys, bad_key): |
| 149 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1") |
| 150 | if "\x00" in bad_key: |
| 151 | monkeypatch.setattr( |
| 152 | hosted.env, |
| 153 | "read_secret_env", |
| 154 | lambda name, default=None: bad_key if name == "LAST30DAYS_API_KEY" else default, |
| 155 | ) |
| 156 | else: |
| 157 | monkeypatch.setenv("LAST30DAYS_API_KEY", bad_key) |
| 158 | |
| 159 | with mock.patch.object(hosted.http, "post") as post, mock.patch.object(hosted.http, "get") as get: |
| 160 | with pytest.raises(ValueError) as sub_exc: |
| 161 | hosted.submit("topic", "quick") |
| 162 | with pytest.raises(ValueError) as poll_exc: |
| 163 | hosted.poll("id-1") |
| 164 | rc = hosted.run_hosted("topic", "quick") |
| 165 | |
| 166 | captured = capsys.readouterr() |
| 167 | post.assert_not_called() |
| 168 | get.assert_not_called() |
| 169 | assert rc == 1 |
| 170 | for blob in (str(sub_exc.value), str(poll_exc.value), captured.out, captured.err): |
| 171 | assert "sk_live_SPLIT_SECRET" not in blob |
| 172 | |
| 173 | |
| 174 | def test_hosted_catches_putheader_value_error_without_echoing_secret(monkeypatch, capsys): |
| 175 | secret = "sk_live_NEVER_ECHO_98765" |
| 176 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test/api/v1") |
| 177 | monkeypatch.setenv("LAST30DAYS_API_KEY", secret) |
| 178 | |
| 179 | def boom(*_args, **_kwargs): |
| 180 | raise ValueError(f"Invalid header value b'Bearer {secret}\\n'") |
| 181 | |
| 182 | monkeypatch.setattr(hosted.http, "post", boom) |
| 183 | with pytest.raises(ValueError) as exc_info: |
| 184 | hosted.submit("topic", "quick") |
| 185 | assert secret not in str(exc_info.value) |
| 186 | |
| 187 | rc = hosted.run_hosted("topic", "quick") |
| 188 | captured = capsys.readouterr() |
| 189 | assert rc == 1 |
| 190 | assert secret not in captured.out + captured.err |
| 191 | |
| 192 | |
| 193 | @pytest.mark.parametrize( |
| 194 | "bad_base,secret_marker", |
| 195 | [ |
| 196 | ("https://alice:topsecretpass@api.example.test/api/v1", "topsecretpass"), |
| 197 | ("https://alice:p@ss@word@api.example.test/api/v1", "p@ss@word"), |
| 198 | ("https://tokenonly@api.example.test/api/v1", "tokenonly"), |
| 199 | ("https://api.example.test/api/v1?secret=qval", "qval"), |
| 200 | ("https://api.example.test/api/v1?", "api.example.test"), |
| 201 | ("https://api.example.test/api/v1#fragsecret", "fragsecret"), |
| 202 | ("https://api.example.test/api/v1#", "api.example.test"), |
| 203 | ("https://api.example.test/api/v1\r\nX-Injected: 1", "X-Injected"), |
| 204 | ("https://api.example.test/api/v1 bad", "bad"), |
| 205 | ("https://evil.example\\@good.example/api/v1", "evil.example"), |
| 206 | ("https://api.example.test:99999/api/v1", "99999"), |
| 207 | ], |
| 208 | ) |
| 209 | def test_hosted_api_base_rejects_userinfo_query_fragment_and_control_chars( |
| 210 | monkeypatch, capsys, bad_base, secret_marker |
| 211 | ): |
| 212 | monkeypatch.setenv("LAST30DAYS_API_BASE", bad_base) |
| 213 | monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_dummy_key") |
| 214 | |
| 215 | with mock.patch.object(hosted.http, "post") as post: |
| 216 | rc = hosted.run_hosted("topic", "quick") |
| 217 | |
| 218 | captured = capsys.readouterr() |
| 219 | post.assert_not_called() |
| 220 | assert rc == 1 |
| 221 | assert secret_marker not in captured.out + captured.err |
| 222 | |
| 223 | |
| 224 | def test_hosted_scrub_url_userinfo_handles_ipv6_at_passwords_and_server_errors(monkeypatch, capsys): |
| 225 | assert hosted._scrub_url_userinfo("https://u:p@api.example.test:8443/api/v1") == "https://api.example.test:8443/api/v1" |
| 226 | assert hosted._scrub_url_userinfo("https://u:p@ss@word@api.example.test/api/v1") == "https://api.example.test/api/v1" |
| 227 | assert hosted._scrub_url_userinfo("http://u:p@[::1]:8080/api/v1") == "http://[::1]:8080/api/v1" |
| 228 | assert hosted._scrub_url_userinfo("https://api.example.test/api/v1") == "https://api.example.test/api/v1" |
| 229 | |
| 230 | # Whitespace-only LAST30DAYS_API_KEY must not redact ordinary spaces. |
| 231 | monkeypatch.setenv("LAST30DAYS_API_KEY", " ") |
| 232 | assert hosted._scrub_error_text("hello world https://u:p@ss@api.example.test/v1") == "hello world https://api.example.test/v1" |
| 233 | |
| 234 | # Defense-in-depth: even if _api_base is monkeypatched to include userinfo, logs scrub it, |
| 235 | # and server-returned balance/needed, unexpected submit payloads, and error rows scrub the key. |
| 236 | secret = "sk_live_HOSTED_ECHO_9999" |
| 237 | monkeypatch.setenv("LAST30DAYS_API_KEY", secret) |
| 238 | monkeypatch.setattr(hosted, "_api_base", lambda: "https://alice:leakpw@api.example.test/api/v1") |
| 239 | monkeypatch.setattr( |
| 240 | hosted.http, |
| 241 | "post", |
| 242 | mock.Mock( |
| 243 | side_effect=http.HTTPError( |
| 244 | "HTTP 402", |
| 245 | 402, |
| 246 | json.dumps({"error": f"No credits for {secret}", "balance": secret, "needed": secret}), |
| 247 | ) |
| 248 | ), |
| 249 | ) |
| 250 | rc = hosted.run_hosted("topic", "quick") |
| 251 | captured = capsys.readouterr() |
| 252 | assert rc == 1 |
| 253 | assert "leakpw" not in captured.err |
| 254 | assert "alice@" not in captured.err |
| 255 | assert secret not in captured.err |
| 256 | assert "https://api.example.test/dashboard/billing" in captured.err |
| 257 | |
| 258 | # Unexpected response without search_id scrubs API key. |
| 259 | monkeypatch.setattr(hosted.http, "post", mock.Mock(return_value={"oops": secret})) |
| 260 | assert hosted.run_hosted("topic", "quick") == 1 |
| 261 | assert secret not in capsys.readouterr().err |
| 262 | |
| 263 | # Terminal error row scrubs API key. |
| 264 | monkeypatch.setattr(hosted.time, "sleep", lambda _s: None) |
| 265 | monkeypatch.setattr(hosted.http, "post", mock.Mock(return_value={"search_id": "sid-1"})) |
| 266 | monkeypatch.setattr(hosted.http, "get", mock.Mock(return_value={"status": "error", "error": f"bad {secret}"})) |
| 267 | assert hosted.run_hosted("topic", "quick") == 1 |
| 268 | assert secret not in capsys.readouterr().err |
| 269 | |
| 270 | |
| 271 | @pytest.mark.parametrize("code", [302, 307, 308]) |
| 272 | def test_hosted_submit_and_poll_refuse_cross_origin_redirects(monkeypatch, serve, code): |
| 273 | attacker_url, attacker_requests = serve(payload={"search_id": "stolen", "status": "complete"}) |
| 274 | |
| 275 | class RedirectHandler(stdlib_http.BaseHTTPRequestHandler): |
| 276 | def do_POST(self): |
| 277 | length = int(self.headers.get("Content-Length", "0")) |
| 278 | if length: |
| 279 | self.rfile.read(length) |
| 280 | self._redirect() |
| 281 | |
| 282 | def do_GET(self): |
| 283 | self._redirect() |
| 284 | |
| 285 | def _redirect(self): |
| 286 | self.send_response(code) |
| 287 | self.send_header("Location", f"{attacker_url}/steal") |
| 288 | self.send_header("Content-Length", "0") |
| 289 | self.end_headers() |
| 290 | |
| 291 | def log_message(self, *_args): |
| 292 | pass |
| 293 | |
| 294 | server = stdlib_http.ThreadingHTTPServer(("127.0.0.1", 0), RedirectHandler) |
| 295 | thread = threading.Thread(target=server.serve_forever, daemon=True) |
| 296 | thread.start() |
| 297 | try: |
| 298 | monkeypatch.setenv("LAST30DAYS_API_BASE", f"http://127.0.0.1:{server.server_port}/api/v1") |
| 299 | monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_never_redirect_key") |
| 300 | with pytest.raises(http.HTTPError) as sub_err: |
| 301 | hosted.submit("sensitive query", "quick") |
| 302 | assert sub_err.value.status_code == 403 |
| 303 | with pytest.raises(http.HTTPError) as poll_err: |
| 304 | hosted.poll("sid-1") |
| 305 | assert poll_err.value.status_code == 403 |
| 306 | finally: |
| 307 | server.shutdown() |
| 308 | server.server_close() |
| 309 | thread.join(timeout=5) |
| 310 | |
| 311 | assert attacker_requests == [] |
| 312 | |
| 313 | |
| 314 | def test_hosted_debug_log_scrubs_embedded_url_credentials_in_upstream_errors(monkeypatch, capsys, serve): |
| 315 | secret_url = "https://alice:topsecretpw@upstream.example.test/internal" |
| 316 | endpoint, _reqs = serve(status=500, payload={"error": f"upstream failed at {secret_url}"}) |
| 317 | monkeypatch.setenv("LAST30DAYS_API_BASE", f"{endpoint}/api/v1") |
| 318 | monkeypatch.setenv("LAST30DAYS_API_KEY", "sk_live_debug_scrub_key_999") |
| 319 | monkeypatch.setenv("LAST30DAYS_DEBUG", "1") |
| 320 | |
| 321 | with pytest.raises(http.HTTPError): |
| 322 | hosted.submit("topic", "quick") |
| 323 | with pytest.raises(http.HTTPError): |
| 324 | hosted.poll("sid-1") |
| 325 | |
| 326 | err = capsys.readouterr().err |
| 327 | assert "[DEBUG]" in err |
| 328 | assert "topsecretpw" not in err |
| 329 | assert "alice:" not in err |
| 330 | assert "sk_live_debug_scrub_key_999" not in err |
| 331 | assert "https://upstream.example.test/internal" in err |
| 332 | |
| 333 | |
| 334 | def test_url_userinfo_scrubber_preserves_at_in_query_or_fragment_without_path(monkeypatch, capsys): |
| 335 | cases = [ |
| 336 | ("https://example.com?email=a@b.com", "https://example.com?email=a@b.com"), |
| 337 | ("https://example.com#a@b", "https://example.com#a@b"), |
| 338 | ("https://user:p@ss@example.com/path", "https://example.com/path"), |
| 339 | ("https://user:p@ss@example.com?email=a@b.com", "https://example.com?email=a@b.com"), |
| 340 | ("https://user:p@ss@example.com#a@b", "https://example.com#a@b"), |
| 341 | ] |
| 342 | monkeypatch.setenv("LAST30DAYS_DEBUG", "1") |
| 343 | for raw_url, expected in cases: |
| 344 | assert hosted._scrub_error_text(raw_url) == expected |
| 345 | assert setup_wizard._scrub_error_text(raw_url) == expected |
| 346 | http.log(raw_url) |
| 347 | logged = capsys.readouterr().err |
| 348 | assert expected in logged |
| 349 | assert "user:p@ss" not in logged |
| 350 | |
| 351 | |
| 352 | # --------------------------------------------------------------------------- |
| 353 | # HIGH-065: setup_wizard.py verification_uri validation |
| 354 | # --------------------------------------------------------------------------- |
| 355 | |
| 356 | |
| 357 | @pytest.mark.parametrize( |
| 358 | "uri", |
| 359 | [ |
| 360 | "https://github.com/login/device", |
| 361 | "https://github.com/login/device/", |
| 362 | "https://github.com/login/device/confirmation", |
| 363 | "https://github.com:443/login/device", |
| 364 | ], |
| 365 | ) |
| 366 | def test_verification_uri_validator_accepts_legitimate_github_uris(uri): |
| 367 | assert setup_wizard._is_valid_verification_uri(uri) is True |
| 368 | |
| 369 | |
| 370 | @pytest.mark.parametrize( |
| 371 | "uri", |
| 372 | [ |
| 373 | "file:///etc/passwd", |
| 374 | "ms-msdt:/id PCWDiagnostic", |
| 375 | "smb://attacker.example/share", |
| 376 | "javascript:alert(1)", |
| 377 | "http://github.com/login/device", |
| 378 | "https://evil.example/login/device", |
| 379 | "https://enterprise.github.com/login/device", |
| 380 | "https://gist.github.com/login/device", |
| 381 | "https://evil.github.com/login/device", |
| 382 | "https://github.com.evil.example/login/device", |
| 383 | "https://evilgithub.com/login/device", |
| 384 | "https://.github.com/login/device", |
| 385 | "https://github.com./login/device", |
| 386 | "https://user:pass@github.com/login/device", |
| 387 | "https://github.com:8443/login/device", |
| 388 | "https://github.com/evil", |
| 389 | "https://github.com/login/device?user_code=ABCD-1234", |
| 390 | "https://github.com/login/device?", |
| 391 | "https://github.com/login/device?return_to=https://evil.example", |
| 392 | "https://github.com/login/device#frag", |
| 393 | "https://github.com/login/device#", |
| 394 | "https://github.com/login/device-evil", |
| 395 | "https://github.com/login/device/../../evil", |
| 396 | "https://github.com/login/device/%2e%2e/evil", |
| 397 | "https://github.com/login/device\\evil", |
| 398 | "https://github.com/login/device\r\n", |
| 399 | " https://github.com/login/device", |
| 400 | " ", |
| 401 | 12345, |
| 402 | ["https://github.com/login/device"], |
| 403 | ], |
| 404 | ) |
| 405 | def test_verification_uri_validator_rejects_unsafe_uris(uri): |
| 406 | assert setup_wizard._is_valid_verification_uri(uri) is False |
| 407 | |
| 408 | |
| 409 | @pytest.mark.parametrize( |
| 410 | "bad_uri", |
| 411 | [ |
| 412 | "file:///etc/passwd", |
| 413 | "javascript:alert(1)", |
| 414 | "http://github.com/login/device", |
| 415 | "https://phishing.example/login/device", |
| 416 | "https://user:pass@github.com/login/device", |
| 417 | " ", |
| 418 | ], |
| 419 | ) |
| 420 | def test_start_device_flow_aborts_before_browser_clipboard_or_stdout_on_bad_uri(bad_uri): |
| 421 | with mock.patch("lib.setup_wizard._existing_scrapecreators_key", return_value=None), \ |
| 422 | mock.patch("lib.setup_wizard.run_device_auth", return_value=("dev-1", "ABCD-1234", bad_uri, 5)), \ |
| 423 | mock.patch("lib.setup_wizard.subprocess.run") as mock_pbcopy, \ |
| 424 | mock.patch("webbrowser.open") as mock_browser: |
| 425 | out = io.StringIO() |
| 426 | with redirect_stdout(out): |
| 427 | public, handle = setup_wizard._start_device_flow() |
| 428 | |
| 429 | assert public["status"] == "error" |
| 430 | assert handle is None |
| 431 | mock_browser.assert_not_called() |
| 432 | mock_pbcopy.assert_not_called() |
| 433 | assert "device_code_ready" not in out.getvalue() |
| 434 | assert bad_uri.strip() not in out.getvalue() or not bad_uri.strip() |
| 435 | |
| 436 | |
| 437 | def test_run_device_auth_rejects_untrusted_verification_uri_response(): |
| 438 | payload = json.dumps( |
| 439 | { |
| 440 | "device_code": "dc-123", |
| 441 | "user_code": "ABCD-1234", |
| 442 | "verification_uri": "file:///etc/passwd", |
| 443 | "interval": 5, |
| 444 | } |
| 445 | ).encode("utf-8") |
| 446 | resp = mock.MagicMock() |
| 447 | resp.read.return_value = payload |
| 448 | resp.__enter__.return_value = resp |
| 449 | resp.__exit__.return_value = False |
| 450 | |
| 451 | with mock.patch("lib.setup_wizard.urlopen", return_value=resp): |
| 452 | assert setup_wizard.run_device_auth() is None |
| 453 | |
| 454 | |
| 455 | # --------------------------------------------------------------------------- |
| 456 | # HIGH-068: setup_wizard.py no-redirect http.open_request & error scrubbing |
| 457 | # --------------------------------------------------------------------------- |
| 458 | |
| 459 | |
| 460 | def test_setup_wizard_has_no_direct_urllib_urlopen_calls(): |
| 461 | source = Path(setup_wizard.__file__).read_text(encoding="utf-8") |
| 462 | tree = ast.parse(source) |
| 463 | for node in ast.walk(tree): |
| 464 | if isinstance(node, ast.ImportFrom) and node.module == "urllib.request": |
| 465 | names = {alias.name for alias in node.names} |
| 466 | assert "urlopen" not in names |
| 467 | |
| 468 | |
| 469 | def test_fetch_api_key_refuses_cross_origin_redirect_and_never_leaks_token(monkeypatch, serve): |
| 470 | attacker_url, attacker_requests = serve(payload={"api_key": "sc_forged_attacker_key"}) |
| 471 | victim_url, victim_requests = serve(redirect_to=f"{attacker_url}/steal") |
| 472 | monkeypatch.setattr(setup_wizard, "_DEVICE_BASE", f"{victim_url}/v1/github/device") |
| 473 | |
| 474 | result = setup_wizard.fetch_api_key("gho_top_secret_oauth_token_12345") |
| 475 | |
| 476 | assert result["ok"] is False |
| 477 | assert result["reason"] == "http_error" |
| 478 | assert result["http_status"] == 403 |
| 479 | assert attacker_requests == [] |
| 480 | assert len(victim_requests) == 1 |
| 481 | assert victim_requests[0][2]["authorization"] == "Bearer gho_top_secret_oauth_token_12345" |
| 482 | assert "gho_top_secret_oauth_token_12345" not in json.dumps(result) |
| 483 | |
| 484 | |
| 485 | def test_run_device_auth_and_poll_refuse_redirects(monkeypatch, serve): |
| 486 | attacker_url, attacker_requests = serve(payload={"access_token": "forged"}) |
| 487 | victim_url, _victim_requests = serve(redirect_to=f"{attacker_url}/steal") |
| 488 | monkeypatch.setattr(setup_wizard, "_DEVICE_BASE", f"{victim_url}/v1/github/device") |
| 489 | |
| 490 | assert setup_wizard.run_device_auth() is None |
| 491 | assert attacker_requests == [] |
| 492 | |
| 493 | # poll_device_auth fails fast on a refused redirect instead of looping until timeout. |
| 494 | with mock.patch("lib.setup_wizard.time.sleep") as mock_sleep, \ |
| 495 | mock.patch("lib.setup_wizard.time.time", return_value=0): |
| 496 | assert setup_wizard.poll_device_auth("dc-secret-123", interval=1, timeout=300) is None |
| 497 | mock_sleep.assert_called_once_with(1) |
| 498 | assert attacker_requests == [] |
| 499 | |
| 500 | |
| 501 | def test_device_auth_refuses_redirects_and_ignores_wrapped_urllib_urlopen(monkeypatch, serve): |
| 502 | attacker_url, attacker_requests = serve(payload={"api_key": "sc_stolen"}) |
| 503 | victim_url, _victim_requests = serve(redirect_to=f"{attacker_url}/steal") |
| 504 | monkeypatch.setattr(setup_wizard, "_DEVICE_BASE", f"{victim_url}/v1/github/device") |
| 505 | |
| 506 | def forbidden_urlopen(*_args, **_kwargs): |
| 507 | raise AssertionError("setup_wizard must not delegate through urllib.request.urlopen") |
| 508 | |
| 509 | with mock.patch("urllib.request.urlopen", side_effect=forbidden_urlopen): |
| 510 | res = setup_wizard.fetch_api_key("gho_secret_oauth_token_wrapped") |
| 511 | assert res["ok"] is False |
| 512 | assert res["http_status"] == 403 |
| 513 | assert setup_wizard.run_device_auth() is None |
| 514 | with mock.patch("lib.setup_wizard.time.sleep"), \ |
| 515 | mock.patch("lib.setup_wizard.time.time", return_value=0): |
| 516 | assert setup_wizard.poll_device_auth("dc-123", interval=1, timeout=300) is None |
| 517 | |
| 518 | assert attacker_requests == [] |
| 519 | |
| 520 | |
| 521 | def test_device_opener_enforces_https_only_and_drops_non_https_handlers(monkeypatch): |
| 522 | monkeypatch.setenv("HTTP_PROXY", "http://proxy.example.test:8080") |
| 523 | monkeypatch.setenv("HTTPS_PROXY", "http://https-proxy.example.test:8443") |
| 524 | opener = setup_wizard._build_device_opener(loopback_http=False) |
| 525 | for scheme in ("http", "file", "ftp", "data"): |
| 526 | assert scheme not in opener.handle_open |
| 527 | assert "https" in opener.handle_open |
| 528 | proxy_handlers = [h for h in opener.handlers if isinstance(h, urllib.request.ProxyHandler)] |
| 529 | assert len(proxy_handlers) == 1 |
| 530 | assert set(proxy_handlers[0].proxies.keys()) <= {"https"} |
| 531 | |
| 532 | for bad_url in ("http://remote.example.test/v1/github/device/profile", "file:///etc/passwd", "ftp://example.test/x"): |
| 533 | with pytest.raises(urllib.error.URLError): |
| 534 | setup_wizard._default_urlopen(urllib.request.Request(bad_url), timeout=1) |
| 535 | |
| 536 | |
| 537 | def test_device_auth_bounds_response_size_validates_json_and_closes_http_errors(): |
| 538 | oversized = b'{"api_key":"' + (b"a" * (setup_wizard._MAX_DEVICE_RESPONSE_BYTES + 10)) + b'"}' |
| 539 | for bad_payload in (oversized, b"not-json", b'["not-a-dict"]'): |
| 540 | resp = mock.MagicMock() |
| 541 | resp.read.side_effect = lambda n=-1, data=bad_payload: data[:n] if n >= 0 else data |
| 542 | resp.__enter__.return_value = resp |
| 543 | resp.__exit__.return_value = False |
| 544 | with mock.patch("lib.setup_wizard.urlopen", return_value=resp): |
| 545 | assert setup_wizard.run_device_auth() is None |
| 546 | res = setup_wizard.fetch_api_key("gho_valid_tok") |
| 547 | assert res["ok"] is False and res["reason"] == "request_failed" |
| 548 | with mock.patch("lib.setup_wizard.time.sleep"), \ |
| 549 | mock.patch("lib.setup_wizard.time.time", return_value=0): |
| 550 | assert setup_wizard.poll_device_auth("dc-1", interval=1, timeout=300) is None |
| 551 | |
| 552 | # Verify HTTPError streams are always closed across all three callers. |
| 553 | closed_flags = [] |
| 554 | |
| 555 | class TrackingBytesIO(io.BytesIO): |
| 556 | def close(self): |
| 557 | closed_flags.append(True) |
| 558 | super().close() |
| 559 | |
| 560 | def make_err(code=401): |
| 561 | return urllib.error.HTTPError( |
| 562 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 563 | code, |
| 564 | "Err", |
| 565 | {}, |
| 566 | TrackingBytesIO(b'{"error":"fail"}'), |
| 567 | ) |
| 568 | |
| 569 | with mock.patch("lib.setup_wizard.urlopen", side_effect=lambda *a, **k: (_ for _ in ()).throw(make_err(401))): |
| 570 | setup_wizard.run_device_auth() |
| 571 | setup_wizard.fetch_api_key("gho_valid_tok") |
| 572 | with mock.patch("lib.setup_wizard.time.sleep"), \ |
| 573 | mock.patch("lib.setup_wizard.time.time", return_value=0): |
| 574 | setup_wizard.poll_device_auth("dc-1", interval=1, timeout=300) |
| 575 | |
| 576 | assert len(closed_flags) >= 3 |
| 577 | |
| 578 | |
| 579 | def test_setup_wizard_scrub_handles_at_password_and_whitespace_secret(): |
| 580 | assert setup_wizard._scrub_error_text( |
| 581 | "https://alice:p@ss@word@api.scrapecreators.com/profile", secrets=(" ",) |
| 582 | ) == "https://api.scrapecreators.com/profile" |
| 583 | assert setup_wizard._scrub_error_text("plain message with spaces", secrets=(" ",)) == "plain message with spaces" |
| 584 | |
| 585 | |
| 586 | def test_http_error_detail_redacts_escaped_quotes_in_json_and_omits_unclosed_secret_bodies(caplog): |
| 587 | # 1. Valid JSON /profile 500 with escaped quote inside access_token: neither half leaks. |
| 588 | escaped_json_body = json.dumps( |
| 589 | {"error": "bad", "access_token": 'gho_part1"part2_secret_tail'} |
| 590 | ).encode("utf-8") |
| 591 | |
| 592 | def fake_500_json(_req, timeout=15): |
| 593 | raise urllib.error.HTTPError( |
| 594 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 595 | 500, |
| 596 | "Internal Server Error", |
| 597 | {}, |
| 598 | io.BytesIO(escaped_json_body), |
| 599 | ) |
| 600 | |
| 601 | with caplog.at_level("WARNING", logger=setup_wizard.logger.name), \ |
| 602 | mock.patch("lib.setup_wizard.time.sleep"), \ |
| 603 | mock.patch("lib.setup_wizard.urlopen", side_effect=fake_500_json): |
| 604 | res_json = setup_wizard.fetch_api_key("gho_unrelated_caller_tok") |
| 605 | |
| 606 | combined_json = json.dumps(res_json) + "\n" + caplog.text |
| 607 | assert res_json["ok"] is False |
| 608 | assert res_json["http_status"] == 500 |
| 609 | assert "part1" not in combined_json |
| 610 | assert "part2_secret_tail" not in combined_json |
| 611 | assert "bad" in res_json["detail"] |
| 612 | |
| 613 | # 2. Non-JSON body with escaped quote inside a secret field: regex scrubs across escaped quote. |
| 614 | non_json_escaped = 'upstream failed: access_token="raw_part1\\"raw_part2_secret_tail" status=500' |
| 615 | scrubbed = setup_wizard._scrub_error_text(non_json_escaped) |
| 616 | assert "raw_part1" not in scrubbed |
| 617 | assert "raw_part2_secret_tail" not in scrubbed |
| 618 | |
| 619 | # 3. Malformed / truncated non-JSON body with unclosed quote on a secret field: body omitted. |
| 620 | caplog.clear() |
| 621 | unclosed_body = b'error: access_token="unclosed_part1\\"unclosed_part2_secret_tail' |
| 622 | |
| 623 | def fake_500_unclosed(_req, timeout=15): |
| 624 | raise urllib.error.HTTPError( |
| 625 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 626 | 500, |
| 627 | "Internal Server Error", |
| 628 | {}, |
| 629 | io.BytesIO(unclosed_body), |
| 630 | ) |
| 631 | |
| 632 | with caplog.at_level("WARNING", logger=setup_wizard.logger.name), \ |
| 633 | mock.patch("lib.setup_wizard.time.sleep"), \ |
| 634 | mock.patch("lib.setup_wizard.urlopen", side_effect=fake_500_unclosed): |
| 635 | res_unclosed = setup_wizard.fetch_api_key("gho_unrelated_caller_tok") |
| 636 | |
| 637 | combined_unclosed = json.dumps(res_unclosed) + "\n" + caplog.text |
| 638 | assert res_unclosed["ok"] is False |
| 639 | assert "unclosed_part1" not in combined_unclosed |
| 640 | assert "unclosed_part2_secret_tail" not in combined_unclosed |
| 641 | assert "body=" not in res_unclosed["detail"] |
| 642 | |
| 643 | |
| 644 | def test_http_error_detail_handles_deeply_nested_json_and_scrubs_json_dict_keys(caplog): |
| 645 | # 1. Deeply nested JSON (within 64 KiB) must never crash with RecursionError |
| 646 | # and must preserve 5xx retries on both Python 3.12 and 3.13+. |
| 647 | deep_list = (b"[" * 20000) + (b"]" * 20000) |
| 648 | deep_obj = (b'{"a":' * 5000) + b'"deep_secret_value"' + (b"}" * 5000) |
| 649 | for payload in (deep_list, deep_obj): |
| 650 | attempts = {"n": 0} |
| 651 | |
| 652 | def fake_deep_500(_req, timeout=15, data=payload): |
| 653 | attempts["n"] += 1 |
| 654 | raise urllib.error.HTTPError( |
| 655 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 656 | 500, |
| 657 | "Internal Server Error", |
| 658 | {}, |
| 659 | io.BytesIO(data), |
| 660 | ) |
| 661 | |
| 662 | with mock.patch("lib.setup_wizard.time.sleep"), \ |
| 663 | mock.patch("lib.setup_wizard.urlopen", side_effect=fake_deep_500): |
| 664 | res = setup_wizard.fetch_api_key("gho_deep_retry_tok") |
| 665 | |
| 666 | assert res["ok"] is False |
| 667 | assert res["reason"] == "upstream_error" |
| 668 | assert res["http_status"] == 500 |
| 669 | assert attempts["n"] == setup_wizard._PROFILE_FETCH_ATTEMPTS |
| 670 | assert "deep_secret_value" not in res["detail"] |
| 671 | assert ("body=" not in res["detail"]) or ("[REDACTED]" in res["detail"]) |
| 672 | |
| 673 | # Explicit RecursionError from json.loads must fall back cleanly to status/reason alone. |
| 674 | rec_attempts = {"n": 0} |
| 675 | |
| 676 | def fake_rec_500(_req, timeout=15): |
| 677 | rec_attempts["n"] += 1 |
| 678 | raise urllib.error.HTTPError( |
| 679 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 680 | 500, |
| 681 | "Internal Server Error", |
| 682 | {}, |
| 683 | io.BytesIO(b'{"a":{"b":1}}'), |
| 684 | ) |
| 685 | |
| 686 | with mock.patch("lib.setup_wizard.time.sleep"), \ |
| 687 | mock.patch("lib.setup_wizard.json.loads", side_effect=RecursionError("max recursion")), \ |
| 688 | mock.patch("lib.setup_wizard.urlopen", side_effect=fake_rec_500): |
| 689 | rec_res = setup_wizard.fetch_api_key("gho_deep_retry_tok") |
| 690 | assert rec_res["ok"] is False |
| 691 | assert rec_res["reason"] == "upstream_error" |
| 692 | assert rec_attempts["n"] == setup_wizard._PROFILE_FETCH_ATTEMPTS |
| 693 | assert "body=" not in rec_res["detail"] |
| 694 | |
| 695 | # Moderate deep nesting parses but is capped at _MAX_JSON_REDACT_DEPTH. |
| 696 | nested_20 = (b'{"a":' * 20) + b'"deep_secret_value"' + (b"}" * 20) |
| 697 | err_20 = urllib.error.HTTPError( |
| 698 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 699 | 500, |
| 700 | "Internal Server Error", |
| 701 | {}, |
| 702 | io.BytesIO(nested_20), |
| 703 | ) |
| 704 | detail_20 = setup_wizard._http_error_detail(err_20) |
| 705 | assert "deep_secret_value" not in detail_20 |
| 706 | assert "[REDACTED]" in detail_20 |
| 707 | |
| 708 | # 2. Submitted access_token used as a top-level or nested JSON key must never leak. |
| 709 | submitted_tok = "opaque_keyname_secret_7777" |
| 710 | for payload_dict in ( |
| 711 | {submitted_tok: "bad"}, |
| 712 | {"detail": {submitted_tok: "x"}}, |
| 713 | ): |
| 714 | caplog.clear() |
| 715 | raw_body = json.dumps(payload_dict).encode("utf-8") |
| 716 | |
| 717 | def fake_401(_req, timeout=15, data=raw_body): |
| 718 | raise urllib.error.HTTPError( |
| 719 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 720 | 401, |
| 721 | "Unauthorized", |
| 722 | {}, |
| 723 | io.BytesIO(data), |
| 724 | ) |
| 725 | |
| 726 | with caplog.at_level("WARNING", logger=setup_wizard.logger.name), \ |
| 727 | mock.patch("lib.setup_wizard.urlopen", side_effect=fake_401): |
| 728 | res = setup_wizard.fetch_api_key(submitted_tok) |
| 729 | |
| 730 | combined = json.dumps(res) + "\n" + caplog.text |
| 731 | assert res["ok"] is False |
| 732 | assert res["http_status"] == 401 |
| 733 | assert submitted_tok not in combined |
| 734 | |
| 735 | |
| 736 | def test_fetch_api_key_scrubs_access_token_and_secrets_from_http_error_bodies(caplog): |
| 737 | opaque_token = "opaque_tok_9876543210_SECRET" |
| 738 | # Place token across the 200-char boundary to prove scrubbing happens before truncation. |
| 739 | prefix = "x" * 190 |
| 740 | body = ( |
| 741 | f"{prefix}{opaque_token} " |
| 742 | 'Authorization: Bearer bearer_leaked_abc123 ' |
| 743 | 'gho_github_leaked_token_999 ' |
| 744 | '{"api_key":"sc_leaked_999","access_token":"tok_leaked_888"} ' |
| 745 | "https://bob:pwsecret@api.scrapecreators.com/profile" |
| 746 | ).encode("utf-8") |
| 747 | |
| 748 | def fake_error(_req, timeout=15): |
| 749 | raise urllib.error.HTTPError( |
| 750 | "https://api.scrapecreators.com/v1/github/device/profile", |
| 751 | 401, |
| 752 | f"Unauthorized for {opaque_token}", |
| 753 | {}, |
| 754 | io.BytesIO(body), |
| 755 | ) |
| 756 | |
| 757 | with caplog.at_level("WARNING", logger=setup_wizard.logger.name), \ |
| 758 | mock.patch("lib.setup_wizard.urlopen", side_effect=fake_error): |
| 759 | result = setup_wizard.fetch_api_key(opaque_token) |
| 760 | |
| 761 | assert result["ok"] is False |
| 762 | assert result["reason"] == "http_error" |
| 763 | assert result["http_status"] == 401 |
| 764 | combined = json.dumps(result) + "\n" + caplog.text |
| 765 | for leaked in ( |
| 766 | opaque_token, |
| 767 | "opaque_tok_9876", |
| 768 | "bearer_leaked_abc123", |
| 769 | "gho_github_leaked_token_999", |
| 770 | "sc_leaked_999", |
| 771 | "tok_leaked_888", |
| 772 | "pwsecret", |
| 773 | ): |
| 774 | assert leaked not in combined |
| 775 | assert "[REDACTED]" in result["detail"] |
| 776 | |
| 777 | |
| 778 | def test_fetch_api_key_rejects_control_chars_in_access_token_without_echoing(): |
| 779 | bad_token = "gho_bad_token_SECRET\r\nX-Injected: 1" |
| 780 | with mock.patch("lib.setup_wizard.urlopen") as mock_urlopen: |
| 781 | result = setup_wizard.fetch_api_key(bad_token) |
| 782 | |
| 783 | mock_urlopen.assert_not_called() |
| 784 | assert result["ok"] is False |
| 785 | assert result["reason"] == "request_failed" |
| 786 | assert "gho_bad_token_SECRET" not in json.dumps(result) |
| 787 | |
| 788 | |
| 789 | # --------------------------------------------------------------------------- |
| 790 | # HIGH-078: setup-keychain.sh pins security binary & passes secret via stdin |
| 791 | # --------------------------------------------------------------------------- |
| 792 | |
| 793 | |
| 794 | @pytest.mark.skipif(os.name == "nt", reason="POSIX shell script") |
| 795 | def test_setup_keychain_bash_syntax_and_no_argv_secret_flag(): |
| 796 | check = subprocess.run(["bash", "-n", str(SETUP_KEYCHAIN_SH)], capture_output=True, text=True, timeout=10) |
| 797 | assert check.returncode == 0, check.stderr |
| 798 | script = SETUP_KEYCHAIN_SH.read_text(encoding="utf-8") |
| 799 | assert '-w "$value"' not in script |
| 800 | assert "command -v security" not in script |
| 801 | assert 'if [[ -x /usr/bin/security ]]; then\n SECURITY_BIN="/usr/bin/security"' in script |
| 802 | assert 'SECURITY_BIN="${SECURITY_BIN:-' not in script |
| 803 | |
| 804 | |
| 805 | @pytest.mark.skipif( |
| 806 | os.name == "nt" or Path("/usr/bin/security").exists(), |
| 807 | reason="POSIX non-macOS shell fixture (macOS pins /usr/bin/security unconditionally)", |
| 808 | ) |
| 809 | def test_setup_keychain_ignores_path_shadow_and_passes_hex_via_stdin(tmp_path): |
| 810 | # 1. A shadowed `security` on PATH (or SECURITY_BIN env var) must never be executed. |
| 811 | rogue_dir = tmp_path / "rogue" |
| 812 | rogue_dir.mkdir() |
| 813 | rogue = rogue_dir / "security" |
| 814 | rogue_marker = tmp_path / "rogue-ran" |
| 815 | rogue.write_text(f"#!/bin/sh\necho PWNED > {shlex.quote(str(rogue_marker))}\nexit 0\n", encoding="utf-8") |
| 816 | rogue.chmod(0o755) |
| 817 | res = subprocess.run( |
| 818 | ["/bin/bash", str(SETUP_KEYCHAIN_SH), "OPENAI_API_KEY"], |
| 819 | input="dummy-secret\n", |
| 820 | text=True, |
| 821 | capture_output=True, |
| 822 | timeout=10, |
| 823 | env={"PATH": str(rogue_dir), "SECURITY_BIN": str(rogue), "USER": "alice", "OSTYPE": "darwin"}, |
| 824 | ) |
| 825 | assert res.returncode != 0 |
| 826 | assert not rogue_marker.exists() |
| 827 | |
| 828 | # 2. With LAST30DAYS_TEST_SECURITY_BIN stubbed, secret with quotes/spaces/backslashes/$/!/UTF-8 |
| 829 | # never appears in argv and decodes identically from `-X <hex>` on stdin. |
| 830 | records = tmp_path / "security-records.jsonl" |
| 831 | stub = tmp_path / "security-stub" |
| 832 | stub.write_text( |
| 833 | f"#!{sys.executable}\n" |
| 834 | "import json, os, sys\n" |
| 835 | "argv = sys.argv[1:]\n" |
| 836 | "stdin_data = sys.stdin.read() if argv == ['-i'] else ''\n" |
| 837 | "with open(os.environ['RECORDS'], 'a', encoding='utf-8') as f:\n" |
| 838 | " f.write(json.dumps({'argv': argv, 'stdin': stdin_data}) + '\\n')\n" |
| 839 | "if argv and argv[0] == 'find-generic-password':\n" |
| 840 | " sys.exit(44)\n" |
| 841 | "if argv == ['-i']:\n" |
| 842 | " sys.exit(0)\n" |
| 843 | "if argv and argv[0] == 'delete-generic-password':\n" |
| 844 | " sys.exit(0)\n" |
| 845 | "sys.exit(99)\n", |
| 846 | encoding="utf-8", |
| 847 | ) |
| 848 | stub.chmod(0o755) |
| 849 | |
| 850 | tricky_secret = """sk-live-'single' "double" \\slash $var !bang café🔑""" |
| 851 | res = subprocess.run( |
| 852 | ["/bin/bash", str(SETUP_KEYCHAIN_SH), "OPENAI_API_KEY"], |
| 853 | input=tricky_secret + "\n", |
| 854 | text=True, |
| 855 | capture_output=True, |
| 856 | timeout=10, |
| 857 | env={ |
| 858 | "PATH": str(tmp_path), |
| 859 | "LAST30DAYS_TEST_SECURITY_BIN": str(stub), |
| 860 | "USER": "alice", |
| 861 | "OSTYPE": "darwin", |
| 862 | "RECORDS": str(records), |
| 863 | }, |
| 864 | ) |
| 865 | assert res.returncode == 0, res.stderr |
| 866 | assert "added=1 replaced=0 skipped=0" in res.stdout |
| 867 | assert tricky_secret not in res.stdout + res.stderr |
| 868 | |
| 869 | calls = [json.loads(line) for line in records.read_text(encoding="utf-8").splitlines()] |
| 870 | assert len(calls) == 2 |
| 871 | assert calls[0]["argv"] == ["find-generic-password", "-a", "alice", "-s", "last30days-OPENAI_API_KEY"] |
| 872 | assert calls[1]["argv"] == ["-i"] |
| 873 | assert tricky_secret not in json.dumps(calls[1]["argv"]) |
| 874 | |
| 875 | tokens = shlex.split(calls[1]["stdin"].strip()) |
| 876 | assert tokens[:6] == [ |
| 877 | "add-generic-password", |
| 878 | "-U", |
| 879 | "-a", |
| 880 | "alice", |
| 881 | "-s", |
| 882 | "last30days-OPENAI_API_KEY", |
| 883 | ] |
| 884 | assert tokens[6] == "-X" |
| 885 | decoded = bytes.fromhex(tokens[7]).decode("utf-8") |
| 886 | assert decoded == tricky_secret |
| 887 | |
| 888 | # 3. EOF without trailing newline still stores value; empty EOF skips cleanly under set -e. |
| 889 | records.unlink() |
| 890 | eof_val = subprocess.run( |
| 891 | ["/bin/bash", str(SETUP_KEYCHAIN_SH), "OPENAI_API_KEY"], |
| 892 | input="eof-no-newline-secret", |
| 893 | text=True, |
| 894 | capture_output=True, |
| 895 | timeout=10, |
| 896 | env={"PATH": str(tmp_path), "LAST30DAYS_TEST_SECURITY_BIN": str(stub), "USER": "alice", "OSTYPE": "darwin", "RECORDS": str(records)}, |
| 897 | ) |
| 898 | assert eof_val.returncode == 0, eof_val.stderr |
| 899 | assert "added=1 replaced=0 skipped=0" in eof_val.stdout |
| 900 | eof_calls = [json.loads(line) for line in records.read_text(encoding="utf-8").splitlines()] |
| 901 | assert bytes.fromhex(shlex.split(eof_calls[1]["stdin"].strip())[7]).decode("utf-8") == "eof-no-newline-secret" |
| 902 | |
| 903 | records.unlink() |
| 904 | eof_empty = subprocess.run( |
| 905 | ["/bin/bash", str(SETUP_KEYCHAIN_SH), "OPENAI_API_KEY"], |
| 906 | input="", |
| 907 | text=True, |
| 908 | capture_output=True, |
| 909 | timeout=10, |
| 910 | env={"PATH": str(tmp_path), "LAST30DAYS_TEST_SECURITY_BIN": str(stub), "USER": "alice", "OSTYPE": "darwin", "RECORDS": str(records)}, |
| 911 | ) |
| 912 | assert eof_empty.returncode == 0, eof_empty.stderr |
| 913 | assert "added=0 replaced=0 skipped=1" in eof_empty.stdout |
| 914 | |
| 915 | # 4. Unknown / injection keys are rejected with exit 2 before calling security. |
| 916 | records.unlink() |
| 917 | bad_res = subprocess.run( |
| 918 | ["/bin/bash", str(SETUP_KEYCHAIN_SH), "--delete", "../evil"], |
| 919 | text=True, |
| 920 | capture_output=True, |
| 921 | timeout=10, |
| 922 | env={"PATH": str(tmp_path), "LAST30DAYS_TEST_SECURITY_BIN": str(stub), "USER": "alice", "OSTYPE": "darwin", "RECORDS": str(records)}, |
| 923 | ) |
| 924 | assert bad_res.returncode == 2 |
| 925 | assert not records.exists() |
| 926 | |
| 927 | |
| 928 | @pytest.mark.skipif( |
| 929 | sys.platform != "darwin" or not Path("/usr/bin/security").is_file(), |
| 930 | reason="macOS /usr/bin/security only", |
| 931 | ) |
| 932 | def test_macos_temporary_keychain_security_interactive_hex_roundtrip(tmp_path): |
| 933 | """Exercise real `/usr/bin/security -i` add-generic-password `-X <hex>` against an isolated temp keychain.""" |
| 934 | kc_path = tmp_path / "last30days-test.keychain-db" |
| 935 | kc_pass = "tmp-keychain-pass-0001" |
| 936 | account = "last30days-ci-test" |
| 937 | service = "last30days-TEST_ROUNDTRIP" |
| 938 | |
| 939 | def _run_security(*args, stdin_text: str | None = None): |
| 940 | return subprocess.run( |
| 941 | ["/usr/bin/security", *args], |
| 942 | input=stdin_text, |
| 943 | text=True, |
| 944 | capture_output=True, |
| 945 | timeout=15, |
| 946 | ) |
| 947 | |
| 948 | create = _run_security("create-keychain", "-p", kc_pass, str(kc_path)) |
| 949 | assert create.returncode == 0, create.stderr |
| 950 | try: |
| 951 | unlock = _run_security("unlock-keychain", "-p", kc_pass, str(kc_path)) |
| 952 | assert unlock.returncode == 0, unlock.stderr |
| 953 | |
| 954 | escaped_kc = str(kc_path).replace("\\", "\\\\").replace('"', '\\"') |
| 955 | for secret in ( |
| 956 | """sk-live-'single' "double" \\slash $var !bang""", |
| 957 | "café🔑-utf8-secret", |
| 958 | ): |
| 959 | hex_val = secret.encode("utf-8").hex() |
| 960 | cmd_line = ( |
| 961 | f'add-generic-password -U -a "{account}" -s "{service}" ' |
| 962 | f'-X {hex_val} "{escaped_kc}"\n' |
| 963 | ) |
| 964 | add = _run_security("-i", stdin_text=cmd_line) |
| 965 | assert add.returncode == 0, add.stderr |
| 966 | |
| 967 | read_back = _run_security( |
| 968 | "find-generic-password", "-a", account, "-s", service, "-w", str(kc_path) |
| 969 | ) |
| 970 | assert read_back.returncode == 0, read_back.stderr |
| 971 | raw_out = read_back.stdout.rstrip("\r\n") |
| 972 | if raw_out == hex_val: |
| 973 | assert bytes.fromhex(raw_out).decode("utf-8") == secret |
| 974 | else: |
| 975 | assert raw_out == secret |
| 976 | finally: |
| 977 | _run_security("delete-keychain", str(kc_path)) |
| 978 | |
| 979 | |
| 980 | # --------------------------------------------------------------------------- |
| 981 | # HIGH-085: setup-pass.sh prefix validation, key allowlist & `--` markers |
| 982 | # --------------------------------------------------------------------------- |
| 983 | |
| 984 | |
| 985 | @pytest.mark.skipif(os.name == "nt", reason="POSIX shell script") |
| 986 | def test_setup_pass_bash_syntax_and_bash32_safe_regexes(): |
| 987 | check = subprocess.run(["bash", "-n", str(SETUP_PASS_SH)], capture_output=True, text=True, timeout=10) |
| 988 | assert check.returncode == 0, check.stderr |
| 989 | for script_path in (SETUP_PASS_SH, SETUP_KEYCHAIN_SH): |
| 990 | text = script_path.read_text(encoding="utf-8") |
| 991 | lines = text.splitlines() |
| 992 | # Ensure every `=~` uses a variable RHS (Bash 3.2 rejects inline parentheses). |
| 993 | for line in lines: |
| 994 | stripped = line.strip() |
| 995 | if "=~" in stripped and not stripped.startswith("#"): |
| 996 | assert "=~ $" in stripped, f"inline regex in {script_path.name}: {line}" |
| 997 | # Ensure every `"${TARGETS[@]}"` expansion is preceded by a `${#TARGETS[@]}` non-empty guard |
| 998 | # (macOS Bash 3.2 aborts on empty `"${arr[@]}"` under `set -u`). |
| 999 | for idx, line in enumerate(lines): |
| 1000 | if '"${TARGETS[@]}"' in line: |
| 1001 | window = "\n".join(lines[max(0, idx - 10):idx]) |
| 1002 | assert "${#TARGETS[@]}" in window, ( |
| 1003 | f"unguarded TARGETS[@] expansion in {script_path.name}:{idx + 1}: {line}" |
| 1004 | ) |
| 1005 | # Ensure bare `"$@"` after `shift` is guarded by `$# -gt 0` (Bash 3.2 `set -u`). |
| 1006 | for line in lines: |
| 1007 | if '"$@"' in line and not line.strip().startswith("#"): |
| 1008 | assert "$# -gt 0" in line, f"unguarded $@ expansion in {script_path.name}: {line}" |
| 1009 | |
| 1010 | |
| 1011 | @pytest.fixture |
| 1012 | def mock_pass_env(tmp_path): |
| 1013 | store = tmp_path / "store" |
| 1014 | store.mkdir() |
| 1015 | bin_dir = tmp_path / "bin" |
| 1016 | bin_dir.mkdir() |
| 1017 | calls_file = tmp_path / "pass-calls.jsonl" |
| 1018 | pass_bin = bin_dir / "pass" |
| 1019 | pass_bin.write_text( |
| 1020 | f"#!{sys.executable}\n" |
| 1021 | "import json, os, pathlib, sys\n" |
| 1022 | "args = sys.argv[1:]\n" |
| 1023 | "with open(os.environ['PASS_CALLS'], 'a', encoding='utf-8') as f:\n" |
| 1024 | " f.write(json.dumps(args) + '\\n')\n" |
| 1025 | "if args and args[0] == 'insert':\n" |
| 1026 | " target = pathlib.Path(os.environ['PASSWORD_STORE_DIR']) / (args[-1] + '.gpg')\n" |
| 1027 | " target.parent.mkdir(parents=True, exist_ok=True)\n" |
| 1028 | " target.write_text(sys.stdin.read(), encoding='utf-8')\n" |
| 1029 | " sys.exit(0)\n" |
| 1030 | "if args and args[0] == 'show':\n" |
| 1031 | " target = pathlib.Path(os.environ['PASSWORD_STORE_DIR']) / (args[-1] + '.gpg')\n" |
| 1032 | " sys.exit(0 if target.exists() else 1)\n" |
| 1033 | "if args and args[0] == 'rm':\n" |
| 1034 | " target = pathlib.Path(os.environ['PASSWORD_STORE_DIR']) / (args[-1] + '.gpg')\n" |
| 1035 | " if target.exists():\n" |
| 1036 | " target.unlink()\n" |
| 1037 | " sys.exit(0)\n" |
| 1038 | " sys.exit(1)\n" |
| 1039 | "sys.exit(3)\n", |
| 1040 | encoding="utf-8", |
| 1041 | ) |
| 1042 | pass_bin.chmod(0o755) |
| 1043 | base_env = { |
| 1044 | "PATH": str(bin_dir) + os.pathsep + os.environ.get("PATH", ""), |
| 1045 | "PASSWORD_STORE_DIR": str(store), |
| 1046 | "PASS_CALLS": str(calls_file), |
| 1047 | } |
| 1048 | return store, calls_file, base_env |
| 1049 | |
| 1050 | |
| 1051 | @pytest.mark.skipif(os.name == "nt", reason="POSIX shell script") |
| 1052 | @pytest.mark.parametrize( |
| 1053 | "bad_prefix", |
| 1054 | [ |
| 1055 | "-r", |
| 1056 | "-c/", |
| 1057 | "/", |
| 1058 | "/etc/pass/", |
| 1059 | "..", |
| 1060 | "../", |
| 1061 | "last30days/../other/", |
| 1062 | ".", |
| 1063 | "./", |
| 1064 | "last30days/./other/", |
| 1065 | ".git/", |
| 1066 | ".gpg-id/", |
| 1067 | "last30days//sub/", |
| 1068 | "last30days/-r/", |
| 1069 | "last 30 days/", |
| 1070 | "last30days\n-r/", |
| 1071 | "last30days/\n", |
| 1072 | " ", |
| 1073 | ], |
| 1074 | ) |
| 1075 | def test_setup_pass_rejects_unsafe_prefix(mock_pass_env, bad_prefix): |
| 1076 | _store, calls_file, base_env = mock_pass_env |
| 1077 | env_vars = {**base_env, "LAST30DAYS_PASS_PREFIX": bad_prefix} |
| 1078 | |
| 1079 | for args in (["OPENAI_API_KEY"], ["--list"], ["--delete", "OPENAI_API_KEY"]): |
| 1080 | res = subprocess.run( |
| 1081 | ["bash", str(SETUP_PASS_SH), *args], |
| 1082 | input="secret\n", |
| 1083 | text=True, |
| 1084 | capture_output=True, |
| 1085 | timeout=10, |
| 1086 | env=env_vars, |
| 1087 | ) |
| 1088 | assert res.returncode == 2, f"expected exit 2 for prefix={bad_prefix!r} args={args}" |
| 1089 | assert not calls_file.exists() |
| 1090 | |
| 1091 | |
| 1092 | @pytest.mark.skipif(os.name == "nt", reason="POSIX shell script") |
| 1093 | @pytest.mark.parametrize( |
| 1094 | "bad_key", |
| 1095 | [ |
| 1096 | "../other", |
| 1097 | "sub/OPENAI_API_KEY", |
| 1098 | "OPENAI_API_KEY.gpg", |
| 1099 | "NOT_A_VALID_KEY", |
| 1100 | "-r", |
| 1101 | "foo bar", |
| 1102 | "OPENAI_API_KEY\n", |
| 1103 | ], |
| 1104 | ) |
| 1105 | def test_setup_pass_rejects_unlisted_or_traversal_keys(mock_pass_env, bad_key): |
| 1106 | _store, calls_file, base_env = mock_pass_env |
| 1107 | for args in (["--", bad_key], ["--delete", "--", bad_key]): |
| 1108 | res = subprocess.run( |
| 1109 | ["bash", str(SETUP_PASS_SH), *args], |
| 1110 | input="secret\n", |
| 1111 | text=True, |
| 1112 | capture_output=True, |
| 1113 | timeout=10, |
| 1114 | env=base_env, |
| 1115 | ) |
| 1116 | assert res.returncode == 2, f"expected exit 2 for key={bad_key!r} args={args}" |
| 1117 | assert not calls_file.exists() |
| 1118 | |
| 1119 | |
| 1120 | @pytest.mark.skipif(os.name == "nt", reason="POSIX shell script") |
| 1121 | def test_setup_pass_uses_end_of_options_and_preserves_prefix(mock_pass_env): |
| 1122 | store, calls_file, base_env = mock_pass_env |
| 1123 | env_vars = {**base_env, "LAST30DAYS_PASS_PREFIX": "secrets/l30/"} |
| 1124 | |
| 1125 | # Insert |
| 1126 | ins = subprocess.run( |
| 1127 | ["bash", str(SETUP_PASS_SH), "OPENAI_API_KEY"], |
| 1128 | input="sk-dummy-1\n", |
| 1129 | text=True, |
| 1130 | capture_output=True, |
| 1131 | timeout=10, |
| 1132 | env=env_vars, |
| 1133 | ) |
| 1134 | assert ins.returncode == 0, ins.stderr |
| 1135 | assert (store / "secrets" / "l30" / "OPENAI_API_KEY.gpg").read_text(encoding="utf-8") == "sk-dummy-1\n" |
| 1136 | |
| 1137 | # List |
| 1138 | lst = subprocess.run( |
| 1139 | ["bash", str(SETUP_PASS_SH), "--list"], |
| 1140 | text=True, |
| 1141 | capture_output=True, |
| 1142 | timeout=10, |
| 1143 | env=env_vars, |
| 1144 | ) |
| 1145 | assert lst.returncode == 0, lst.stderr |
| 1146 | assert "OPENAI_API_KEY" in lst.stdout |
| 1147 | |
| 1148 | # Delete |
| 1149 | rm = subprocess.run( |
| 1150 | ["bash", str(SETUP_PASS_SH), "--delete", "OPENAI_API_KEY"], |
| 1151 | text=True, |
| 1152 | capture_output=True, |
| 1153 | timeout=10, |
| 1154 | env=env_vars, |
| 1155 | ) |
| 1156 | assert rm.returncode == 0, rm.stderr |
| 1157 | assert "deleted: OPENAI_API_KEY" in rm.stdout |
| 1158 | |
| 1159 | calls = [json.loads(line) for line in calls_file.read_text(encoding="utf-8").splitlines()] |
| 1160 | assert ["insert", "-m", "--", "secrets/l30/OPENAI_API_KEY"] in calls |
| 1161 | assert ["show", "--", "secrets/l30/OPENAI_API_KEY"] in calls |
| 1162 | assert ["rm", "-f", "--", "secrets/l30/OPENAI_API_KEY"] in calls |
| 1163 | |
| 1164 | # EOF without trailing newline stores value cleanly; empty EOF skips without crashing. |
| 1165 | eof_ins = subprocess.run( |
| 1166 | ["bash", str(SETUP_PASS_SH), "XAI_API_KEY"], |
| 1167 | input="xai-no-newline", |
| 1168 | text=True, |
| 1169 | capture_output=True, |
| 1170 | timeout=10, |
| 1171 | env=env_vars, |
| 1172 | ) |
| 1173 | assert eof_ins.returncode == 0, eof_ins.stderr |
| 1174 | assert (store / "secrets" / "l30" / "XAI_API_KEY.gpg").read_text(encoding="utf-8") == "xai-no-newline\n" |
| 1175 | |
| 1176 | eof_empty = subprocess.run( |
| 1177 | ["bash", str(SETUP_PASS_SH), "BRAVE_API_KEY"], |
| 1178 | input="", |
| 1179 | text=True, |
| 1180 | capture_output=True, |
| 1181 | timeout=10, |
| 1182 | env=env_vars, |
| 1183 | ) |
| 1184 | assert eof_empty.returncode == 0, eof_empty.stderr |
| 1185 | assert "added=0 replaced=0 skipped=1" in eof_empty.stdout |
| 1186 | |
| 1187 | |
| 1188 | @pytest.mark.skipif(os.name == "nt", reason="POSIX shell script") |
| 1189 | def test_setup_pass_and_env_loader_preserve_exact_prefix_and_isolate_profiles(mock_pass_env, monkeypatch): |
| 1190 | """setup-pass.sh and lib/env.py agree verbatim on every valid prefix, keeping `work-` and `work-/` isolated.""" |
| 1191 | store, _calls_file, base_env = mock_pass_env |
| 1192 | pass_bin = Path(base_env["PATH"].split(os.pathsep)[0]) / "pass" |
| 1193 | pass_bin.write_text( |
| 1194 | f"#!{sys.executable}\n" |
| 1195 | "import os, pathlib, sys\n" |
| 1196 | "args = sys.argv[1:]\n" |
| 1197 | "target = pathlib.Path(os.environ['PASSWORD_STORE_DIR']) / (args[-1] + '.gpg')\n" |
| 1198 | "if args and args[0] == 'insert':\n" |
| 1199 | " target.parent.mkdir(parents=True, exist_ok=True)\n" |
| 1200 | " target.write_text(sys.stdin.read(), encoding='utf-8')\n" |
| 1201 | " sys.exit(0)\n" |
| 1202 | "if args and args[0] == 'show':\n" |
| 1203 | " if target.exists():\n" |
| 1204 | " sys.stdout.write(target.read_text(encoding='utf-8'))\n" |
| 1205 | " sys.exit(0)\n" |
| 1206 | " sys.exit(1)\n" |
| 1207 | "if args and args[0] == 'rm':\n" |
| 1208 | " if target.exists():\n" |
| 1209 | " target.unlink()\n" |
| 1210 | " sys.exit(0)\n" |
| 1211 | " sys.exit(1)\n" |
| 1212 | "sys.exit(3)\n", |
| 1213 | encoding="utf-8", |
| 1214 | ) |
| 1215 | pass_bin.chmod(0o755) |
| 1216 | |
| 1217 | monkeypatch.setenv("PATH", base_env["PATH"]) |
| 1218 | monkeypatch.setenv("PASSWORD_STORE_DIR", base_env["PASSWORD_STORE_DIR"]) |
| 1219 | |
| 1220 | # 1. Exact agreement between setup-pass.sh and env._load_pass / env.get_config across valid prefixes. |
| 1221 | for prefix, secret in ( |
| 1222 | ("last30days/", "sk-default-prefix"), |
| 1223 | ("secrets/l30/", "sk-nested-prefix"), |
| 1224 | ("work-", "sk-profile-a"), |
| 1225 | ("work-/", "sk-profile-b"), |
| 1226 | ): |
| 1227 | ins = subprocess.run( |
| 1228 | ["bash", str(SETUP_PASS_SH), "OPENAI_API_KEY"], |
| 1229 | input=f"{secret}\n", |
| 1230 | text=True, |
| 1231 | capture_output=True, |
| 1232 | timeout=10, |
| 1233 | env={**base_env, "LAST30DAYS_PASS_PREFIX": prefix}, |
| 1234 | ) |
| 1235 | assert ins.returncode == 0, ins.stderr |
| 1236 | assert (store / f"{prefix}OPENAI_API_KEY.gpg").read_text(encoding="utf-8") == f"{secret}\n" |
| 1237 | |
| 1238 | monkeypatch.setenv("LAST30DAYS_PASS_PREFIX", prefix) |
| 1239 | with mock.patch("shutil.which", return_value=str(pass_bin)): |
| 1240 | assert env._load_pass(["OPENAI_API_KEY"], prefix) == {"OPENAI_API_KEY": secret} |
| 1241 | assert env.get_config()["OPENAI_API_KEY"] == secret |
| 1242 | |
| 1243 | # 2. Replacing and deleting in profile `work-` must NEVER touch profile `work-/`. |
| 1244 | rep = subprocess.run( |
| 1245 | ["bash", str(SETUP_PASS_SH), "--replace", "OPENAI_API_KEY"], |
| 1246 | input="sk-profile-a-updated\n", |
| 1247 | text=True, |
| 1248 | capture_output=True, |
| 1249 | timeout=10, |
| 1250 | env={**base_env, "LAST30DAYS_PASS_PREFIX": "work-"}, |
| 1251 | ) |
| 1252 | assert rep.returncode == 0, rep.stderr |
| 1253 | assert (store / "work-OPENAI_API_KEY.gpg").read_text(encoding="utf-8") == "sk-profile-a-updated\n" |
| 1254 | assert (store / "work-" / "OPENAI_API_KEY.gpg").read_text(encoding="utf-8") == "sk-profile-b\n" |
| 1255 | |
| 1256 | rm = subprocess.run( |
| 1257 | ["bash", str(SETUP_PASS_SH), "--delete", "OPENAI_API_KEY"], |
| 1258 | text=True, |
| 1259 | capture_output=True, |
| 1260 | timeout=10, |
| 1261 | env={**base_env, "LAST30DAYS_PASS_PREFIX": "work-"}, |
| 1262 | ) |
| 1263 | assert rm.returncode == 0, rm.stderr |
| 1264 | assert not (store / "work-OPENAI_API_KEY.gpg").exists() |
| 1265 | assert (store / "work-" / "OPENAI_API_KEY.gpg").read_text(encoding="utf-8") == "sk-profile-b\n" |
| 1266 | |
| 1267 | with mock.patch("shutil.which", return_value=str(pass_bin)): |
| 1268 | assert env._load_pass(["OPENAI_API_KEY"], "work-") == {} |
| 1269 | assert env._load_pass(["OPENAI_API_KEY"], "work-/") == {"OPENAI_API_KEY": "sk-profile-b"} |
| 1270 |