| 1 | """Regression tests for PR 13: setup, preflight, doctor, and provider hardening. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-064: permission_preflight hosted mode, endpoint overrides, credentials, |
| 5 | local corpus & secret store disclosures, CDP scheme case, reads_values |
| 6 | - HIGH-066: per-user private GitHub device handle path, atomic 0o600 writes, |
| 7 | fail-closed persistence before user-code/browser emission, safe poll read |
| 8 | - HIGH-067: atomic private .env rewrite and hardened _open_secret_append |
| 9 | - HIGH-069: clean/no-config mode (env_path=None) handling across writers and CLI |
| 10 | - HIGH-071: atomic 0o600 doctor-cache.json, complete secret leak guard, |
| 11 | KEY_PRESENCE_VARS parity, and full _config_fingerprint coverage |
| 12 | - HIGH-073: scoped @xdevplatform/xurl package, app-only bearer prescription, |
| 13 | and OAuth-only token-store mismatch detection |
| 14 | - HIGH-075: Gemini API key in x-goog-api-key header with same-origin redirect guard |
| 15 | and anchored model validation/percent-encoding |
| 16 | """ |
| 17 | |
| 18 | from __future__ import annotations |
| 19 | |
| 20 | import concurrent.futures |
| 21 | import http.server |
| 22 | import io |
| 23 | import json |
| 24 | import os |
| 25 | import socketserver |
| 26 | import stat |
| 27 | import sys |
| 28 | import tempfile |
| 29 | import threading |
| 30 | from contextlib import redirect_stderr, redirect_stdout |
| 31 | from pathlib import Path |
| 32 | from unittest import mock |
| 33 | |
| 34 | from urllib.request import Request |
| 35 | |
| 36 | import pytest |
| 37 | |
| 38 | import last30days as cli |
| 39 | from lib import ( |
| 40 | backends, |
| 41 | chrome_cdp, |
| 42 | doctor, |
| 43 | env, |
| 44 | health, |
| 45 | http as http_mod, |
| 46 | permission_preflight, |
| 47 | pipeline, |
| 48 | private_files, |
| 49 | providers, |
| 50 | proxy, |
| 51 | setup_wizard, |
| 52 | xurl_x, |
| 53 | ) |
| 54 | |
| 55 | |
| 56 | def _diag(**overrides): |
| 57 | base = { |
| 58 | "providers": { |
| 59 | "google": False, |
| 60 | "openai": False, |
| 61 | "xai": False, |
| 62 | "openrouter": False, |
| 63 | "perplexity": False, |
| 64 | }, |
| 65 | "has_scrapecreators": False, |
| 66 | "has_github": False, |
| 67 | "available_sources": ["reddit", "hackernews", "polymarket"], |
| 68 | "safe": True, |
| 69 | "config_source": "env_only", |
| 70 | "ignored_project_config": None, |
| 71 | "ignored_project_config_keys": [], |
| 72 | "ignored_endpoint_overrides": [], |
| 73 | "browser_cookies": {"mode": "plan_only", "browsers": [], "reads_values": False}, |
| 74 | "external_commands": {"yt-dlp": False, "digg-pp-cli": False, "gh": False}, |
| 75 | "credential_destinations": {"global_env": None}, |
| 76 | "local_writes": [], |
| 77 | "native_search": False, |
| 78 | } |
| 79 | base.update(overrides) |
| 80 | return base |
| 81 | |
| 82 | |
| 83 | class _NtOs: |
| 84 | """Delegates to os while reporting os.name == 'nt'.""" |
| 85 | |
| 86 | name = "nt" |
| 87 | |
| 88 | def __getattr__(self, attr): |
| 89 | return getattr(os, attr) |
| 90 | |
| 91 | |
| 92 | # --------------------------------------------------------------------------- |
| 93 | # HIGH-064: permission_preflight completeness and accuracy |
| 94 | # --------------------------------------------------------------------------- |
| 95 | |
| 96 | |
| 97 | class TestHigh064PermissionPreflight: |
| 98 | def test_hosted_mode_disclosed_and_hides_local_sources(self, monkeypatch): |
| 99 | secret = "dummy-hosted-key-064" |
| 100 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 101 | monkeypatch.setenv("LAST30DAYS_API_KEY", secret) |
| 102 | |
| 103 | preflight = permission_preflight.build({}, _diag()) |
| 104 | |
| 105 | assert preflight["status"] == "ready" |
| 106 | assert preflight["network"]["hosted_mode"] is True |
| 107 | assert preflight["network"]["available_sources"] == ["hosted"] |
| 108 | assert "LAST30DAYS_API_BASE" in preflight["network"]["endpoint_overrides"] |
| 109 | assert preflight["credentials"]["hosted_api"]["present"] is True |
| 110 | |
| 111 | rendered = permission_preflight.render_text(preflight) |
| 112 | assert "Hosted mode: active (LAST30DAYS_API_BASE)" in rendered |
| 113 | assert "last30days hosted/proxy API key" in rendered |
| 114 | assert secret not in json.dumps(preflight) |
| 115 | assert secret not in rendered |
| 116 | assert "hosted.example" not in rendered |
| 117 | |
| 118 | @pytest.mark.parametrize( |
| 119 | "bad_base", |
| 120 | [ |
| 121 | "http://remote-cleartext.example/api/v1", |
| 122 | "https://secret-user:secret-pass@hosted.example/api/v1", |
| 123 | "https://hosted.example/api/v1?token=secret-param", |
| 124 | "https://hosted.example/api/v1#frag", |
| 125 | "https://hosted.example/api/v1\nX-Injected: 1", |
| 126 | "https://hosted.example\\evil.example/api/v1", |
| 127 | ], |
| 128 | ) |
| 129 | def test_invalid_hosted_api_base_rejected_without_leaking_url(self, monkeypatch, bad_base): |
| 130 | monkeypatch.setenv("LAST30DAYS_API_BASE", bad_base) |
| 131 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key-064") |
| 132 | |
| 133 | preflight = permission_preflight.build({}, _diag()) |
| 134 | |
| 135 | assert preflight["status"] == "action_needed" |
| 136 | assert preflight["network"]["hosted_mode"] is False |
| 137 | assert "LAST30DAYS_API_BASE" not in preflight["network"]["endpoint_overrides"] |
| 138 | assert "LAST30DAYS_API_BASE" in preflight["network"]["ignored_endpoint_overrides"] |
| 139 | assert any("LAST30DAYS_API_BASE" in item for item in preflight["action_items"]) |
| 140 | serialized = json.dumps(preflight) + permission_preflight.render_text(preflight) |
| 141 | assert "secret-user" not in serialized |
| 142 | assert "secret-pass" not in serialized |
| 143 | assert "secret-param" not in serialized |
| 144 | |
| 145 | def test_proxy_mode_keeps_local_sources_and_reports_api_base(self, monkeypatch): |
| 146 | monkeypatch.setenv("LAST30DAYS_API_MODE", "proxy") |
| 147 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://proxy.example/api/v1") |
| 148 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-proxy-key-064") |
| 149 | |
| 150 | preflight = permission_preflight.build({}, _diag()) |
| 151 | |
| 152 | assert preflight["status"] == "ready" |
| 153 | assert preflight["network"]["hosted_mode"] is False |
| 154 | assert preflight["network"]["available_sources"] == ["reddit", "hackernews", "polymarket"] |
| 155 | assert "LAST30DAYS_API_BASE" in preflight["network"]["endpoint_overrides"] |
| 156 | assert preflight["credentials"]["hosted_api"]["present"] is True |
| 157 | |
| 158 | def test_new_endpoint_override_keys_and_amazon_default_handling(self, tmp_path, monkeypatch): |
| 159 | for key in ( |
| 160 | "LAST30DAYS_API_BASE", |
| 161 | "BROWSER_CDP_URL", |
| 162 | "YOUTUBE_PROXY", |
| 163 | "YT_PROXY", |
| 164 | "LAST30DAYS_AMAZON_DOMAIN", |
| 165 | ): |
| 166 | assert key in permission_preflight.ENDPOINT_OVERRIDE_KEYS |
| 167 | |
| 168 | default_only = permission_preflight.build( |
| 169 | {"LAST30DAYS_AMAZON_DOMAIN": "https://www.amazon.com/"}, |
| 170 | _diag(), |
| 171 | ) |
| 172 | assert "LAST30DAYS_AMAZON_DOMAIN" not in default_only["network"]["endpoint_overrides"] |
| 173 | |
| 174 | active = permission_preflight.build( |
| 175 | { |
| 176 | "BROWSER_CDP_URL": "http://127.0.0.1:18800", |
| 177 | "YOUTUBE_PROXY": "http://127.0.0.1:8080", |
| 178 | "YT_PROXY": "socks5://127.0.0.1:1080", |
| 179 | "LAST30DAYS_AMAZON_DOMAIN": "https://www.amazon.co.uk", |
| 180 | }, |
| 181 | _diag(), |
| 182 | ) |
| 183 | assert { |
| 184 | "BROWSER_CDP_URL", |
| 185 | "YOUTUBE_PROXY", |
| 186 | "YT_PROXY", |
| 187 | "LAST30DAYS_AMAZON_DOMAIN", |
| 188 | } <= set(active["network"]["endpoint_overrides"]) |
| 189 | |
| 190 | project_env = tmp_path / ".claude" / "last30days.env" |
| 191 | project_env.parent.mkdir() |
| 192 | project_env.write_text( |
| 193 | "BROWSER_CDP_URL=http://127.0.0.1:19999\n" |
| 194 | "YOUTUBE_PROXY=http://attacker.example:8080\n" |
| 195 | "YT_PROXY=http://attacker.example:8081\n" |
| 196 | "LAST30DAYS_AMAZON_DOMAIN=https://evil.example\n" |
| 197 | "LAST30DAYS_API_BASE=https://evil.example/api/v1\n", |
| 198 | encoding="utf-8", |
| 199 | ) |
| 200 | monkeypatch.chdir(tmp_path) |
| 201 | monkeypatch.setattr(env, "CONFIG_FILE", None) |
| 202 | with mock.patch.object(env, "_load_keychain", return_value={}), \ |
| 203 | mock.patch.object(env, "_load_pass", return_value={}): |
| 204 | config = env.get_config( |
| 205 | policy=env.ConfigLoadPolicy( |
| 206 | browser_cookies="plan_only", |
| 207 | inspect_ignored_project_config=True, |
| 208 | ) |
| 209 | ) |
| 210 | diag = pipeline.diagnose(config, safe=True) |
| 211 | ignored = set(diag["permission_preflight"]["network"]["ignored_endpoint_overrides"]) |
| 212 | assert { |
| 213 | "BROWSER_CDP_URL", |
| 214 | "YOUTUBE_PROXY", |
| 215 | "YT_PROXY", |
| 216 | "LAST30DAYS_AMAZON_DOMAIN", |
| 217 | "LAST30DAYS_API_BASE", |
| 218 | } <= ignored |
| 219 | |
| 220 | def test_all_credential_families_disclosed_without_values(self): |
| 221 | secrets = { |
| 222 | "AUTH_TOKEN": "dummy-auth-token-064", |
| 223 | "CT0": "dummy-ct0-064", |
| 224 | "BRAVE_API_KEY": "dummy-brave-064", |
| 225 | "EXA_API_KEY": "dummy-exa-064", |
| 226 | "SERPER_API_KEY": "dummy-serper-064", |
| 227 | "PARALLEL_API_KEY": "dummy-parallel-064", |
| 228 | "BSKY_HANDLE": "tester.bsky.social", |
| 229 | "BSKY_APP_PASSWORD": "dummy-bsky-pass-064", |
| 230 | "TRUTHSOCIAL_TOKEN": "dummy-truth-064", |
| 231 | "APIFY_API_TOKEN": "dummy-apify-064", |
| 232 | "XQUIK_API_KEY": "dummy-xquik-064", |
| 233 | "BRIGHTDATA_API_KEY": "dummy-brightdata-064", |
| 234 | "GROQ_API_KEY": "dummy-groq-064", |
| 235 | "DEEPLINE_API_KEY": "dummy-deepline-064", |
| 236 | "LAST30DAYS_API_KEY": "dummy-hosted-064", |
| 237 | "LAST30DAYS_PUBLISH_PASSWORD": "dummy-publish-064", |
| 238 | } |
| 239 | preflight = permission_preflight.build(secrets, _diag()) |
| 240 | creds = preflight["credentials"] |
| 241 | for family in ( |
| 242 | "x_cookies", |
| 243 | "brave", |
| 244 | "exa", |
| 245 | "serper", |
| 246 | "parallel", |
| 247 | "bluesky", |
| 248 | "truthsocial", |
| 249 | "apify", |
| 250 | "xquik", |
| 251 | "brightdata", |
| 252 | "groq", |
| 253 | "deepline", |
| 254 | "hosted_api", |
| 255 | "publish_password", |
| 256 | ): |
| 257 | assert creds[family]["present"] is True, family |
| 258 | |
| 259 | text = permission_preflight.render_text(preflight) |
| 260 | assert "Present: none" not in text |
| 261 | combined = json.dumps(preflight) + text |
| 262 | for key, value in secrets.items(): |
| 263 | if key == "BSKY_HANDLE": |
| 264 | continue |
| 265 | assert value not in combined, key |
| 266 | |
| 267 | # Proxy sentinel placeholders must not masquerade as user-held keys. |
| 268 | proxied = permission_preflight.build({"SERPER_API_KEY": proxy.SENTINEL}, _diag()) |
| 269 | assert proxied["credentials"]["serper"]["present"] is False |
| 270 | |
| 271 | def test_corpus_dirs_and_secret_stores_disclosed_with_env_file(self, tmp_path, monkeypatch): |
| 272 | notes = tmp_path / "notes" |
| 273 | notes.mkdir() |
| 274 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 275 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key-064") |
| 276 | monkeypatch.delenv(env.KEYCHAIN_DISABLE_ENV, raising=False) |
| 277 | with mock.patch.object(permission_preflight.platform, "system", return_value="Darwin"), \ |
| 278 | mock.patch.object( |
| 279 | permission_preflight.shutil, |
| 280 | "which", |
| 281 | side_effect=lambda cmd: f"/usr/bin/{cmd}" if cmd in {"security", "pass"} else None, |
| 282 | ): |
| 283 | preflight = permission_preflight.build( |
| 284 | {"LAST30DAYS_CORPUS_DIRS": str(notes)}, |
| 285 | _diag(config_source="global:/Users/tester/.config/last30days/.env"), |
| 286 | ) |
| 287 | |
| 288 | assert preflight["local_reads"]["corpus_dirs"] == [str(notes.resolve())] |
| 289 | # Local corpus bypasses hosted mode, so secret stores and local sources remain active. |
| 290 | assert preflight["network"]["hosted_mode"] is False |
| 291 | assert preflight["local_reads"]["secret_stores"] == ["keychain", "pass"] |
| 292 | rendered = permission_preflight.render_text(preflight) |
| 293 | assert f"Corpus directories: {notes.resolve()}" in rendered |
| 294 | assert "Secret stores: keychain, pass" in rendered |
| 295 | |
| 296 | excluded = permission_preflight.build( |
| 297 | {"LAST30DAYS_CORPUS_DIRS": str(notes), "EXCLUDE_SOURCES": "corpus"}, |
| 298 | _diag(), |
| 299 | ) |
| 300 | assert excluded["local_reads"]["corpus_dirs"] == [] |
| 301 | |
| 302 | def test_uppercase_https_wss_cdp_scheme_excluded_and_reads_values_preserved(self, monkeypatch): |
| 303 | monkeypatch.setattr(env, "x_extras_enabled", lambda _cfg: True) |
| 304 | monkeypatch.setattr(chrome_cdp, "cookie_access_allowed", lambda _cfg: True) |
| 305 | monkeypatch.setattr( |
| 306 | chrome_cdp, |
| 307 | "candidate_endpoints", |
| 308 | lambda _cfg: ["HTTPS://127.0.0.1:9222", "WSS://127.0.0.1:9222/devtools/page/1"], |
| 309 | ) |
| 310 | assert permission_preflight._conditional_x_cookie_routes({"BROWSER_CONSENT": "true"}) == [] |
| 311 | |
| 312 | diag_unsafe = _diag( |
| 313 | safe=False, |
| 314 | browser_cookies={"mode": "read", "browsers": ["firefox"], "reads_values": True}, |
| 315 | ) |
| 316 | preflight = permission_preflight.build({"FROM_BROWSER": "firefox"}, diag_unsafe) |
| 317 | assert preflight["local_reads"]["browser_cookies"]["reads_values"] is True |
| 318 | rendered = permission_preflight.render_text(preflight) |
| 319 | assert "cookie values were read" in rendered |
| 320 | assert "preflight did not read cookie values" not in rendered |
| 321 | |
| 322 | |
| 323 | # --------------------------------------------------------------------------- |
| 324 | # HIGH-066: GitHub device-handle path, atomic write, fail-closed start, safe poll |
| 325 | # --------------------------------------------------------------------------- |
| 326 | |
| 327 | |
| 328 | class TestHigh066DeviceHandleSecurity: |
| 329 | def test_temp_fallback_uses_per_user_private_dir_on_posix(self, monkeypatch): |
| 330 | if os.name != "posix": |
| 331 | pytest.skip("POSIX per-uid temp dir check") |
| 332 | monkeypatch.setattr(env, "CONFIG_FILE", None) |
| 333 | path = setup_wizard._device_handle_path() |
| 334 | expected_dir = Path(tempfile.gettempdir()) / f"last30days-{os.geteuid()}" |
| 335 | assert path.parent == expected_dir |
| 336 | assert path.name == "github-device-handle.json" |
| 337 | assert path != Path(tempfile.gettempdir()) / "last30days-github-device-handle.json" |
| 338 | |
| 339 | def test_temp_fallback_uses_localappdata_on_windows(self, monkeypatch, tmp_path): |
| 340 | monkeypatch.setattr(env, "CONFIG_FILE", None) |
| 341 | monkeypatch.setattr(setup_wizard, "os", _NtOs()) |
| 342 | monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "LocalAppData")) |
| 343 | path = setup_wizard._device_handle_path() |
| 344 | assert path == tmp_path / "LocalAppData" / "last30days" / "github-device-handle.json" |
| 345 | |
| 346 | @pytest.mark.skipif(os.name != "posix", reason="POSIX permissions and symlinks") |
| 347 | def test_fallback_dir_created_0700_and_rejects_symlink_or_foreign_owner(self, tmp_path, monkeypatch): |
| 348 | fallback = tmp_path / f"last30days-{os.geteuid()}" |
| 349 | monkeypatch.setattr(setup_wizard, "_device_handle_fallback_dir", lambda: fallback) |
| 350 | setup_wizard._ensure_private_handle_dir(fallback) |
| 351 | assert stat.S_IMODE(fallback.lstat().st_mode) == 0o700 |
| 352 | |
| 353 | fallback.chmod(0o755) |
| 354 | setup_wizard._ensure_private_handle_dir(fallback) |
| 355 | assert stat.S_IMODE(fallback.lstat().st_mode) == 0o700 |
| 356 | |
| 357 | sym_dir = tmp_path / "sym-dir" |
| 358 | sym_dir.symlink_to(fallback) |
| 359 | with pytest.raises(OSError, match="symlink"): |
| 360 | setup_wizard._ensure_private_handle_dir(sym_dir) |
| 361 | |
| 362 | real_lstat = os.lstat |
| 363 | |
| 364 | def foreign_lstat(p): |
| 365 | st = real_lstat(p) |
| 366 | fake = list(st) |
| 367 | fake[4] = os.geteuid() + 1 # st_uid |
| 368 | return os.stat_result(fake) |
| 369 | |
| 370 | with mock.patch.object(setup_wizard.os, "lstat", side_effect=foreign_lstat): |
| 371 | with pytest.raises(OSError, match="another user"): |
| 372 | setup_wizard._ensure_private_handle_dir(fallback) |
| 373 | |
| 374 | def test_ensure_private_handle_dir_rejects_windows_junction(self, tmp_path, monkeypatch): |
| 375 | junction = tmp_path / "junction-dir" |
| 376 | junction.mkdir() |
| 377 | monkeypatch.setattr(setup_wizard.os.path, "isjunction", lambda p: Path(p) == junction, raising=False) |
| 378 | with pytest.raises(OSError, match="junction"): |
| 379 | setup_wizard._ensure_private_handle_dir(junction) |
| 380 | |
| 381 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks and permissions") |
| 382 | def test_github_start_fails_closed_before_printing_or_opening_browser(self, tmp_path): |
| 383 | victim = tmp_path / "victim.txt" |
| 384 | victim.write_text("precious-data", encoding="utf-8") |
| 385 | victim.chmod(0o644) |
| 386 | handle_link = tmp_path / ".github-device-handle.json" |
| 387 | handle_link.symlink_to(victim) |
| 388 | |
| 389 | out = io.StringIO() |
| 390 | err = io.StringIO() |
| 391 | with mock.patch.object(setup_wizard, "_existing_scrapecreators_key", return_value=None), \ |
| 392 | mock.patch.object( |
| 393 | setup_wizard, |
| 394 | "run_device_auth", |
| 395 | return_value=("dev-code-066", "ABCD-1234", "https://github.com/login/device", 5), |
| 396 | ), \ |
| 397 | mock.patch.object(setup_wizard, "_device_handle_path", return_value=handle_link), \ |
| 398 | mock.patch("webbrowser.open") as open_browser, \ |
| 399 | redirect_stdout(out), redirect_stderr(err): |
| 400 | result = setup_wizard.run_github_start() |
| 401 | |
| 402 | assert result["status"] == "error" |
| 403 | assert "device_code_ready" not in out.getvalue() |
| 404 | assert "ABCD-1234" not in out.getvalue() |
| 405 | open_browser.assert_not_called() |
| 406 | assert victim.read_text(encoding="utf-8") == "precious-data" |
| 407 | assert stat.S_IMODE(victim.stat().st_mode) == 0o644 |
| 408 | |
| 409 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks and permissions") |
| 410 | def test_github_poll_rejects_symlink_and_world_writable_handles(self, tmp_path): |
| 411 | real_handle = tmp_path / "real.json" |
| 412 | real_handle.write_text(json.dumps({"device_code": "attacker-code", "interval": 5}), encoding="utf-8") |
| 413 | |
| 414 | link_handle = tmp_path / "link.json" |
| 415 | link_handle.symlink_to(real_handle) |
| 416 | with mock.patch.object(setup_wizard, "_device_handle_path", return_value=link_handle), \ |
| 417 | mock.patch.object(setup_wizard, "poll_device_auth") as poll_mock: |
| 418 | res = setup_wizard.run_github_poll(timeout=1) |
| 419 | assert res["status"] == "error" |
| 420 | poll_mock.assert_not_called() |
| 421 | |
| 422 | real_handle.chmod(0o666) |
| 423 | with mock.patch.object(setup_wizard, "_device_handle_path", return_value=real_handle), \ |
| 424 | mock.patch.object(setup_wizard, "poll_device_auth") as poll_mock: |
| 425 | res = setup_wizard.run_github_poll(timeout=1) |
| 426 | assert res["status"] == "error" |
| 427 | poll_mock.assert_not_called() |
| 428 | |
| 429 | |
| 430 | # --------------------------------------------------------------------------- |
| 431 | # HIGH-067: atomic .env updates and hardened _open_secret_append |
| 432 | # --------------------------------------------------------------------------- |
| 433 | |
| 434 | |
| 435 | class TestHigh067EnvSecretFileHardening: |
| 436 | @pytest.mark.skipif(os.name != "posix", reason="POSIX permissions and symlinks") |
| 437 | def test_open_secret_append_uses_fchmod_rejects_symlink_and_closes_fd_on_error(self, tmp_path): |
| 438 | victim = tmp_path / "victim.txt" |
| 439 | victim.write_text("keep", encoding="utf-8") |
| 440 | victim.chmod(0o644) |
| 441 | link = tmp_path / ".env" |
| 442 | link.symlink_to(victim) |
| 443 | |
| 444 | with pytest.raises(OSError): |
| 445 | setup_wizard._open_secret_append(link) |
| 446 | assert victim.read_text(encoding="utf-8") == "keep" |
| 447 | assert stat.S_IMODE(victim.stat().st_mode) == 0o644 |
| 448 | |
| 449 | target = tmp_path / "loose.env" |
| 450 | target.write_text("A=1\n", encoding="utf-8") |
| 451 | target.chmod(0o644) |
| 452 | with mock.patch.object(setup_wizard.os, "chmod", side_effect=AssertionError("must use fchmod")): |
| 453 | with setup_wizard._open_secret_append(target) as stream: |
| 454 | stream.write("B=2\n") |
| 455 | assert stat.S_IMODE(target.stat().st_mode) == 0o600 |
| 456 | |
| 457 | closed_fds: list[int] = [] |
| 458 | real_close = os.close |
| 459 | |
| 460 | def spy_close(fd: int): |
| 461 | closed_fds.append(fd) |
| 462 | return real_close(fd) |
| 463 | |
| 464 | target2 = tmp_path / "fdopen_fail.env" |
| 465 | with mock.patch.object(setup_wizard.os, "fdopen", side_effect=OSError("fdopen failed")), \ |
| 466 | mock.patch.object(setup_wizard.os, "close", side_effect=spy_close): |
| 467 | with pytest.raises(OSError, match="fdopen failed"): |
| 468 | setup_wizard._open_secret_append(target2) |
| 469 | assert len(closed_fds) == 1 |
| 470 | |
| 471 | def test_open_secret_append_rejects_windows_junction(self, tmp_path, monkeypatch): |
| 472 | junction = tmp_path / "junction.env" |
| 473 | junction.mkdir() |
| 474 | monkeypatch.setattr(setup_wizard, "os", _NtOs()) |
| 475 | monkeypatch.setattr(private_files, "_IS_JUNCTION", lambda p: Path(p) == junction) |
| 476 | with pytest.raises(OSError, match="junction"): |
| 477 | setup_wizard._open_secret_append(junction) |
| 478 | |
| 479 | @pytest.mark.skipif(os.name != "posix", reason="POSIX permissions and symlinks") |
| 480 | def test_replace_env_line_ignores_preplanted_loose_tmp_and_cleans_up_on_replace_error(self, tmp_path): |
| 481 | env_path = tmp_path / ".env" |
| 482 | env_path.write_text("XAI_API_KEY=old-secret\n", encoding="utf-8") |
| 483 | env_path.chmod(0o600) |
| 484 | |
| 485 | planted = tmp_path / ".env.tmp" |
| 486 | planted.write_text("attacker-file", encoding="utf-8") |
| 487 | planted.chmod(0o644) |
| 488 | |
| 489 | assert setup_wizard._replace_env_line(env_path, env_path.read_text(), "XAI_API_KEY", "new-secret") |
| 490 | assert stat.S_IMODE(env_path.stat().st_mode) == 0o600 |
| 491 | assert "new-secret" in env_path.read_text(encoding="utf-8") |
| 492 | assert planted.read_text(encoding="utf-8") == "attacker-file" |
| 493 | |
| 494 | # Failed replace must unlink the temporary staging file with no stray secret file left behind. |
| 495 | with mock.patch.object(private_files.os, "replace", side_effect=OSError("replace denied")): |
| 496 | with pytest.raises(OSError, match="replace denied"): |
| 497 | setup_wizard._replace_env_line(env_path, env_path.read_text(), "XAI_API_KEY", "leaked-secret") |
| 498 | stray = [p for p in tmp_path.iterdir() if p.name not in {".env", ".env.tmp"}] |
| 499 | assert stray == [] |
| 500 | assert "leaked-secret" not in env_path.read_text(encoding="utf-8") |
| 501 | |
| 502 | @pytest.mark.skipif(os.name != "posix", reason="POSIX permissions and concurrency") |
| 503 | def test_concurrent_replace_env_line_stays_valid_and_0600(self, tmp_path): |
| 504 | env_path = tmp_path / ".env" |
| 505 | env_path.write_text("XAI_API_KEY=init\nKEEP_ME=ok\n", encoding="utf-8") |
| 506 | env_path.chmod(0o600) |
| 507 | |
| 508 | def worker(idx: int) -> bool: |
| 509 | return setup_wizard.write_api_key( |
| 510 | env_path, f"secret-value-{idx}", key_name="XAI_API_KEY", replace=True |
| 511 | ) |
| 512 | |
| 513 | with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool: |
| 514 | results = list(pool.map(worker, range(12))) |
| 515 | |
| 516 | assert all(results) |
| 517 | assert stat.S_IMODE(env_path.stat().st_mode) == 0o600 |
| 518 | loaded = env.load_env_file(env_path) |
| 519 | assert loaded["KEEP_ME"] == "ok" |
| 520 | assert loaded["XAI_API_KEY"].startswith("secret-value-") |
| 521 | leftover = [p for p in tmp_path.iterdir() if p.name != ".env"] |
| 522 | assert leftover == [] |
| 523 | |
| 524 | @pytest.mark.skipif(os.name != "posix", reason="POSIX symlinks") |
| 525 | def test_writers_reject_symlink_env_path(self, tmp_path): |
| 526 | target = tmp_path / "target.txt" |
| 527 | target.write_text("untouched\n", encoding="utf-8") |
| 528 | link = tmp_path / ".env" |
| 529 | link.symlink_to(target) |
| 530 | |
| 531 | assert setup_wizard.write_api_key(link, "dummy-secret") is False |
| 532 | assert setup_wizard.write_setup_config(link, from_browser="chrome") is False |
| 533 | assert target.read_text(encoding="utf-8") == "untouched\n" |
| 534 | |
| 535 | |
| 536 | # --------------------------------------------------------------------------- |
| 537 | # HIGH-069: Clean/no-config mode (env_path is None) |
| 538 | # --------------------------------------------------------------------------- |
| 539 | |
| 540 | |
| 541 | class TestHigh069CleanModeNoConfig: |
| 542 | def test_writers_and_reddit_session_handle_none_env_path_without_typeerror(self): |
| 543 | assert setup_wizard.write_api_key(None, "dummy-secret") is False |
| 544 | assert setup_wizard.write_api_key("", "dummy-secret") is False |
| 545 | assert setup_wizard.write_api_key(123, "dummy-secret") is False # type: ignore[arg-type] |
| 546 | assert setup_wizard.write_setup_config(None, from_browser="chrome", browser_consent=True) is False |
| 547 | assert setup_wizard.write_setup_config("", browser_consent=False) is False |
| 548 | |
| 549 | declined = setup_wizard.run_reddit_session_setup({}, None, consent=False) |
| 550 | assert declined == {"status": "declined", "consent": False, "env_written": False} |
| 551 | |
| 552 | found = setup_wizard.run_reddit_session_setup( |
| 553 | {}, |
| 554 | None, |
| 555 | consent=True, |
| 556 | reader=lambda _cfg, browser: ("dummy-cookie", "found") if browser == "chrome" else (None, "empty"), |
| 557 | ) |
| 558 | assert found["status"] == "found" |
| 559 | assert found["browser"] == "chrome" |
| 560 | assert found["env_written"] is False |
| 561 | |
| 562 | def test_cli_setup_paths_survive_none_config_file_and_mask_secrets(self): |
| 563 | dummy_key = "sc_live_cleanmode_secret_069" |
| 564 | |
| 565 | # 1. setup --store-key |
| 566 | out, err = io.StringIO(), io.StringIO() |
| 567 | with mock.patch.object(cli.env, "CONFIG_FILE", None), \ |
| 568 | mock.patch.object(sys, "stdin", io.StringIO(dummy_key + "\n")), \ |
| 569 | mock.patch.object(sys, "argv", ["last30days.py", "setup", "--store-key", "X_BEARER_TOKEN"]), \ |
| 570 | redirect_stdout(out), redirect_stderr(err): |
| 571 | rc = cli.main() |
| 572 | assert rc == 1 |
| 573 | assert dummy_key not in out.getvalue() and dummy_key not in err.getvalue() |
| 574 | assert json.loads(out.getvalue().strip().splitlines()[-1]) == { |
| 575 | "persisted": False, |
| 576 | "key": "X_BEARER_TOKEN", |
| 577 | } |
| 578 | |
| 579 | # 2. setup --github-poll (must mask api_key even when persistence fails) |
| 580 | out, err = io.StringIO(), io.StringIO() |
| 581 | with mock.patch.object(cli.env, "CONFIG_FILE", None), \ |
| 582 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 583 | mock.patch.object( |
| 584 | setup_wizard, |
| 585 | "run_github_poll", |
| 586 | return_value={"status": "success", "method": "device", "api_key": dummy_key}, |
| 587 | ), \ |
| 588 | mock.patch.object(sys, "argv", ["last30days.py", "setup", "--github-poll"]), \ |
| 589 | redirect_stdout(out), redirect_stderr(err): |
| 590 | rc = cli.main() |
| 591 | assert rc == 0 |
| 592 | payload = json.loads(out.getvalue()) |
| 593 | assert payload["persisted"] is False |
| 594 | assert dummy_key not in out.getvalue() |
| 595 | assert payload["api_key"] == setup_wizard.mask_api_key(dummy_key) |
| 596 | |
| 597 | # 3. setup --no-reddit-session |
| 598 | out, err = io.StringIO(), io.StringIO() |
| 599 | with mock.patch.object(cli.env, "CONFIG_FILE", None), \ |
| 600 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 601 | mock.patch.object(sys, "argv", ["last30days.py", "setup", "--no-reddit-session"]), \ |
| 602 | redirect_stdout(out), redirect_stderr(err): |
| 603 | rc = cli.main() |
| 604 | assert rc == 0 |
| 605 | assert json.loads(out.getvalue())["env_written"] is False |
| 606 | |
| 607 | # 4. auto-setup |
| 608 | out, err = io.StringIO(), io.StringIO() |
| 609 | with mock.patch.object(cli.env, "CONFIG_FILE", None), \ |
| 610 | mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 611 | mock.patch.object(setup_wizard, "run_auto_setup", return_value={"cookies_found": {}}), \ |
| 612 | mock.patch.object(sys, "argv", ["last30days.py", "setup"]), \ |
| 613 | redirect_stdout(out), redirect_stderr(err): |
| 614 | rc = cli.main() |
| 615 | assert rc == 1 |
| 616 | assert "could not be fully saved" in err.getvalue().lower() |
| 617 | |
| 618 | |
| 619 | # --------------------------------------------------------------------------- |
| 620 | # HIGH-071: doctor-cache.json atomic 0o600 write, secret guard, fingerprint |
| 621 | # --------------------------------------------------------------------------- |
| 622 | |
| 623 | |
| 624 | class TestHigh071DoctorCacheHardening: |
| 625 | @staticmethod |
| 626 | def _sample_report(note: str = "ok") -> dict: |
| 627 | return { |
| 628 | "engine_version": "4.6.0", |
| 629 | "config": {"global_env": None, "config_source": None}, |
| 630 | "setup": {"setup_complete": False, "keys_present": {}}, |
| 631 | "permissions": {"status": "ready"}, |
| 632 | "sources": { |
| 633 | "hackernews": { |
| 634 | "tier": "ok", |
| 635 | "status": "ok", |
| 636 | "mode": "single", |
| 637 | "backends": None, |
| 638 | "active_backend": None, |
| 639 | "fix": "", |
| 640 | "requires": "none", |
| 641 | "note": note, |
| 642 | "detail": "", |
| 643 | "pin_var": None, |
| 644 | "pin_flag": None, |
| 645 | "pinned": False, |
| 646 | } |
| 647 | }, |
| 648 | } |
| 649 | |
| 650 | @pytest.mark.skipif(os.name != "posix", reason="POSIX file permissions and symlinks") |
| 651 | def test_write_cache_creates_0600_atomically_and_refuses_symlinks(self, tmp_path, monkeypatch): |
| 652 | config_dir = tmp_path / "cfg" |
| 653 | monkeypatch.setattr(env, "CONFIG_DIR", config_dir) |
| 654 | |
| 655 | old_umask = os.umask(0o022) |
| 656 | try: |
| 657 | assert doctor._write_cache(self._sample_report(), {}) is True |
| 658 | finally: |
| 659 | os.umask(old_umask) |
| 660 | |
| 661 | cache_file = config_dir / doctor.CACHE_FILENAME |
| 662 | assert stat.S_IMODE(cache_file.stat().st_mode) == 0o600 |
| 663 | assert doctor.read_cached_report({}) is not None |
| 664 | |
| 665 | # Symlink at doctor-cache.json must be refused on both read and write. |
| 666 | victim = tmp_path / "victim.json" |
| 667 | victim.write_text('{"keep": true}', encoding="utf-8") |
| 668 | cache_file.unlink() |
| 669 | cache_file.symlink_to(victim) |
| 670 | |
| 671 | assert doctor.read_cached_report({}) is None |
| 672 | err = io.StringIO() |
| 673 | with redirect_stderr(err): |
| 674 | assert doctor._write_cache(self._sample_report("overwrite"), {}) is False |
| 675 | assert victim.read_text(encoding="utf-8") == '{"keep": true}' |
| 676 | assert "WARNING" in err.getvalue() |
| 677 | |
| 678 | def test_key_presence_and_secret_leak_guard_cover_new_secrets(self, tmp_path, monkeypatch): |
| 679 | assert "GOOGLE_GENAI_API_KEY" in doctor.KEY_PRESENCE_VARS |
| 680 | assert "BRIGHTDATA_API_KEY" in doctor.KEY_PRESENCE_VARS |
| 681 | |
| 682 | setup_block = doctor._setup_block( |
| 683 | { |
| 684 | "GOOGLE_GENAI_API_KEY": "dummy-genai-071", |
| 685 | "BRIGHTDATA_API_KEY": "dummy-brightdata-071", |
| 686 | } |
| 687 | ) |
| 688 | assert setup_block["keys_present"]["GOOGLE_GENAI_API_KEY"] is True |
| 689 | assert setup_block["keys_present"]["BRIGHTDATA_API_KEY"] is True |
| 690 | |
| 691 | config_dir = tmp_path / "cfg" |
| 692 | monkeypatch.setattr(env, "CONFIG_DIR", config_dir) |
| 693 | |
| 694 | for key, secret in ( |
| 695 | ("BRIGHTDATA_API_KEY", "dummy-brightdata-leak-071"), |
| 696 | ("LAST30DAYS_PUBLISH_PASSWORD", "dummy-publish-leak-071"), |
| 697 | ("LAST30DAYS_API_KEY", "dummy-hosted-leak-071"), |
| 698 | ("CUSTOM_EXTRA_TOKEN", "dummy-extra-token-leak-071"), |
| 699 | ): |
| 700 | report = self._sample_report(note=f"accidental {secret}") |
| 701 | assert doctor._write_cache(report, {key: secret}) is False, key |
| 702 | assert not (config_dir / doctor.CACHE_FILENAME).exists() |
| 703 | |
| 704 | # Also block LAST30DAYS_API_KEY set only in os.environ. |
| 705 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-env-hosted-leak-071") |
| 706 | assert doctor._write_cache(self._sample_report(note="dummy-env-hosted-leak-071"), {}) is False |
| 707 | |
| 708 | # Proxy sentinel must not cause a false positive refusal. |
| 709 | monkeypatch.delenv("LAST30DAYS_API_KEY", raising=False) |
| 710 | assert doctor._write_cache(self._sample_report(note="ok"), {"XAI_API_KEY": proxy.SENTINEL}) is True |
| 711 | |
| 712 | @pytest.mark.parametrize( |
| 713 | ("key", "value"), |
| 714 | [ |
| 715 | ("EXCLUDE_SOURCES", "reddit"), |
| 716 | ("BRIGHTDATA_API_KEY", "dummy-bd-071"), |
| 717 | ("GOOGLE_GENAI_API_KEY", "dummy-genai-071"), |
| 718 | ("TELEGRAM_SOURCES", "chan1"), |
| 719 | ("XIAOHONGSHU_API_BASE", "http://127.0.0.1:18061"), |
| 720 | ("LAST30DAYS_NATIVE_SEARCH", "1"), |
| 721 | ("CLAUDECODE", "1"), |
| 722 | ("SETUP_COMPLETE", "true"), |
| 723 | ("LAST30DAYS_REDDIT_SC_MIN_ITEMS", "9"), |
| 724 | ("LAST30DAYS_MEMORY_DIR", "/tmp/custom-mem"), |
| 725 | ("LAST30DAYS_LIBRARY_CONTEXT", "off"), |
| 726 | ], |
| 727 | ) |
| 728 | def test_config_fingerprint_changes_for_every_tracked_knob(self, key, value): |
| 729 | base = doctor._config_fingerprint({}) |
| 730 | changed = doctor._config_fingerprint({key: value}) |
| 731 | assert changed != base, f"{key} did not invalidate doctor cache fingerprint" |
| 732 | |
| 733 | |
| 734 | # --------------------------------------------------------------------------- |
| 735 | # HIGH-073: xurl scoped package, app-only bearer prescription, store check |
| 736 | # --------------------------------------------------------------------------- |
| 737 | |
| 738 | |
| 739 | class TestHigh073XurlBackendPrescriptionAndAuth: |
| 740 | def test_missing_binary_prescribes_scoped_package_and_app_only_auth(self): |
| 741 | with mock.patch("lib.backends.which", return_value=None): |
| 742 | finding = backends._probe_xurl({}) |
| 743 | assert finding.status == health.MISSING |
| 744 | assert "npm install -g @xdevplatform/xurl" in finding.prescription |
| 745 | assert "npm install -g xurl " not in finding.prescription |
| 746 | assert "xurl auth app-only <bearer-token>" in finding.prescription |
| 747 | assert "oauth2" not in finding.prescription.lower() |
| 748 | assert "app-only bearer" in finding.requires.lower() |
| 749 | assert "app-only bearer" in backends._X_REQUIRES["xurl"].lower() |
| 750 | |
| 751 | @pytest.mark.parametrize( |
| 752 | "store_content", |
| 753 | [ |
| 754 | "apps:\n app:\n oauth2_tokens:\n me:\n oauth2:\n access_token: dummy-oauth2-only\n", |
| 755 | "apps:\n app:\n bearer_token: null\n oauth2_tokens:\n me:\n access_token: dummy-oauth2-only\n", |
| 756 | 'apps:\n app:\n bearer_token: ""\n oauth2_tokens:\n me:\n access_token: dummy-oauth2-only\n', |
| 757 | "# bearer_token: none\naccess_token: dummy-oauth2-only\n", |
| 758 | json.dumps({"bearer_token": None, "oauth2_tokens": {"me": {"access_token": "dummy"}}}), |
| 759 | ], |
| 760 | ) |
| 761 | def test_oauth2_only_token_store_does_not_report_will_use_xurl(self, tmp_path, store_content): |
| 762 | store = tmp_path / ".xurl" / "auth.yml" |
| 763 | store.parent.mkdir(exist_ok=True) |
| 764 | store.write_text(store_content, encoding="utf-8") |
| 765 | with mock.patch("lib.backends.which", side_effect=lambda n: "/usr/bin/xurl" if n == "xurl" else None), \ |
| 766 | mock.patch("lib.xurl_x.token_store_path", return_value=store): |
| 767 | finding = backends._probe_xurl({}) |
| 768 | assert finding.status == health.MISSING |
| 769 | assert not finding.usable |
| 770 | assert "app-only bearer" in finding.detail.lower() |
| 771 | assert "xurl auth app-only <bearer-token>" in finding.prescription |
| 772 | |
| 773 | def test_bearer_token_store_reports_ok_with_app_only_detail(self, tmp_path): |
| 774 | store = tmp_path / ".xurl" / "auth.yml" |
| 775 | store.parent.mkdir() |
| 776 | store.write_text( |
| 777 | "apps:\n app:\n bearer_token:\n bearer: dummy-bearer-073\n", |
| 778 | encoding="utf-8", |
| 779 | ) |
| 780 | with mock.patch("lib.backends.which", side_effect=lambda n: "/usr/bin/xurl" if n == "xurl" else None), \ |
| 781 | mock.patch("lib.xurl_x.token_store_path", return_value=store): |
| 782 | finding = backends._probe_xurl({}) |
| 783 | assert finding.status == health.OK |
| 784 | assert "app-only bearer" in finding.detail.lower() |
| 785 | assert "oauth2" not in finding.detail.lower() |
| 786 | |
| 787 | def test_doctor_x_auth_path_describes_xurl_as_app_only_bearer(self): |
| 788 | with mock.patch.object(env, "get_x_source", return_value="xurl"): |
| 789 | info = doctor._x_auth_path({"LAST30DAYS_HOST": "grok-bot"}) |
| 790 | assert "app-only bearer" in info["note"].lower() |
| 791 | assert "oauth2" not in info["note"].lower() |
| 792 | |
| 793 | |
| 794 | # --------------------------------------------------------------------------- |
| 795 | # HIGH-075: Gemini header auth, redirect guard, and anchored model validation |
| 796 | # --------------------------------------------------------------------------- |
| 797 | |
| 798 | |
| 799 | class TestHigh075GeminiProviderHardening: |
| 800 | def test_gemini_sends_api_key_in_header_not_query_string(self): |
| 801 | assert "?key=" not in providers.GEMINI_URL |
| 802 | secret = "dummy-gemini-key&extra=1#frag" |
| 803 | client = providers.GeminiClient(secret) |
| 804 | captured: dict = {} |
| 805 | |
| 806 | def fake_post(url, body, *, headers=None, timeout=None, redirect_guard=None, **kwargs): |
| 807 | captured["url"] = url |
| 808 | captured["headers"] = headers |
| 809 | captured["redirect_guard"] = redirect_guard |
| 810 | return {"candidates": [{"content": {"parts": [{"text": "ok"}]}}]} |
| 811 | |
| 812 | with mock.patch.object(providers.http, "post", side_effect=fake_post): |
| 813 | assert client.generate_text("gemini-3.1-flash-lite", "hello") == "ok" |
| 814 | |
| 815 | assert secret not in captured["url"] |
| 816 | assert "?key=" not in captured["url"] |
| 817 | assert captured["url"] == ( |
| 818 | "https://generativelanguage.googleapis.com/v1beta/models/" |
| 819 | "gemini-3.1-flash-lite:generateContent" |
| 820 | ) |
| 821 | assert captured["headers"]["x-goog-api-key"] == secret |
| 822 | assert callable(captured["redirect_guard"]) |
| 823 | assert captured["redirect_guard"]( |
| 824 | "https://generativelanguage.googleapis.com/v1beta/models/other:generateContent" |
| 825 | ) is True |
| 826 | assert captured["redirect_guard"]("https://attacker.example/steal") is False |
| 827 | assert captured["redirect_guard"]("http://generativelanguage.googleapis.com/downgrade") is False |
| 828 | |
| 829 | def test_gemini_cross_origin_redirect_refused_before_leaking_header(self): |
| 830 | leaked: dict = {} |
| 831 | |
| 832 | class Attacker(http.server.BaseHTTPRequestHandler): |
| 833 | def do_POST(self): |
| 834 | leaked.update({k.lower(): v for k, v in self.headers.items()}) |
| 835 | self.send_response(200) |
| 836 | self.end_headers() |
| 837 | self.wfile.write(b'{"candidates":[]}') |
| 838 | |
| 839 | def do_GET(self): |
| 840 | self.do_POST() |
| 841 | |
| 842 | def log_message(self, *_args): |
| 843 | pass |
| 844 | |
| 845 | attacker = socketserver.TCPServer(("127.0.0.1", 0), Attacker) |
| 846 | threading.Thread(target=attacker.serve_forever, daemon=True).start() |
| 847 | attacker_port = attacker.server_address[1] |
| 848 | |
| 849 | class Victim(http.server.BaseHTTPRequestHandler): |
| 850 | def do_POST(self): |
| 851 | self.send_response(307) |
| 852 | self.send_header("Location", f"http://127.0.0.1:{attacker_port}/steal") |
| 853 | self.send_header("Content-Length", "0") |
| 854 | self.end_headers() |
| 855 | |
| 856 | def log_message(self, *_args): |
| 857 | pass |
| 858 | |
| 859 | victim = socketserver.TCPServer(("127.0.0.1", 0), Victim) |
| 860 | threading.Thread(target=victim.serve_forever, daemon=True).start() |
| 861 | victim_port = victim.server_address[1] |
| 862 | |
| 863 | try: |
| 864 | client = providers.GeminiClient("dummy-gemini-redirect-secret-075") |
| 865 | redirect_url = f"http://127.0.0.1:{victim_port}/v1beta/models/{{model}}:generateContent" |
| 866 | with mock.patch.object(providers, "GEMINI_URL", redirect_url): |
| 867 | with pytest.raises(providers.http.HTTPError): |
| 868 | client.generate_text("gemini-3.1-flash-lite", "hello") |
| 869 | assert "x-goog-api-key" not in leaked |
| 870 | finally: |
| 871 | victim.shutdown() |
| 872 | victim.server_close() |
| 873 | attacker.shutdown() |
| 874 | attacker.server_close() |
| 875 | |
| 876 | @pytest.mark.parametrize( |
| 877 | "malicious_model", |
| 878 | [ |
| 879 | "gemini-3.1-flash/../../evil?foo=bar", |
| 880 | "gemini-3.1-flash?alt=json", |
| 881 | "gemini-3.1-flash#fragment", |
| 882 | "gemini-3.1-flash\n", |
| 883 | "gemini-3.1-flash evil", |
| 884 | "gemini-3.1-..", |
| 885 | "gemini-3.1\\evil", |
| 886 | ], |
| 887 | ) |
| 888 | def test_gemini_model_pin_rejects_path_query_and_control_injection(self, malicious_model): |
| 889 | assert providers._is_gemini_31_or_newer(malicious_model) is False |
| 890 | runtime = providers.mock_runtime( |
| 891 | {"LAST30DAYS_PLANNER_MODEL": malicious_model, "LAST30DAYS_RERANK_MODEL": malicious_model}, |
| 892 | depth="default", |
| 893 | ) |
| 894 | assert runtime.planner_model == providers.GEMINI_FLASH_LITE |
| 895 | assert runtime.rerank_model == providers.GEMINI_FLASH_LITE |
| 896 | |
| 897 | client = providers.GeminiClient("dummy-key") |
| 898 | with pytest.raises(ValueError, match="Invalid Gemini model name"): |
| 899 | client.generate_text(malicious_model, "hello") |
| 900 | |
| 901 | @pytest.mark.parametrize( |
| 902 | "valid_model", |
| 903 | [ |
| 904 | "gemini-3.1", |
| 905 | "gemini-3.1-flash-lite", |
| 906 | "gemini-3.1-pro-preview", |
| 907 | "gemini-3.5-flash", |
| 908 | "gemini-4-hydrogen", |
| 909 | "gemini-10-pro", |
| 910 | ], |
| 911 | ) |
| 912 | def test_gemini_valid_31_plus_models_accepted(self, valid_model): |
| 913 | assert providers._is_gemini_31_or_newer(valid_model) is True |
| 914 | |
| 915 | def test_http_cross_origin_auth_headers_strips_x_goog_api_key(self): |
| 916 | assert "x-goog-api-key" in http_mod._CROSS_ORIGIN_AUTH_HEADERS |
| 917 | handler = http_mod._StripAuthOnCrossOriginRedirect() |
| 918 | req = Request( |
| 919 | "https://generativelanguage.googleapis.com/v1beta/models/m:generateContent", |
| 920 | headers={"X-Goog-Api-Key": "dummy-secret-075"}, |
| 921 | ) |
| 922 | cross = handler.redirect_request( |
| 923 | req, None, 302, "Found", {}, "https://attacker.example/steal" |
| 924 | ) |
| 925 | cross_headers = { |
| 926 | k.lower(): v |
| 927 | for store in (cross.headers, getattr(cross, "unredirected_hdrs", {})) |
| 928 | for k, v in store.items() |
| 929 | } |
| 930 | assert "x-goog-api-key" not in cross_headers |
| 931 | |
| 932 | same = handler.redirect_request( |
| 933 | req, |
| 934 | None, |
| 935 | 302, |
| 936 | "Found", |
| 937 | {}, |
| 938 | "https://generativelanguage.googleapis.com/v1beta/models/other:generateContent", |
| 939 | ) |
| 940 | same_headers = { |
| 941 | k.lower(): v |
| 942 | for store in (same.headers, getattr(same, "unredirected_hdrs", {})) |
| 943 | for k, v in store.items() |
| 944 | } |
| 945 | assert same_headers.get("x-goog-api-key") == "dummy-secret-075" |
| 946 | |
| 947 | @pytest.mark.parametrize( |
| 948 | "bad_model", |
| 949 | [ |
| 950 | "gemini-٣.١", |
| 951 | "gemini-٣.١-flash", |
| 952 | ".", |
| 953 | "..", |
| 954 | "%2e%2e", |
| 955 | "gemini-3.1-flash\u0085", |
| 956 | "gemini-3.1-flash\u00a0", |
| 957 | "gemini-3.1-flash\u2028", |
| 958 | ], |
| 959 | ) |
| 960 | def test_gemini_model_rejects_unicode_digits_dots_and_control_chars(self, bad_model): |
| 961 | assert providers._is_gemini_31_or_newer(bad_model) is False |
| 962 | client = providers.GeminiClient("dummy-key") |
| 963 | with pytest.raises(ValueError, match="Invalid Gemini model name"): |
| 964 | client.generate_text(bad_model, "hello") |
| 965 | |
| 966 | def test_gemini_redirect_guard_handles_malformed_port_without_value_error(self): |
| 967 | client = providers.GeminiClient("dummy-key") |
| 968 | captured: dict = {} |
| 969 | |
| 970 | def fake_post(url, body, *, headers=None, timeout=None, redirect_guard=None, **kwargs): |
| 971 | captured["redirect_guard"] = redirect_guard |
| 972 | return {"candidates": [{"content": {"parts": [{"text": "ok"}]}}]} |
| 973 | |
| 974 | with mock.patch.object(providers.http, "post", side_effect=fake_post): |
| 975 | client.generate_text("gemini-3.1-flash-lite", "hello") |
| 976 | |
| 977 | assert captured["redirect_guard"]("https://generativelanguage.googleapis.com:99999/x") is False |
| 978 | |
| 979 | |
| 980 | class TestReviewRound2Regressions: |
| 981 | """Regressions for PR 13 adversarial review findings.""" |
| 982 | |
| 983 | def test_cli_corpus_flag_disclosed_in_preflight_and_disables_hosted_mode( |
| 984 | self, tmp_path, monkeypatch, capsys |
| 985 | ): |
| 986 | notes = tmp_path / "cli-notes" |
| 987 | notes.mkdir() |
| 988 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 989 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key-r2") |
| 990 | monkeypatch.setattr( |
| 991 | sys, |
| 992 | "argv", |
| 993 | ["last30days.py", "--preflight", "--emit=json", "--corpus", str(notes)], |
| 994 | ) |
| 995 | assert cli.main() == 0 |
| 996 | payload = json.loads(capsys.readouterr().out) |
| 997 | assert payload["local_reads"]["corpus_dirs"] == [str(notes.resolve())] |
| 998 | assert payload["network"]["hosted_mode"] is False |
| 999 | assert "hosted" not in payload["network"]["available_sources"] |
| 1000 | |
| 1001 | @pytest.mark.parametrize( |
| 1002 | "store_content", |
| 1003 | [ |
| 1004 | "apps:\n app:\n bearer_token: []\n oauth2_tokens:\n me:\n access_token: tok\n", |
| 1005 | "apps:\n app:\n bearer_token:\n bearer: null\n type: app\n oauth2_tokens:\n me:\n access_token: tok\n", |
| 1006 | json.dumps({"bearer_token": {"bearer": None, "type": "app"}, "oauth2_tokens": {"me": {"access_token": "tok"}}}), |
| 1007 | ], |
| 1008 | ) |
| 1009 | def test_xurl_oauth2_only_rejected_consistently_across_all_surfaces(self, tmp_path, store_content): |
| 1010 | store = tmp_path / ".xurl" / "auth.yml" |
| 1011 | store.parent.mkdir(exist_ok=True) |
| 1012 | store.write_text(store_content, encoding="utf-8") |
| 1013 | |
| 1014 | assert env._X_METHOD_LABELS["xurl"] == "bearer" |
| 1015 | with mock.patch("lib.xurl_x.token_store_path", return_value=store), \ |
| 1016 | mock.patch("lib.xurl_x.shutil.which", side_effect=lambda n: "/usr/bin/xurl" if n == "xurl" else None), \ |
| 1017 | mock.patch("lib.backends.which", side_effect=lambda n: "/usr/bin/xurl" if n == "xurl" else None): |
| 1018 | assert xurl_x.stored_auth_status()[0] == xurl_x.AUTH_MISSING |
| 1019 | assert xurl_x.has_stored_auth() is False |
| 1020 | assert env.get_x_source({"LAST30DAYS_HOST": "grok-bot"}, local_only=True) is None |
| 1021 | assert env.get_x_source_status({"LAST30DAYS_HOST": "grok-bot"}, probe=False)["xurl_available"] is False |
| 1022 | assert doctor._x_auth_path({"LAST30DAYS_HOST": "grok-bot"})["armed"] is False |
| 1023 | finding = backends._probe_xurl({}) |
| 1024 | assert finding.status == health.MISSING |
| 1025 | assert "app-only bearer" in finding.detail.lower() |
| 1026 | |
| 1027 | @pytest.mark.skipif(os.name != "posix", reason="POSIX FIFO check") |
| 1028 | def test_xurl_store_and_doctor_cache_do_not_block_on_fifo(self, tmp_path, monkeypatch): |
| 1029 | fifo_dir = tmp_path / ".xurl" |
| 1030 | fifo_dir.mkdir() |
| 1031 | fifo_store = fifo_dir / "auth.yml" |
| 1032 | os.mkfifo(fifo_store) |
| 1033 | with mock.patch("lib.xurl_x.token_store_path", return_value=fifo_store), \ |
| 1034 | mock.patch("lib.backends.which", side_effect=lambda n: "/usr/bin/xurl" if n == "xurl" else None): |
| 1035 | status, _ = xurl_x.stored_auth_status() |
| 1036 | assert status == xurl_x.AUTH_MISSING |
| 1037 | with pytest.raises(OSError, match="regular"): |
| 1038 | xurl_x._read_token_store_text(fifo_store) |
| 1039 | finding = backends._probe_xurl({}) |
| 1040 | assert finding.status == health.MISSING |
| 1041 | |
| 1042 | cfg_dir = tmp_path / "cfg" |
| 1043 | cfg_dir.mkdir() |
| 1044 | os.mkfifo(cfg_dir / doctor.CACHE_FILENAME) |
| 1045 | monkeypatch.setattr(env, "CONFIG_DIR", cfg_dir) |
| 1046 | assert doctor.read_cached_report({}) is None |
| 1047 | |
| 1048 | def test_doctor_cache_short_secret_values_do_not_disable_caching_and_size_cap_enforced( |
| 1049 | self, tmp_path, monkeypatch |
| 1050 | ): |
| 1051 | cfg_dir = tmp_path / "cfg" |
| 1052 | monkeypatch.setattr(env, "CONFIG_DIR", cfg_dir) |
| 1053 | report = TestHigh071DoctorCacheHardening._sample_report("ok") |
| 1054 | assert doctor._write_cache( |
| 1055 | report, |
| 1056 | { |
| 1057 | "BRIGHTDATA_API_KEY": "ok", |
| 1058 | "LAST30DAYS_PUBLISH_PASSWORD": "1", |
| 1059 | "LAST30DAYS_API_KEY": "yes", |
| 1060 | }, |
| 1061 | ) is True |
| 1062 | assert doctor.read_cached_report( |
| 1063 | { |
| 1064 | "BRIGHTDATA_API_KEY": "ok", |
| 1065 | "LAST30DAYS_PUBLISH_PASSWORD": "1", |
| 1066 | "LAST30DAYS_API_KEY": "yes", |
| 1067 | } |
| 1068 | ) is not None |
| 1069 | |
| 1070 | # Oversized cache file (>4 MiB) is ignored safely. |
| 1071 | cache_file = cfg_dir / doctor.CACHE_FILENAME |
| 1072 | cache_file.write_bytes(b" " * (doctor._MAX_DOCTOR_CACHE_BYTES + 16)) |
| 1073 | assert doctor.read_cached_report({}) is None |
| 1074 | |
| 1075 | def test_in_memory_poll_does_not_unlink_disk_handle_and_windows_temp_has_user_suffix( |
| 1076 | self, tmp_path, monkeypatch |
| 1077 | ): |
| 1078 | sentinel = tmp_path / "existing-handle.json" |
| 1079 | sentinel.write_text('{"device_code": "keep"}', encoding="utf-8") |
| 1080 | with mock.patch.object(setup_wizard, "_device_handle_path", return_value=sentinel), \ |
| 1081 | mock.patch.object(setup_wizard, "poll_device_auth", return_value=None): |
| 1082 | res = setup_wizard.run_github_poll( |
| 1083 | timeout=1, |
| 1084 | _handle={"device_code": "mem-only", "interval": 1, "user_code": "ABCD-1234"}, |
| 1085 | ) |
| 1086 | assert res["status"] == "timeout" |
| 1087 | assert sentinel.exists() |
| 1088 | |
| 1089 | monkeypatch.setattr(env, "CONFIG_FILE", None) |
| 1090 | monkeypatch.setattr(setup_wizard, "os", _NtOs()) |
| 1091 | monkeypatch.delenv("LOCALAPPDATA", raising=False) |
| 1092 | monkeypatch.setenv("USERNAME", "Alice/Bob") |
| 1093 | path = setup_wizard._device_handle_path() |
| 1094 | assert path.parent == Path(tempfile.gettempdir()) / "last30days-Alice_Bob" |
| 1095 | assert path.name == "github-device-handle.json" |
| 1096 | |
| 1097 | |
| 1098 | class TestGreptileRound3Regressions: |
| 1099 | """Regressions for PR 13 Greptile findings.""" |
| 1100 | |
| 1101 | def test_preflight_deep_research_and_default_search_with_corpus_disable_hosted_mode( |
| 1102 | self, tmp_path, monkeypatch, capsys |
| 1103 | ): |
| 1104 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 1105 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key-r3") |
| 1106 | |
| 1107 | # --deep-research runs locally in CLI, so preflight must report hosted_mode=False. |
| 1108 | monkeypatch.setattr( |
| 1109 | sys, |
| 1110 | "argv", |
| 1111 | ["last30days.py", "--preflight", "--emit=json", "--deep-research"], |
| 1112 | ) |
| 1113 | assert cli.main() == 0 |
| 1114 | deep_payload = json.loads(capsys.readouterr().out) |
| 1115 | assert deep_payload["network"]["hosted_mode"] is False |
| 1116 | assert "hosted" not in deep_payload["network"]["available_sources"] |
| 1117 | |
| 1118 | # Configured corpus keeps CLI local even when LAST30DAYS_DEFAULT_SEARCH=reddit |
| 1119 | # omits corpus from planned local_reads.corpus_dirs. |
| 1120 | notes = tmp_path / "notes" |
| 1121 | notes.mkdir() |
| 1122 | monkeypatch.setenv("LAST30DAYS_CORPUS_DIRS", str(notes)) |
| 1123 | monkeypatch.setenv("LAST30DAYS_DEFAULT_SEARCH", "reddit") |
| 1124 | monkeypatch.setattr( |
| 1125 | sys, |
| 1126 | "argv", |
| 1127 | ["last30days.py", "--preflight", "--emit=json"], |
| 1128 | ) |
| 1129 | assert cli.main() == 0 |
| 1130 | reddit_payload = json.loads(capsys.readouterr().out) |
| 1131 | assert reddit_payload["local_reads"]["corpus_dirs"] == [] |
| 1132 | assert reddit_payload["network"]["hosted_mode"] is False |
| 1133 | assert "hosted" not in reddit_payload["network"]["available_sources"] |
| 1134 | |
| 1135 | # EXCLUDE_SOURCES=corpus disables corpus completely and restores hosted mode. |
| 1136 | monkeypatch.setenv("EXCLUDE_SOURCES", "corpus") |
| 1137 | monkeypatch.setattr( |
| 1138 | sys, |
| 1139 | "argv", |
| 1140 | ["last30days.py", "--preflight", "--emit=json"], |
| 1141 | ) |
| 1142 | assert cli.main() == 0 |
| 1143 | excluded_payload = json.loads(capsys.readouterr().out) |
| 1144 | assert excluded_payload["local_reads"]["corpus_dirs"] == [] |
| 1145 | assert excluded_payload["network"]["hosted_mode"] is True |
| 1146 | assert excluded_payload["network"]["available_sources"] == ["hosted"] |
| 1147 | |
| 1148 | def test_doctor_cache_fingerprint_tracks_hosted_key_endpoint_and_corpus_without_leaking( |
| 1149 | self, tmp_path, monkeypatch |
| 1150 | ): |
| 1151 | cfg_dir = tmp_path / "cfg" |
| 1152 | notes = tmp_path / "notes" |
| 1153 | notes.mkdir() |
| 1154 | monkeypatch.setattr(env, "CONFIG_DIR", cfg_dir) |
| 1155 | |
| 1156 | base_fp = doctor._config_fingerprint({}) |
| 1157 | |
| 1158 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-fp-secret-r3") |
| 1159 | key_fp = doctor._config_fingerprint({}) |
| 1160 | assert key_fp != base_fp |
| 1161 | |
| 1162 | monkeypatch.setenv("LAST30DAYS_API_BASE", "http://cleartext.example/api/v1") |
| 1163 | invalid_ep_fp = doctor._config_fingerprint({}) |
| 1164 | assert invalid_ep_fp != key_fp |
| 1165 | |
| 1166 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 1167 | valid_ep_fp = doctor._config_fingerprint({}) |
| 1168 | assert valid_ep_fp != invalid_ep_fp |
| 1169 | |
| 1170 | monkeypatch.setenv("LAST30DAYS_API_MODE", "proxy") |
| 1171 | proxy_fp = doctor._config_fingerprint({}) |
| 1172 | assert proxy_fp != valid_ep_fp |
| 1173 | |
| 1174 | monkeypatch.delenv("LAST30DAYS_API_MODE", raising=False) |
| 1175 | corpus_fp = doctor._config_fingerprint({"LAST30DAYS_CORPUS_DIRS": str(notes)}) |
| 1176 | assert corpus_fp != valid_ep_fp |
| 1177 | |
| 1178 | report = TestHigh071DoctorCacheHardening._sample_report("ok") |
| 1179 | assert doctor._write_cache(report, {}) is True |
| 1180 | raw_cache = (cfg_dir / doctor.CACHE_FILENAME).read_text(encoding="utf-8") |
| 1181 | assert "dummy-hosted-fp-secret-r3" not in raw_cache |
| 1182 | assert "hosted.example" not in raw_cache |
| 1183 | |
| 1184 | def test_preflight_discloses_secret_stores_even_in_hosted_mode(self, monkeypatch): |
| 1185 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 1186 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key-r3") |
| 1187 | monkeypatch.delenv(env.KEYCHAIN_DISABLE_ENV, raising=False) |
| 1188 | with mock.patch.object(permission_preflight.platform, "system", return_value="Darwin"), \ |
| 1189 | mock.patch.object( |
| 1190 | permission_preflight.shutil, |
| 1191 | "which", |
| 1192 | side_effect=lambda cmd: f"/usr/bin/{cmd}" if cmd in {"security", "pass"} else None, |
| 1193 | ): |
| 1194 | preflight = permission_preflight.build( |
| 1195 | {}, |
| 1196 | _diag(config_source="global:/Users/tester/.config/last30days/.env"), |
| 1197 | ) |
| 1198 | assert preflight["network"]["hosted_mode"] is True |
| 1199 | assert preflight["local_reads"]["secret_stores"] == ["keychain", "pass"] |
| 1200 | assert "Secret stores: keychain, pass" in permission_preflight.render_text(preflight) |
| 1201 | |
| 1202 | def test_probe_xurl_reads_token_store_once_without_redundant_reread(self, tmp_path): |
| 1203 | store = tmp_path / ".xurl" / "auth.yml" |
| 1204 | store.parent.mkdir() |
| 1205 | store.write_text("apps:\n app:\n bearer_token:\n bearer: dummy-bearer-r3\n", encoding="utf-8") |
| 1206 | |
| 1207 | assert not hasattr(backends, "_xurl_store_lacks_bearer") |
| 1208 | with mock.patch("lib.backends.which", side_effect=lambda n: "/usr/bin/xurl" if n == "xurl" else None), \ |
| 1209 | mock.patch("lib.xurl_x.token_store_path", return_value=store), \ |
| 1210 | mock.patch.object( |
| 1211 | xurl_x, "_read_token_store_text", wraps=xurl_x._read_token_store_text |
| 1212 | ) as read_spy: |
| 1213 | finding = backends._probe_xurl({}) |
| 1214 | assert finding.status == health.OK |
| 1215 | assert read_spy.call_count == 1 |
| 1216 | |
| 1217 | def test_preflight_does_not_report_proxy_sentinels_as_direct_xai_or_scrapecreators_keys( |
| 1218 | self, monkeypatch |
| 1219 | ): |
| 1220 | monkeypatch.setenv("LAST30DAYS_API_MODE", "proxy") |
| 1221 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://proxy.example/api/v1") |
| 1222 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-proxy-key-r3") |
| 1223 | config = { |
| 1224 | "XAI_API_KEY": proxy.SENTINEL, |
| 1225 | "SCRAPECREATORS_API_KEY": proxy.SENTINEL, |
| 1226 | "SERPER_API_KEY": proxy.SENTINEL, |
| 1227 | "PARALLEL_API_KEY": proxy.SENTINEL, |
| 1228 | } |
| 1229 | diag = _diag( |
| 1230 | providers={ |
| 1231 | "google": False, |
| 1232 | "openai": False, |
| 1233 | "xai": True, |
| 1234 | "openrouter": False, |
| 1235 | "perplexity": False, |
| 1236 | }, |
| 1237 | has_scrapecreators=True, |
| 1238 | ) |
| 1239 | preflight = permission_preflight.build(config, diag) |
| 1240 | assert preflight["credentials"]["xai"]["present"] is False |
| 1241 | assert preflight["credentials"]["scrapecreators"]["present"] is False |
| 1242 | assert preflight["credentials"]["serper"]["present"] is False |
| 1243 | assert preflight["credentials"]["parallel"]["present"] is False |
| 1244 | assert preflight["credentials"]["hosted_api"]["present"] is True |
| 1245 | text = permission_preflight.render_text(preflight) |
| 1246 | assert "xAI API key" not in text |
| 1247 | assert "ScrapeCreators API key" not in text |
| 1248 | assert "last30days hosted/proxy API key" in text |
| 1249 | |
| 1250 | def test_preflight_perplexity_search_type_matches_research_run_when_key_only_in_secret_store( |
| 1251 | self, tmp_path, monkeypatch, capsys |
| 1252 | ): |
| 1253 | """Agent host without --plan skips Keychain/pass before hosted dispatch; |
| 1254 | --preflight --perplexity-search-type must agree with the real research run.""" |
| 1255 | from lib import hosted as hosted_mod |
| 1256 | |
| 1257 | monkeypatch.setenv("CLAUDECODE", "1") |
| 1258 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example/api/v1") |
| 1259 | monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key-r4") |
| 1260 | monkeypatch.delenv("PERPLEXITY_API_KEY", raising=False) |
| 1261 | monkeypatch.delenv("LAST30DAYS_ALLOW_ENGINE_PLAN", raising=False) |
| 1262 | |
| 1263 | with mock.patch.object( |
| 1264 | env, "_load_keychain", return_value={"PERPLEXITY_API_KEY": "dummy-kc-pplx-key"} |
| 1265 | ), mock.patch.object(env, "_load_pass", return_value={}): |
| 1266 | # 1. --preflight with --perplexity-search-type=fast stays hosted because |
| 1267 | # the real research run won't query Keychain on an agent host without --plan. |
| 1268 | monkeypatch.setattr( |
| 1269 | sys, |
| 1270 | "argv", |
| 1271 | ["last30days.py", "--preflight", "--emit=json", "--perplexity-search-type=fast"], |
| 1272 | ) |
| 1273 | assert cli.main() == 0 |
| 1274 | preflight_payload = json.loads(capsys.readouterr().out) |
| 1275 | assert preflight_payload["network"]["hosted_mode"] is True |
| 1276 | assert preflight_payload["network"]["available_sources"] == ["hosted"] |
| 1277 | |
| 1278 | # 2. Verify the actual research run with the same flags also dispatches hosted! |
| 1279 | hosted_calls: list[tuple] = [] |
| 1280 | |
| 1281 | def fake_run_hosted(*args, **kwargs): |
| 1282 | hosted_calls.append((args, kwargs)) |
| 1283 | return 0 |
| 1284 | |
| 1285 | monkeypatch.setattr( |
| 1286 | sys, |
| 1287 | "argv", |
| 1288 | ["last30days.py", "AI agents", "--perplexity-search-type=fast"], |
| 1289 | ) |
| 1290 | with mock.patch.object(hosted_mod, "run_hosted", side_effect=fake_run_hosted): |
| 1291 | assert cli.main() == 0 |
| 1292 | assert len(hosted_calls) == 1 |
| 1293 | |
| 1294 | # 3. When PERPLEXITY_API_KEY is in .env (available without secret stores), |
| 1295 | # --preflight --perplexity-search-type=fast DOES bypass hosted mode. |
| 1296 | env_file = tmp_path / ".env" |
| 1297 | env_file.write_text("PERPLEXITY_API_KEY=dummy-env-pplx-key\n", encoding="utf-8") |
| 1298 | monkeypatch.setattr(env, "CONFIG_FILE", env_file) |
| 1299 | monkeypatch.setattr( |
| 1300 | sys, |
| 1301 | "argv", |
| 1302 | ["last30days.py", "--preflight", "--emit=json", "--perplexity-search-type=fast"], |
| 1303 | ) |
| 1304 | assert cli.main() == 0 |
| 1305 | env_payload = json.loads(capsys.readouterr().out) |
| 1306 | assert env_payload["network"]["hosted_mode"] is False |
| 1307 | assert "hosted" not in env_payload["network"]["available_sources"] |
| 1308 |