| 1 | """Reddit session consent, the cookie read, and onboarding (plan U6, AE1, AE10). |
| 2 | |
| 3 | Reading the reddit.com login cookie needs its own consent, separate from the |
| 4 | X browser consent, and every global refusal vetoes it. These tests watch the |
| 5 | cookie reader itself: a ``.reddit.com`` read is any ``extract_cookies`` call |
| 6 | for that domain. |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import contextlib |
| 12 | import io |
| 13 | import json |
| 14 | import os |
| 15 | import sys |
| 16 | from contextlib import redirect_stderr, redirect_stdout |
| 17 | from pathlib import Path |
| 18 | from unittest import mock |
| 19 | |
| 20 | import pytest |
| 21 | |
| 22 | import last30days as cli |
| 23 | from lib import cookie_extract, doctor, env, reddit_session, safari_cookies, setup_wizard |
| 24 | |
| 25 | COOKIE = "dummy-reddit-cookie-value-9876543210" |
| 26 | |
| 27 | |
| 28 | class CookieSpy: |
| 29 | """Stands in for cookie_extract.extract_cookies; records every domain read.""" |
| 30 | |
| 31 | def __init__(self, logged_in=("chrome",)): |
| 32 | self.logged_in = set(logged_in) |
| 33 | self.calls: list[tuple[str, str]] = [] |
| 34 | |
| 35 | def __call__(self, browser, domain, names): |
| 36 | self.calls.append((browser, domain)) |
| 37 | if domain == env.REDDIT_COOKIE_DOMAIN and browser in self.logged_in: |
| 38 | return {"reddit_session": COOKIE} |
| 39 | return None |
| 40 | |
| 41 | def reddit_reads(self): |
| 42 | return [b for b, d in self.calls if "reddit" in d] |
| 43 | |
| 44 | |
| 45 | @pytest.fixture |
| 46 | def spy(monkeypatch): |
| 47 | s = CookieSpy() |
| 48 | monkeypatch.setattr(cookie_extract, "extract_cookies", s) |
| 49 | monkeypatch.setattr(env, "x_extras_enabled", lambda _c: False) |
| 50 | return s |
| 51 | |
| 52 | |
| 53 | def _config(monkeypatch, mode="read", **values): |
| 54 | for key, value in values.items(): |
| 55 | monkeypatch.setenv(key, value) |
| 56 | return env.get_config(policy=env.ConfigLoadPolicy(browser_cookies=mode)) |
| 57 | |
| 58 | |
| 59 | def _session(config): |
| 60 | return reddit_session.session_for(config) |
| 61 | |
| 62 | |
| 63 | class TestAE1: |
| 64 | def test_x_consent_alone_never_reads_reddit(self, spy, monkeypatch): |
| 65 | config = _config(monkeypatch, BROWSER_CONSENT="true", FROM_BROWSER="chrome") |
| 66 | assert _session(config) is None |
| 67 | assert spy.reddit_reads() == [] |
| 68 | assert any(d == ".x.com" for _b, d in spy.calls) # X itself still reads |
| 69 | |
| 70 | def test_reddit_yes_plus_from_browser_off_reads_nothing(self, spy, monkeypatch): |
| 71 | config = _config(monkeypatch, REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome", |
| 72 | FROM_BROWSER="off") |
| 73 | assert _session(config) is None |
| 74 | assert spy.calls == [] |
| 75 | |
| 76 | def test_reddit_yes_outranks_an_x_refusal(self, monkeypatch): |
| 77 | config = _config(monkeypatch, REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome", |
| 78 | BROWSER_CONSENT="false") |
| 79 | assert env.reddit_session_gate(config) == (True, "") |
| 80 | |
| 81 | def test_browser_consent_false_without_a_reddit_yes_reads_nothing(self, spy, monkeypatch): |
| 82 | config = _config(monkeypatch, REDDIT_FROM_BROWSER="chrome", BROWSER_CONSENT="false") |
| 83 | assert _session(config) is None |
| 84 | assert spy.reddit_reads() == [] |
| 85 | |
| 86 | def test_from_browser_off_blocks_even_a_reddit_yes(self, spy, monkeypatch): |
| 87 | config = _config(monkeypatch, REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome", |
| 88 | FROM_BROWSER="off") |
| 89 | assert _session(config) is None |
| 90 | assert spy.reddit_reads() == [] |
| 91 | |
| 92 | def test_grok_bot_with_bird_pin_and_reddit_yes_reads_nothing(self, spy, monkeypatch): |
| 93 | config = _config(monkeypatch, LAST30DAYS_HOST="grok-bot", LAST30DAYS_X_BACKEND="bird", |
| 94 | REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome", FROM_BROWSER="chrome") |
| 95 | assert _session(config) is None |
| 96 | assert spy.reddit_reads() == [] |
| 97 | assert env.reddit_session_gate(config) == (False, "never on a Grok Bot host") |
| 98 | |
| 99 | |
| 100 | class TestVetoesAndContexts: |
| 101 | def test_diagnose_and_doctor_plan_only_read_nothing(self, spy, monkeypatch): |
| 102 | config = _config(monkeypatch, mode="plan_only", REDDIT_BROWSER_CONSENT="true", |
| 103 | REDDIT_FROM_BROWSER="chrome") |
| 104 | allowed, why = env.reddit_session_gate(config) |
| 105 | assert not allowed and "reads no browser cookies" in why |
| 106 | assert _session(config) is None |
| 107 | assert spy.calls == [] |
| 108 | |
| 109 | def test_no_browser_cookies_and_the_mcp_default_read_nothing(self, spy, monkeypatch): |
| 110 | config = _config(monkeypatch, mode="off", REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome") |
| 111 | assert _session(config) is None and spy.calls == [] |
| 112 | |
| 113 | def test_reddit_consent_false_disables_and_agentcookie_on_does_not_enable(self, spy, monkeypatch): |
| 114 | config = _config(monkeypatch, REDDIT_BROWSER_CONSENT="false", REDDIT_FROM_BROWSER="chrome", |
| 115 | AGENTCOOKIE="on") |
| 116 | assert _session(config) is None |
| 117 | assert spy.reddit_reads() == [] |
| 118 | |
| 119 | def test_hosted_backend_reads_nothing(self, spy, monkeypatch): |
| 120 | monkeypatch.setenv("LAST30DAYS_API_KEY", "hosted-test-key") |
| 121 | monkeypatch.setenv("LAST30DAYS_API_BASE", "https://hosted.example.test") |
| 122 | config = _config(monkeypatch, REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome") |
| 123 | assert env.reddit_session_gate(config)[1] == "the hosted API backend runs research remotely" |
| 124 | assert _session(config) is None and spy.reddit_reads() == [] |
| 125 | |
| 126 | def test_scheduled_run_reads_nothing_without_its_opt_in(self, spy, monkeypatch): |
| 127 | monkeypatch.setenv("LAST30DAYS_SCHEDULED_RUN", "1") |
| 128 | config = _config(monkeypatch, REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome") |
| 129 | assert _session(config) is None and spy.reddit_reads() == [] |
| 130 | reddit_session.reset_run_state() |
| 131 | config = _config(monkeypatch, LAST30DAYS_REDDIT_SESSION_SCHEDULED="1") |
| 132 | assert _session(config) is not None |
| 133 | assert spy.reddit_reads() == ["chrome"] |
| 134 | |
| 135 | def test_scheduled_marker_in_a_config_file_is_ignored(self, monkeypatch, tmp_path): |
| 136 | env.CONFIG_FILE.write_text("LAST30DAYS_SCHEDULED_RUN=1\n", encoding="utf-8") |
| 137 | env.CONFIG_FILE.chmod(0o600) |
| 138 | config = env.get_config() |
| 139 | assert not config.get("LAST30DAYS_SCHEDULED_RUN") |
| 140 | |
| 141 | def test_watchlist_runs_are_scheduled_and_cookie_free(self, monkeypatch): |
| 142 | import watchlist |
| 143 | |
| 144 | seen = {} |
| 145 | |
| 146 | def fake_run(argv, **kwargs): |
| 147 | seen["argv"], seen["env"] = argv, kwargs["env"] |
| 148 | raise RuntimeError("stop after capture") |
| 149 | |
| 150 | monkeypatch.setattr(watchlist.subprocess, "run", fake_run) |
| 151 | monkeypatch.setattr(watchlist.store, "update_run", lambda *a, **k: None) |
| 152 | with contextlib.suppress(Exception): |
| 153 | watchlist._research_topic({"id": 1, "name": "x", "search_queries": None}, 1, |
| 154 | {"LAST30DAYS_SCHEDULED_RUN": "1"}) |
| 155 | assert "--no-browser-cookies" in seen["argv"] |
| 156 | assert seen["env"]["LAST30DAYS_SCHEDULED_RUN"] == "1" |
| 157 | source = Path(watchlist.__file__).read_text(encoding="utf-8") |
| 158 | assert '"LAST30DAYS_SCHEDULED_RUN": "1"' in source |
| 159 | |
| 160 | |
| 161 | class TestBrowserChoice: |
| 162 | def test_reads_only_the_recorded_reddit_browser(self, spy, monkeypatch): |
| 163 | config = _config(monkeypatch, REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome") |
| 164 | session = _session(config) |
| 165 | assert session is not None and session.browser == "chrome" |
| 166 | assert spy.reddit_reads() == ["chrome"] |
| 167 | assert COOKIE not in repr(session) and COOKIE not in json.dumps( |
| 168 | {k: str(v) for k, v in config.items()} |
| 169 | ) |
| 170 | |
| 171 | def test_returning_user_with_firefox_for_x_gets_a_chrome_reddit_session(self, spy, monkeypatch): |
| 172 | config = _config(monkeypatch, BROWSER_CONSENT="true", FROM_BROWSER="firefox", |
| 173 | REDDIT_BROWSER_CONSENT="true", REDDIT_FROM_BROWSER="chrome") |
| 174 | assert _session(config) is not None |
| 175 | assert ("chrome", env.REDDIT_COOKIE_DOMAIN) in spy.calls |
| 176 | assert ("firefox", env.REDDIT_COOKIE_DOMAIN) not in spy.calls |
| 177 | assert all(b == "firefox" for b, d in spy.calls if d == ".x.com") |
| 178 | |
| 179 | def test_generic_browser_extract_never_reads_reddit(self, spy): |
| 180 | env.extract_browser_credentials({"FROM_BROWSER": "chrome", env.REDDIT_CONSENT_VAR: "true"}) |
| 181 | assert spy.reddit_reads() == [] |
| 182 | |
| 183 | def test_lookalike_host_cookie_is_rejected(self): |
| 184 | assert safari_cookies._host_matches(".reddit.com", env.REDDIT_COOKIE_DOMAIN) |
| 185 | assert safari_cookies._host_matches("www.reddit.com", env.REDDIT_COOKIE_DOMAIN) |
| 186 | assert not safari_cookies._host_matches("reddit.com.evil.tld", env.REDDIT_COOKIE_DOMAIN) |
| 187 | assert not safari_cookies._host_matches("notreddit.com", env.REDDIT_COOKIE_DOMAIN) |
| 188 | |
| 189 | def test_windows_app_bound_store_is_reported_as_unsupported(self, monkeypatch): |
| 190 | monkeypatch.setattr(env.os, "name", "nt") |
| 191 | assert env.read_reddit_session_cookie({}, "chrome") == (None, "unsupported-encryption") |
| 192 | |
| 193 | |
| 194 | class TestSetup: |
| 195 | def test_yes_scans_chrome_first_records_the_browser_and_never_prints_the_cookie(self, spy, tmp_path): |
| 196 | env_path = tmp_path / ".env" |
| 197 | spy.logged_in = {"firefox"} |
| 198 | result = setup_wizard.run_reddit_session_setup({}, env_path, consent=True) |
| 199 | assert result["status"] == "found" and result["browser"] == "firefox" |
| 200 | assert [c["browser"] for c in result["checked"]][0] == "chrome" |
| 201 | text = env_path.read_text(encoding="utf-8") |
| 202 | assert "REDDIT_BROWSER_CONSENT=true" in text |
| 203 | assert "REDDIT_FROM_BROWSER=firefox" in text |
| 204 | assert "REDDIT_SESSION_OFFERED=true" in text |
| 205 | assert COOKIE not in text and COOKIE not in json.dumps(result) |
| 206 | |
| 207 | def test_no_records_the_refusal_and_the_offer(self, spy, tmp_path): |
| 208 | env_path = tmp_path / ".env" |
| 209 | result = setup_wizard.run_reddit_session_setup({}, env_path, consent=False) |
| 210 | assert result["status"] == "declined" and spy.calls == [] |
| 211 | text = env_path.read_text(encoding="utf-8") |
| 212 | assert "REDDIT_BROWSER_CONSENT=false" in text and "REDDIT_SESSION_OFFERED=true" in text |
| 213 | |
| 214 | def test_global_refusal_vetoes_the_setup_read(self, spy, tmp_path): |
| 215 | result = setup_wizard.run_reddit_session_setup({"FROM_BROWSER": "off"}, tmp_path / ".env", consent=True) |
| 216 | assert result["status"] == "vetoed" and spy.calls == [] |
| 217 | |
| 218 | def test_reddit_yes_after_skipping_x_still_reads(self, spy, tmp_path): |
| 219 | setup_wizard.run_reddit_session_setup({"BROWSER_CONSENT": "false"}, tmp_path / ".env", consent=True) |
| 220 | assert spy.calls |
| 221 | |
| 222 | def test_grok_bot_setup_reads_and_writes_nothing(self, spy, tmp_path): |
| 223 | env_path = tmp_path / ".env" |
| 224 | result = setup_wizard.run_reddit_session_setup({"LAST30DAYS_HOST": "grok-bot"}, env_path, consent=True) |
| 225 | assert result["status"] == "unavailable" and spy.calls == [] and not env_path.exists() |
| 226 | |
| 227 | def test_cli_setup_flag_is_a_passthrough(self): |
| 228 | assert "--reddit-session" in cli.SETUP_PASSTHROUGH_FLAGS |
| 229 | assert "--no-reddit-session" in cli.SETUP_PASSTHROUGH_FLAGS |
| 230 | |
| 231 | |
| 232 | class TestDoctorRow: |
| 233 | def test_session_row_shows_consent_without_reading_a_cookie(self, spy): |
| 234 | config = {env.REDDIT_CONSENT_VAR: "true", env.REDDIT_FROM_BROWSER_VAR: "chrome"} |
| 235 | report = doctor.build_report(config) |
| 236 | row = next(r for r in report["sources"]["reddit"]["paths"] if r["path"] == "session") |
| 237 | assert row["consent"] == "granted" and row["browser"] == "chrome" and row["would_run"] is True |
| 238 | assert spy.calls == [] |
| 239 | assert "consent granted (chrome)" in doctor.render_text(report) |
| 240 | |
| 241 | def test_unset_consent_row_says_how_to_opt_in(self, spy): |
| 242 | row = next(r for r in doctor.build_report({})["sources"]["reddit"]["paths"] if r["path"] == "session") |
| 243 | assert row["consent"] == "unset" and "setup --reddit-session" in row["action"] |
| 244 | |
| 245 | |
| 246 | def _cli(argv, config, environ=None): |
| 247 | out, err = io.StringIO(), io.StringIO() |
| 248 | with mock.patch.object(cli.env, "get_config", return_value=dict(config)), \ |
| 249 | mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1", **(environ or {})}), \ |
| 250 | mock.patch.object(sys, "argv", ["last30days.py", *argv]), \ |
| 251 | mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("must not run")), \ |
| 252 | redirect_stdout(out), redirect_stderr(err): |
| 253 | rc = cli.main() |
| 254 | return rc, out.getvalue(), err.getvalue() |
| 255 | |
| 256 | |
| 257 | class TestCli: |
| 258 | SESSION_ON = {"_BROWSER_COOKIE_MODE": "read", env.REDDIT_CONSENT_VAR: "true", env.REDDIT_FROM_BROWSER_VAR: "chrome"} |
| 259 | |
| 260 | def test_ae10_record_fixtures_refuses_while_the_session_is_on(self, tmp_path): |
| 261 | rc, _out, err = _cli(["Ghostty terminal", "--record-fixtures", str(tmp_path / "rec")], self.SESSION_ON) |
| 262 | assert rc == 2 |
| 263 | assert "--record-fixtures refuses" in err and "--no-browser-cookies" in err |
| 264 | |
| 265 | def test_hosted_backend_prints_a_notice_and_reads_no_cookie(self, spy): |
| 266 | with mock.patch.object(cli.env, "read_secret_env", return_value="hosted-test-key"), \ |
| 267 | mock.patch("lib.hosted.run_hosted", return_value=0): |
| 268 | rc, _out, err = _cli(["Ghostty terminal"], self.SESSION_ON, |
| 269 | environ={"LAST30DAYS_API_BASE": "https://hosted.example.test"}) |
| 270 | assert rc == 0 |
| 271 | assert "Reddit session is not used with the hosted backend" in err |
| 272 | assert spy.calls == [] |
| 273 |