| 1 | """Regression tests for agent-host local-read boundaries.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import importlib |
| 6 | import io |
| 7 | import json |
| 8 | import os |
| 9 | import subprocess |
| 10 | import sys |
| 11 | from contextlib import redirect_stderr, redirect_stdout |
| 12 | from pathlib import Path |
| 13 | from unittest import mock |
| 14 | |
| 15 | import pytest |
| 16 | |
| 17 | import last30days as cli |
| 18 | from lib import env |
| 19 | |
| 20 | |
| 21 | def test_importing_cli_does_not_load_config_or_propagate_endpoints(monkeypatch): |
| 22 | monkeypatch.delenv("OPENAI_BASE_URL", raising=False) |
| 23 | monkeypatch.delenv("XAI_BASE_URL", raising=False) |
| 24 | with mock.patch("lib.env.get_config", side_effect=AssertionError("import loaded config")) as get_config: |
| 25 | importlib.reload(cli) |
| 26 | get_config.assert_not_called() |
| 27 | assert os.environ.get("OPENAI_BASE_URL") is None |
| 28 | assert os.environ.get("XAI_BASE_URL") is None |
| 29 | |
| 30 | |
| 31 | @pytest.mark.parametrize("mode", ["import", "help"]) |
| 32 | def test_cold_cli_does_not_attempt_config_or_cookie_access(tmp_path, mode): |
| 33 | scripts = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts" |
| 34 | attempts = tmp_path / "attempts.json" |
| 35 | binary_dir = tmp_path / "bin" |
| 36 | binary_dir.mkdir() |
| 37 | sidecar = binary_dir / "agentcookie" |
| 38 | sidecar.write_text("#!/bin/sh\nprintf 'unexpected sidecar execution'\nexit 1\n") |
| 39 | sidecar.chmod(0o700) |
| 40 | # No inherited credentials or host paths: even a regression stays inside |
| 41 | # this fixture, and an exception caught by the CLI cannot hide an attempt. |
| 42 | child_env = { |
| 43 | "HOME": str(tmp_path), |
| 44 | "USERPROFILE": str(tmp_path), |
| 45 | "XDG_CONFIG_HOME": str(tmp_path / ".config"), |
| 46 | "LAST30DAYS_CONFIG_DIR": str(tmp_path / ".config" / "last30days"), |
| 47 | "LAST30DAYS_SKIP_KEYCHAIN": "1", |
| 48 | "PATH": str(binary_dir), |
| 49 | } |
| 50 | result = subprocess.run( |
| 51 | [sys.executable, "-I", "-c", """ |
| 52 | import json |
| 53 | from pathlib import Path |
| 54 | import socket |
| 55 | import subprocess |
| 56 | import sys |
| 57 | scripts, output, mode = sys.argv[1:] |
| 58 | sys.path.insert(0, scripts) |
| 59 | attempts = [] |
| 60 | def forbid(name): |
| 61 | def denied(*args, **kwargs): |
| 62 | attempts.append(name) |
| 63 | raise AssertionError("unexpected acquisition") |
| 64 | return denied |
| 65 | subprocess.Popen = forbid("subprocess") |
| 66 | socket.create_connection = forbid("network") |
| 67 | socket.socket.connect = forbid("network") |
| 68 | socket.getaddrinfo = forbid("network") |
| 69 | from lib import env |
| 70 | env.get_config = forbid("get_config") |
| 71 | try: |
| 72 | import last30days |
| 73 | if mode == "help": |
| 74 | sys.argv = ["last30days.py", "--help"] |
| 75 | try: |
| 76 | last30days.main() |
| 77 | except SystemExit as error: |
| 78 | if error.code != 0: |
| 79 | raise |
| 80 | finally: |
| 81 | Path(output).write_text(json.dumps(attempts)) |
| 82 | """, str(scripts), str(attempts), mode], |
| 83 | env=child_env, cwd=tmp_path, capture_output=True, text=True, timeout=30, |
| 84 | ) |
| 85 | assert result.returncode == 0, result.stderr |
| 86 | assert json.loads(attempts.read_text()) == [] |
| 87 | if mode == "help": |
| 88 | assert "usage:" in result.stdout.lower() |
| 89 | |
| 90 | |
| 91 | def test_diagnose_uses_plan_only_cookie_policy_and_safe_pipeline(monkeypatch): |
| 92 | seen: dict[str, object] = {} |
| 93 | |
| 94 | def fake_get_config(*, policy): |
| 95 | seen["policy"] = policy |
| 96 | return {"_BROWSER_COOKIE_MODE": policy.browser_cookies, "_BROWSER_COOKIE_BROWSERS": ["firefox"]} |
| 97 | |
| 98 | with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \ |
| 99 | mock.patch.object(cli.pipeline, "diagnose", return_value={"ok": True}) as diagnose, \ |
| 100 | mock.patch.object(sys, "argv", ["last30days.py", "--diagnose"]): |
| 101 | stdout = io.StringIO() |
| 102 | stderr = io.StringIO() |
| 103 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 104 | assert cli.main() == 0 |
| 105 | |
| 106 | assert seen["policy"].browser_cookies == "plan_only" |
| 107 | diagnose.assert_called_once_with( |
| 108 | {"_BROWSER_COOKIE_MODE": "plan_only", "_BROWSER_COOKIE_BROWSERS": ["firefox"]}, |
| 109 | None, |
| 110 | safe=True, |
| 111 | x_envelope=False, |
| 112 | ) |
| 113 | assert json.loads(stdout.getvalue()) == {"ok": True} |
| 114 | |
| 115 | |
| 116 | def test_setup_without_cookie_flag_disables_browser_cookie_setup(monkeypatch): |
| 117 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 118 | mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as setup, \ |
| 119 | mock.patch("lib.setup_wizard.write_setup_config", return_value=True), \ |
| 120 | mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \ |
| 121 | mock.patch.object(sys, "argv", ["last30days.py", "setup"]): |
| 122 | stdout = io.StringIO() |
| 123 | stderr = io.StringIO() |
| 124 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 125 | assert cli.main() == 0 |
| 126 | |
| 127 | assert setup.call_args.kwargs["allow_browser_cookies"] is False |
| 128 | |
| 129 | |
| 130 | def test_setup_cookie_flag_allows_browser_cookie_setup(monkeypatch): |
| 131 | with mock.patch.object(cli.env, "get_config", return_value={}), \ |
| 132 | mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as setup, \ |
| 133 | mock.patch("lib.setup_wizard.write_setup_config", return_value=True), \ |
| 134 | mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \ |
| 135 | mock.patch.object(sys, "argv", ["last30days.py", "setup", "--allow-browser-cookies"]): |
| 136 | stdout = io.StringIO() |
| 137 | stderr = io.StringIO() |
| 138 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 139 | assert cli.main() == 0 |
| 140 | |
| 141 | assert setup.call_args.kwargs["allow_browser_cookies"] is True |
| 142 | |
| 143 | |
| 144 | def test_no_browser_cookies_overrides_setup_cookie_flag(monkeypatch): |
| 145 | seen: dict[str, object] = {} |
| 146 | |
| 147 | def fake_get_config(*, policy): |
| 148 | seen["policy"] = policy |
| 149 | return {} |
| 150 | |
| 151 | with mock.patch.object(cli.env, "get_config", side_effect=fake_get_config), \ |
| 152 | mock.patch("lib.setup_wizard.run_auto_setup", return_value={"cookies_found": {}}) as setup, \ |
| 153 | mock.patch("lib.setup_wizard.write_setup_config", return_value=True), \ |
| 154 | mock.patch("lib.setup_wizard.get_setup_status_text", return_value="ok"), \ |
| 155 | mock.patch.object( |
| 156 | sys, |
| 157 | "argv", |
| 158 | ["last30days.py", "--no-browser-cookies", "setup", "--allow-browser-cookies"], |
| 159 | ): |
| 160 | stdout = io.StringIO() |
| 161 | stderr = io.StringIO() |
| 162 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 163 | assert cli.main() == 0 |
| 164 | |
| 165 | assert seen["policy"].browser_cookies == "off" |
| 166 | assert setup.call_args.kwargs["allow_browser_cookies"] is False |
| 167 | |
| 168 | |
| 169 | def test_diagnose_overrides_setup_cookie_flag(monkeypatch): |
| 170 | parser = cli.build_parser() |
| 171 | args, extra = parser.parse_known_args(["--diagnose", "setup", "--allow-browser-cookies"]) |
| 172 | assert cli._config_policy_for_args(args, "setup", extra).browser_cookies == "plan_only" |
| 173 | assert cli._setup_has_fresh_browser_consent(args, extra) is False |
| 174 | |
| 175 | with mock.patch.object(cli.env, "get_config", side_effect=AssertionError("setup --diagnose must not load config")), \ |
| 176 | mock.patch("lib.setup_wizard.run_auto_setup", side_effect=AssertionError("setup must not run under --diagnose")), \ |
| 177 | mock.patch("lib.setup_wizard.write_setup_config", side_effect=AssertionError("setup must not write under --diagnose")), \ |
| 178 | mock.patch.object( |
| 179 | sys, |
| 180 | "argv", |
| 181 | ["last30days.py", "--diagnose", "setup", "--allow-browser-cookies"], |
| 182 | ): |
| 183 | stdout = io.StringIO() |
| 184 | stderr = io.StringIO() |
| 185 | with redirect_stdout(stdout), redirect_stderr(stderr): |
| 186 | assert cli.main() == 2 |
| 187 | |
| 188 | assert "--diagnose cannot be combined" in stderr.getvalue() |
| 189 | |
| 190 | |
| 191 | def test_research_run_defaults_to_browser_cookie_read(): |
| 192 | """A plain research run reads cookies (the path that powers X auth).""" |
| 193 | parser = cli.build_parser() |
| 194 | args, extra = parser.parse_known_args(["some topic"]) |
| 195 | policy = cli._config_policy_for_args(args, "some topic", extra) |
| 196 | assert policy.browser_cookies == "read" |
| 197 | |
| 198 | |
| 199 | def test_no_browser_cookies_flag_disables_research_run_cookie_read(): |
| 200 | """--no-browser-cookies flips a research run to the no-read policy.""" |
| 201 | parser = cli.build_parser() |
| 202 | args, extra = parser.parse_known_args(["--no-browser-cookies", "some topic"]) |
| 203 | policy = cli._config_policy_for_args(args, "some topic", extra) |
| 204 | assert policy.browser_cookies == "off" |
| 205 | |
| 206 | |
| 207 | def test_watchlist_subprocess_disables_browser_cookies(): |
| 208 | """The unattended watchlist cron must never probe browser cookies.""" |
| 209 | import watchlist |
| 210 | |
| 211 | fake_result = mock.Mock(returncode=1, stdout="", stderr="boom") |
| 212 | with mock.patch.object(watchlist, "store") as store, \ |
| 213 | mock.patch.object(watchlist.subprocess, "run", return_value=fake_result) as run: |
| 214 | store.record_run.return_value = 1 |
| 215 | watchlist._run_topic({"id": 1, "name": "test topic", "search_queries": None}) |
| 216 | |
| 217 | argv = run.call_args.args[0] |
| 218 | assert "--no-browser-cookies" in argv |
| 219 | |
| 220 | |
| 221 | def test_project_config_ignored_by_default_and_cannot_self_trust(tmp_path, monkeypatch): |
| 222 | project_env = tmp_path / ".claude" / "last30days.env" |
| 223 | project_env.parent.mkdir() |
| 224 | project_env.write_text( |
| 225 | "LAST30DAYS_TRUST_PROJECT_CONFIG=1\nOPENAI_BASE_URL=https://example.invalid\n", |
| 226 | encoding="utf-8", |
| 227 | ) |
| 228 | monkeypatch.chdir(tmp_path) |
| 229 | monkeypatch.setattr(env, "CONFIG_FILE", None) |
| 230 | monkeypatch.delenv("LAST30DAYS_TRUST_PROJECT_CONFIG", raising=False) |
| 231 | monkeypatch.delenv("OPENAI_BASE_URL", raising=False) |
| 232 | |
| 233 | with mock.patch.object(env, "_load_keychain", return_value={}), \ |
| 234 | mock.patch.object(env, "_load_pass", return_value={}): |
| 235 | cfg = env.get_config() |
| 236 | |
| 237 | assert cfg["OPENAI_BASE_URL"] is None |
| 238 | assert cfg["_CONFIG_SOURCE"] == "env_only" |
| 239 | |
| 240 | |
| 241 | def test_project_config_loads_with_process_trust_signal(tmp_path, monkeypatch): |
| 242 | project_env = tmp_path / ".claude" / "last30days.env" |
| 243 | project_env.parent.mkdir() |
| 244 | project_env.write_text("OPENAI_BASE_URL=https://trusted.example\n", encoding="utf-8") |
| 245 | monkeypatch.chdir(tmp_path) |
| 246 | monkeypatch.setattr(env, "CONFIG_FILE", None) |
| 247 | monkeypatch.setenv("LAST30DAYS_TRUST_PROJECT_CONFIG", "1") |
| 248 | monkeypatch.delenv("OPENAI_BASE_URL", raising=False) |
| 249 | |
| 250 | with mock.patch.object(env, "_load_keychain", return_value={}), \ |
| 251 | mock.patch.object(env, "_load_pass", return_value={}): |
| 252 | cfg = env.get_config() |
| 253 | |
| 254 | assert cfg["OPENAI_BASE_URL"] == "https://trusted.example" |
| 255 | assert cfg["_CONFIG_SOURCE"].startswith(f"project:{project_env}") |
| 256 |