| 1 | """Security regression tests for PR10: Reddit session privacy & envelope TOCTOU. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-126: Non-public subreddit_type values (gold_only, gold_restricted, |
| 5 | employees_only, user, missing/unknown) are dropped unless explicitly named |
| 6 | and never enter session.public_subs. |
| 7 | - HIGH-127: Per-entity named subreddit allowlists are isolated via ContextVar |
| 8 | across comparison entities sharing the process-wide singleton Session. |
| 9 | - HIGH-134: Credential-directory existence oracle, symlink/FIFO/inode TOCTOU |
| 10 | races, and unhandled stdin/NUL-byte exceptions in reddit_envelope._read_bytes |
| 11 | (shared by shortform_envelope). |
| 12 | """ |
| 13 | |
| 14 | from __future__ import annotations |
| 15 | |
| 16 | import concurrent.futures |
| 17 | import contextlib |
| 18 | import io |
| 19 | import json |
| 20 | import os |
| 21 | import sys |
| 22 | import threading |
| 23 | from contextlib import redirect_stderr, redirect_stdout |
| 24 | from pathlib import Path |
| 25 | from unittest import mock |
| 26 | |
| 27 | import pytest |
| 28 | |
| 29 | import last30days as cli |
| 30 | from lib import ( |
| 31 | dates, |
| 32 | env, |
| 33 | http, |
| 34 | pipeline, |
| 35 | reddit_arctic, |
| 36 | reddit_envelope, |
| 37 | reddit_hydrate, |
| 38 | reddit_keyless, |
| 39 | reddit_search, |
| 40 | reddit_session, |
| 41 | reddit_shreddit, |
| 42 | shortform_envelope, |
| 43 | ) |
| 44 | from lib.reddit_refs import canonical_thread |
| 45 | |
| 46 | FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" |
| 47 | DUMMY_COOKIE = "dummy-pr10-session-cookie-0123456789" |
| 48 | TOPIC = "Ghostty terminal" |
| 49 | FROM, TO = "2026-10-16", "2026-11-15" |
| 50 | IN_WINDOW_UTC = 1794355200 # 2026-11-11T00:00:00Z |
| 51 | |
| 52 | THREAD_FIXTURE = json.loads((FIXTURES / "reddit_session_thread.json").read_text(encoding="utf-8")) |
| 53 | POSTS_FIXTURE = (FIXTURES / "reddit_session_posts.html").read_text(encoding="utf-8") |
| 54 | NO_COMMENTS_FIXTURE = (FIXTURES / "reddit_session_comments_no_results.html").read_text(encoding="utf-8") |
| 55 | |
| 56 | |
| 57 | def _thread_json(post_id: str, *, clear_comments: bool = False, **fields) -> str: |
| 58 | data = json.loads(json.dumps(THREAD_FIXTURE)) |
| 59 | post = data[0]["data"]["children"][0]["data"] |
| 60 | sub = fields.get("subreddit", post["subreddit"]) |
| 61 | post.update({ |
| 62 | "id": post_id, |
| 63 | "created_utc": IN_WINDOW_UTC, |
| 64 | "permalink": f"/r/{sub}/comments/{post_id}/t/", |
| 65 | }) |
| 66 | for key, value in fields.items(): |
| 67 | if value is _OMIT: |
| 68 | post.pop(key, None) |
| 69 | else: |
| 70 | post[key] = value |
| 71 | if clear_comments: |
| 72 | data[1]["data"]["children"] = [] |
| 73 | return json.dumps(data) |
| 74 | |
| 75 | |
| 76 | _OMIT = object() |
| 77 | |
| 78 | |
| 79 | def _ref(post_id: str, sub: str = "Ghostty", provenance: str = "session"): |
| 80 | ref = canonical_thread(f"https://www.reddit.com/r/{sub}/comments/{post_id}/") |
| 81 | ref.provenance.add(provenance) |
| 82 | ref.title = "Ghostty terminal discussion" |
| 83 | ref.date = "2026-11-11" |
| 84 | return ref |
| 85 | |
| 86 | |
| 87 | def _session(**kwargs) -> reddit_session.Session: |
| 88 | return reddit_session.Session(DUMMY_COOKIE, browser="chrome", **kwargs) |
| 89 | |
| 90 | |
| 91 | def _envelope_payload(threads, topic: str = TOPIC) -> dict: |
| 92 | return {"schema": reddit_envelope.SCHEMA, "topic": topic, "threads": threads} |
| 93 | |
| 94 | |
| 95 | def _write_json(path: Path, payload) -> Path: |
| 96 | path.write_text( |
| 97 | payload if isinstance(payload, str) else json.dumps(payload), |
| 98 | encoding="utf-8", |
| 99 | ) |
| 100 | return path |
| 101 | |
| 102 | |
| 103 | @pytest.fixture |
| 104 | def no_archive(monkeypatch): |
| 105 | monkeypatch.setattr(reddit_arctic, "fetch_posts_by_ids", lambda ids, **_k: ({}, "down")) |
| 106 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 107 | monkeypatch.setattr(reddit_shreddit, "fetch_comments", lambda *_a, **_k: {}) |
| 108 | |
| 109 | |
| 110 | # --------------------------------------------------------------------------- |
| 111 | # HIGH-126: Non-public subreddit_type allowlist & public_subs isolation |
| 112 | # --------------------------------------------------------------------------- |
| 113 | |
| 114 | |
| 115 | class TestNonPublicSubredditTypes: |
| 116 | @pytest.mark.parametrize( |
| 117 | "sub_type", |
| 118 | [ |
| 119 | "private", |
| 120 | "gold_only", |
| 121 | "gold_restricted", |
| 122 | "employees_only", |
| 123 | "user", |
| 124 | "", |
| 125 | None, |
| 126 | _OMIT, |
| 127 | "future_restricted_type", |
| 128 | ], |
| 129 | ) |
| 130 | def test_non_public_subreddit_types_dropped_and_never_enter_public_subs( |
| 131 | self, monkeypatch, no_archive, sub_type, |
| 132 | ): |
| 133 | raw = json.loads(_thread_json("1np0001", subreddit="lounge", subreddit_type=sub_type)) |
| 134 | session = _session() |
| 135 | assert reddit_session.thread_post(raw, session) is reddit_session.DROP |
| 136 | assert "lounge" not in session.public_subs |
| 137 | |
| 138 | # End-to-end hydration: neither the hydrated thread nor a second |
| 139 | # unhydrated search-hit copy from the same non-public sub may survive. |
| 140 | def fake_get(url, _cookie, **_k): |
| 141 | if "1np0001.json" in url: |
| 142 | return 200, json.dumps(raw), False |
| 143 | return 404, "", False |
| 144 | |
| 145 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 146 | found = reddit_session.Discovery() |
| 147 | ref1 = _ref("1np0001", "lounge") |
| 148 | ref2 = _ref("1np0002", "lounge") |
| 149 | found.hits["1np0002"] = { |
| 150 | "title": "Ghostty terminal in lounge", |
| 151 | "subreddit": "lounge", |
| 152 | "url": ref2.url, |
| 153 | "metadata": {"post_id": "1np0002"}, |
| 154 | } |
| 155 | hydrated = reddit_hydrate.hydrate( |
| 156 | [ref1, ref2], |
| 157 | topic=TOPIC, |
| 158 | from_date=FROM, |
| 159 | to_date=TO, |
| 160 | comments=False, |
| 161 | session_hydrator=reddit_session.hydrator(session, found), |
| 162 | now=1.9e9, |
| 163 | ) |
| 164 | assert hydrated.items == [] |
| 165 | assert "lounge" not in session.public_subs |
| 166 | |
| 167 | @pytest.mark.parametrize("sub_type", ["public", "restricted", "archived", " Restricted "]) |
| 168 | def test_public_subreddit_types_admitted_and_recorded_in_public_subs( |
| 169 | self, monkeypatch, no_archive, sub_type, |
| 170 | ): |
| 171 | raw = json.loads(_thread_json("1pb0001", subreddit="Ghostty", subreddit_type=sub_type)) |
| 172 | session = _session(cap=1) |
| 173 | post = reddit_session.thread_post(raw, session) |
| 174 | assert post is not None and post is not reddit_session.DROP |
| 175 | assert "ghostty" in session.public_subs |
| 176 | |
| 177 | # Hydrating one public thread allows an unhydrated search-hit copy from |
| 178 | # that same confirmed-public subreddit when cap runs out. |
| 179 | session2 = _session(cap=1) |
| 180 | monkeypatch.setattr( |
| 181 | http, |
| 182 | "reddit_session_get", |
| 183 | lambda url, _c, **_k: (200, json.dumps(raw), False) if "1pb0001.json" in url else (404, "", False), |
| 184 | ) |
| 185 | found = reddit_session.Discovery() |
| 186 | ref1 = _ref("1pb0001", "Ghostty") |
| 187 | ref2 = _ref("1pb0002", "Ghostty") |
| 188 | found.hits["1pb0002"] = { |
| 189 | "title": "Ghostty terminal second hit", |
| 190 | "subreddit": "Ghostty", |
| 191 | "url": ref2.url, |
| 192 | "date": "2026-11-11", |
| 193 | "metadata": {"post_id": "1pb0002"}, |
| 194 | } |
| 195 | hydrated = reddit_hydrate.hydrate( |
| 196 | [ref1, ref2], |
| 197 | topic=TOPIC, |
| 198 | from_date=FROM, |
| 199 | to_date=TO, |
| 200 | comments=False, |
| 201 | session_hydrator=reddit_session.hydrator(session2, found), |
| 202 | now=1.9e9, |
| 203 | ) |
| 204 | assert [i["metadata"]["post_id"] for i in hydrated.items] == ["1pb0001", "1pb0002"] |
| 205 | |
| 206 | def test_explicitly_named_gold_only_sub_admitted_without_polluting_public_subs(self): |
| 207 | raw = json.loads(_thread_json("1gld001", subreddit="lounge", subreddit_type="gold_only")) |
| 208 | session = _session(named=["lounge"]) |
| 209 | post = reddit_session.thread_post(raw, session) |
| 210 | assert post is not None and post is not reddit_session.DROP |
| 211 | assert post["metadata"]["post_id"] == "1gld001" |
| 212 | # Named non-public subreddits must never be promoted into public_subs. |
| 213 | assert "lounge" not in session.public_subs |
| 214 | |
| 215 | def test_explicitly_named_quarantined_public_sub_never_enters_public_subs(self): |
| 216 | raw = json.loads(_thread_json("1qr0001", subreddit="qsub", subreddit_type="public", quarantine=True)) |
| 217 | session = _session(named=["qsub"]) |
| 218 | post = reddit_session.thread_post(raw, session) |
| 219 | assert post is not None and post is not reddit_session.DROP |
| 220 | assert "qsub" not in session.public_subs |
| 221 | |
| 222 | def test_empty_subreddit_name_never_enters_public_subs(self): |
| 223 | raw = json.loads(_thread_json("1emp001", subreddit="", subreddit_type="public")) |
| 224 | session = _session() |
| 225 | post = reddit_session.thread_post(raw, session) |
| 226 | assert post is not None and post is not reddit_session.DROP |
| 227 | assert "" not in session.public_subs |
| 228 | |
| 229 | |
| 230 | # --------------------------------------------------------------------------- |
| 231 | # HIGH-127: Per-entity named subreddit isolation across comparison runs |
| 232 | # --------------------------------------------------------------------------- |
| 233 | |
| 234 | |
| 235 | class TestPerEntityNamedSubreddits: |
| 236 | def _config(self, dedicated=None) -> dict: |
| 237 | cfg = { |
| 238 | "_BROWSER_COOKIE_MODE": "read", |
| 239 | env.REDDIT_CONSENT_VAR: "true", |
| 240 | env.REDDIT_FROM_BROWSER_VAR: "chrome", |
| 241 | "_comparison_entity_count": 2, |
| 242 | } |
| 243 | if dedicated: |
| 244 | cfg["_dedicated_subreddits"] = list(dedicated) |
| 245 | return cfg |
| 246 | |
| 247 | def test_lane_named_override_isolates_singleton_session_across_entities(self, monkeypatch, no_archive): |
| 248 | cfg1 = self._config(dedicated=["DedA"]) |
| 249 | cfg2 = self._config() |
| 250 | s1 = reddit_session.session_for(cfg1, reader=lambda *_a: (DUMMY_COOKIE, "ok"), topic="updates in r/PrivateA") |
| 251 | s2 = reddit_session.session_for(cfg2, reader=lambda *_a: (DUMMY_COOKIE, "ok"), topic="updates in r/PrivateB") |
| 252 | assert s1 is not None and s1 is s2 |
| 253 | assert s1.named == frozenset({"privatea", "deda"}) |
| 254 | |
| 255 | threads = { |
| 256 | "1pa0001": _thread_json("1pa0001", subreddit="PrivateA", subreddit_type="private"), |
| 257 | "1da0001": _thread_json("1da0001", subreddit="DedA", subreddit_type="private"), |
| 258 | "1pb0001": _thread_json("1pb0001", subreddit="PrivateB", subreddit_type="private"), |
| 259 | } |
| 260 | |
| 261 | def fake_get(url, _cookie, **_k): |
| 262 | pid = url.split("/comments/", 1)[1].split(".json", 1)[0] |
| 263 | return 200, threads[pid], False |
| 264 | |
| 265 | monkeypatch.setattr(http, "reddit_session_get", fake_get) |
| 266 | refs = [ |
| 267 | _ref("1pa0001", "PrivateA"), |
| 268 | _ref("1da0001", "DedA"), |
| 269 | _ref("1pb0001", "PrivateB"), |
| 270 | ] |
| 271 | |
| 272 | # Entity 2 explicitly names r/PrivateB: must admit PrivateB and block |
| 273 | # Entity 1's PrivateA and DedA. |
| 274 | named_e2 = reddit_session.named_subreddits("updates in r/PrivateB") |
| 275 | with reddit_session.lane(s2, "updates in r/PrivateB", named=named_e2): |
| 276 | out_e2 = reddit_hydrate.hydrate( |
| 277 | refs, topic=TOPIC, from_date=FROM, to_date=TO, comments=False, |
| 278 | session_hydrator=reddit_session.hydrator(s2), now=1.9e9, |
| 279 | ) |
| 280 | assert [i["metadata"]["post_id"] for i in out_e2.items] == ["1pb0001"] |
| 281 | |
| 282 | # Entity 3 names no subreddits (empty frozenset): must block ALL |
| 283 | # private subreddits instead of falling back to s1.named. |
| 284 | with reddit_session.lane(s2, "plain entity", named=frozenset()): |
| 285 | out_e3 = reddit_hydrate.hydrate( |
| 286 | refs, topic=TOPIC, from_date=FROM, to_date=TO, comments=False, |
| 287 | session_hydrator=reddit_session.hydrator(s2), now=1.9e9, |
| 288 | ) |
| 289 | assert out_e3.items == [] |
| 290 | |
| 291 | # Outside any lane(), session.named fallback stays intact. |
| 292 | out_fallback = reddit_hydrate.hydrate( |
| 293 | refs, topic=TOPIC, from_date=FROM, to_date=TO, comments=False, |
| 294 | session_hydrator=reddit_session.hydrator(s1), now=1.9e9, |
| 295 | ) |
| 296 | assert sorted(i["metadata"]["post_id"] for i in out_fallback.items) == ["1da0001", "1pa0001"] |
| 297 | |
| 298 | def test_concurrent_comparison_entities_do_not_leak_named_allowlists(self, monkeypatch): |
| 299 | session = _session(named=["PrivateA"], entity_count=3) |
| 300 | post_a = json.loads(_thread_json("1ca0001", subreddit="PrivateA", subreddit_type="private")) |
| 301 | post_b = json.loads(_thread_json("1cb0001", subreddit="PrivateB", subreddit_type="private")) |
| 302 | barrier = threading.Barrier(3) |
| 303 | |
| 304 | def worker(entity: str, named: frozenset[str]): |
| 305 | with reddit_session.lane(session, entity, named=named): |
| 306 | barrier.wait(timeout=5) |
| 307 | admitted_a = reddit_session.thread_post(post_a, session) is not reddit_session.DROP |
| 308 | admitted_b = reddit_session.thread_post(post_b, session) is not reddit_session.DROP |
| 309 | return admitted_a, admitted_b |
| 310 | |
| 311 | with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool: |
| 312 | f1 = pool.submit(worker, "entity-a", frozenset({"privatea"})) |
| 313 | f2 = pool.submit(worker, "entity-b", frozenset({"privateb"})) |
| 314 | f3 = pool.submit(worker, "entity-c", frozenset()) |
| 315 | assert f1.result(timeout=5) == (True, False) |
| 316 | assert f2.result(timeout=5) == (False, True) |
| 317 | assert f3.result(timeout=5) == (False, False) |
| 318 | |
| 319 | def test_hydrator_created_inside_lane_preserves_named_without_context_copy(self, monkeypatch, no_archive): |
| 320 | session = _session(named=["PrivateA"]) |
| 321 | monkeypatch.setattr( |
| 322 | http, |
| 323 | "reddit_session_get", |
| 324 | lambda url, _c, **_k: ( |
| 325 | 200, |
| 326 | _thread_json( |
| 327 | "1pa0001" if "1pa0001" in url else "1pb0001", |
| 328 | subreddit="PrivateA" if "1pa0001" in url else "PrivateB", |
| 329 | subreddit_type="private", |
| 330 | ), |
| 331 | False, |
| 332 | ), |
| 333 | ) |
| 334 | with reddit_session.lane(session, "entity-b", named=frozenset({"privateb"})): |
| 335 | hyd = reddit_session.hydrator(session) |
| 336 | |
| 337 | # Invoke hydrator on a plain worker thread that did NOT copy contextvars. |
| 338 | with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: |
| 339 | result = pool.submit(hyd, [_ref("1pa0001", "PrivateA"), _ref("1pb0001", "PrivateB")]).result(timeout=5) |
| 340 | assert result["1pa0001"].get("_drop") is True |
| 341 | assert result["1pb0001"].get("_drop") is not True |
| 342 | assert result["1pb0001"]["subreddit"] == "PrivateB" |
| 343 | |
| 344 | def test_pipeline_passes_per_entity_named_subreddits_to_reddit_session_lane(self, monkeypatch, no_archive): |
| 345 | cfg1 = self._config(dedicated=["DedA"]) |
| 346 | cfg2 = self._config() |
| 347 | monkeypatch.setattr(env, "read_reddit_session_cookie", lambda *_a, **_k: (DUMMY_COOKIE, "ok")) |
| 348 | |
| 349 | # Make session discovery emit quarantined hits from PrivateA, DedA, PrivateB |
| 350 | # and thread JSON return private threads for all three. |
| 351 | def make_post_page(sub: str, pid: str) -> str: |
| 352 | # Include action_info.type="post" so reddit_search._post_units and |
| 353 | # reddit_session.post_flags parse quarantined=True during discover(). |
| 354 | ctx = json.dumps({ |
| 355 | "action_info": {"type": "post"}, |
| 356 | "post": {"id": f"t3_{pid}", "nsfw": False}, |
| 357 | "subreddit": {"name": sub, "nsfw": False, "quarantined": True}, |
| 358 | }).replace('"', """) |
| 359 | return ( |
| 360 | 'user-logged-in ' |
| 361 | f'<search-telemetry-tracker view-events="search/view/post" ' |
| 362 | f'data-faceplate-tracking-context="{ctx}"></search-telemetry-tracker>' |
| 363 | ) |
| 364 | |
| 365 | titles = { |
| 366 | "1pa0001": "Ghostty shader pipeline latency benchmarks on Linux", |
| 367 | "1da0001": "Ghostty window splits keybinding guide for macOS", |
| 368 | "1pb0001": "Ghostty font ligature rendering memory profile", |
| 369 | } |
| 370 | threads = { |
| 371 | "1pa0001": _thread_json( |
| 372 | "1pa0001", clear_comments=True, subreddit="PrivateA", subreddit_type="private", |
| 373 | title=titles["1pa0001"], |
| 374 | selftext="Ghostty PrivateA PrivateB Linux shader measurements.", |
| 375 | ), |
| 376 | "1da0001": _thread_json( |
| 377 | "1da0001", clear_comments=True, subreddit="DedA", subreddit_type="private", |
| 378 | title=titles["1da0001"], |
| 379 | selftext="Ghostty PrivateA PrivateB macOS keybinding setup.", |
| 380 | ), |
| 381 | "1pb0001": _thread_json( |
| 382 | "1pb0001", clear_comments=True, subreddit="PrivateB", subreddit_type="private", |
| 383 | title=titles["1pb0001"], |
| 384 | selftext="Ghostty PrivateA PrivateB font ligature profiling.", |
| 385 | ), |
| 386 | } |
| 387 | |
| 388 | def fake_session_get(url, _cookie, **_k): |
| 389 | if ".json" in url: |
| 390 | pid = url.split("/comments/", 1)[1].split(".json", 1)[0] |
| 391 | return 200, threads[pid], False |
| 392 | if "type=posts" in url: |
| 393 | return 200, ( |
| 394 | make_post_page("PrivateA", "1pa0001") |
| 395 | + make_post_page("DedA", "1da0001") |
| 396 | + make_post_page("PrivateB", "1pb0001") |
| 397 | ), False |
| 398 | return 200, NO_COMMENTS_FIXTURE, False |
| 399 | |
| 400 | def fake_parse_page(_body, _topic): |
| 401 | return [ |
| 402 | { |
| 403 | "title": titles[pid], |
| 404 | "url": f"https://www.reddit.com/r/{sub}/comments/{pid}/", |
| 405 | "subreddit": sub, |
| 406 | "date": "2026-11-11", |
| 407 | "metadata": {"post_id": pid}, |
| 408 | } |
| 409 | for pid, sub in (("1pa0001", "PrivateA"), ("1da0001", "DedA"), ("1pb0001", "PrivateB")) |
| 410 | ], None |
| 411 | |
| 412 | monkeypatch.setattr(http, "reddit_session_get", fake_session_get) |
| 413 | monkeypatch.setattr(reddit_search, "parse_page", fake_parse_page) |
| 414 | monkeypatch.setattr(reddit_search, "unrecognized_body", lambda _b: None) |
| 415 | monkeypatch.setattr(reddit_search, "next_cursor", lambda _b: None) |
| 416 | monkeypatch.setattr(reddit_search, "search", lambda *_a, **_k: []) |
| 417 | monkeypatch.setattr(reddit_keyless, "_enrich", lambda posts, *_a, **_k: posts) |
| 418 | monkeypatch.setattr( |
| 419 | reddit_keyless, |
| 420 | "_scored_listings_with_state", |
| 421 | lambda *_a, **_k: ([], reddit_keyless.reddit_health.EMPTY), |
| 422 | ) |
| 423 | |
| 424 | def _plan(topic: str) -> dict: |
| 425 | return { |
| 426 | "intent": "opinion", |
| 427 | "freshness_mode": "balanced_recent", |
| 428 | "cluster_mode": "story", |
| 429 | "subqueries": [ |
| 430 | {"label": "primary", "search_query": topic, "ranking_query": topic, "sources": ["reddit"]}, |
| 431 | ], |
| 432 | "source_weights": {"reddit": 1.0}, |
| 433 | } |
| 434 | |
| 435 | with redirect_stderr(io.StringIO()): |
| 436 | report1 = pipeline.run( |
| 437 | topic="Ghostty r/PrivateA", |
| 438 | config=cfg1, |
| 439 | depth="quick", |
| 440 | requested_sources=["reddit"], |
| 441 | mock=False, |
| 442 | external_plan=_plan("Ghostty"), |
| 443 | web_backend="none", |
| 444 | save_dir="", |
| 445 | as_of_date=TO, |
| 446 | ) |
| 447 | # Do NOT call reset_run_state(): mirrors comparison fanout in one process. |
| 448 | report2 = pipeline.run( |
| 449 | topic="Ghostty r/PrivateB", |
| 450 | config=cfg2, |
| 451 | depth="quick", |
| 452 | requested_sources=["reddit"], |
| 453 | mock=False, |
| 454 | external_plan=_plan("Ghostty"), |
| 455 | web_backend="none", |
| 456 | save_dir="", |
| 457 | as_of_date=TO, |
| 458 | ) |
| 459 | |
| 460 | subs1 = {item.container for item in report1.items_by_source.get("reddit") or []} |
| 461 | subs2 = {item.container for item in report2.items_by_source.get("reddit") or []} |
| 462 | assert subs1 == {"PrivateA", "DedA"} |
| 463 | assert subs2 == {"PrivateB"} |
| 464 | |
| 465 | |
| 466 | # --------------------------------------------------------------------------- |
| 467 | # HIGH-134: Credential-dir oracle, symlink/FIFO TOCTOU, stdin & NUL-byte errors |
| 468 | # --------------------------------------------------------------------------- |
| 469 | |
| 470 | |
| 471 | class TestEnvelopeReadSecurity: |
| 472 | def test_protected_directory_no_existence_or_type_oracle(self, tmp_path): |
| 473 | cfg = tmp_path / "cfg" |
| 474 | cfg.mkdir() |
| 475 | subdir = cfg / "subdir" |
| 476 | subdir.mkdir() |
| 477 | non_json = cfg / "credentials" |
| 478 | non_json.write_text("dummy-secret", encoding="utf-8") |
| 479 | json_file = _write_json(cfg / "secrets.json", _envelope_payload([{"id": "abc123"}])) |
| 480 | missing_json = cfg / "does_not_exist.json" |
| 481 | missing_plain = cfg / "does_not_exist" |
| 482 | dangling_link = tmp_path / "dangling.json" |
| 483 | dangling_link.symlink_to(missing_json) |
| 484 | outside = _write_json(tmp_path / "outside.json", _envelope_payload([{"id": "abc123"}])) |
| 485 | escape_link = cfg / "escape.json" |
| 486 | escape_link.symlink_to(outside) |
| 487 | |
| 488 | probes = [ |
| 489 | missing_json, |
| 490 | missing_plain, |
| 491 | subdir, |
| 492 | non_json, |
| 493 | json_file, |
| 494 | dangling_link, |
| 495 | escape_link, |
| 496 | ] |
| 497 | with mock.patch.object(reddit_envelope.env, "CONFIG_DIR", cfg), \ |
| 498 | mock.patch.object(reddit_envelope, "_stat", side_effect=AssertionError("_stat must not run for protected paths")): |
| 499 | reasons = [] |
| 500 | for probe in probes: |
| 501 | with pytest.raises(reddit_envelope.EnvelopeContractError) as exc_info: |
| 502 | reddit_envelope.read(probe, TOPIC) |
| 503 | msg = exc_info.value.message |
| 504 | assert "is inside a configuration or credential directory" in msg |
| 505 | # Strip the echoed path so we verify every probe returns the exact same error text. |
| 506 | reasons.append(msg.replace(str(probe), "<PATH>")) |
| 507 | assert len(set(reasons)) == 1 |
| 508 | |
| 509 | def test_symlink_toctou_swap_into_protected_dir_fails_closed(self, tmp_path): |
| 510 | cfg = tmp_path / "cfg" |
| 511 | cfg.mkdir() |
| 512 | secret = _write_json(cfg / "secret.json", _envelope_payload([{"id": "sec999"}])) |
| 513 | target = _write_json(tmp_path / "threads.json", _envelope_payload([{"id": "ok1111"}])) |
| 514 | real_lstat = os.lstat |
| 515 | |
| 516 | def stat_then_swap_to_symlink(path: Path): |
| 517 | info = real_lstat(path) |
| 518 | os.unlink(path) |
| 519 | os.symlink(secret, path) |
| 520 | return info |
| 521 | |
| 522 | with mock.patch.object(reddit_envelope.env, "CONFIG_DIR", cfg), \ |
| 523 | mock.patch.object(reddit_envelope, "_stat", side_effect=stat_then_swap_to_symlink), \ |
| 524 | pytest.raises(reddit_envelope.EnvelopeContractError) as exc_info: |
| 525 | reddit_envelope.read(target, TOPIC) |
| 526 | assert "cannot be read" in exc_info.value.message |
| 527 | |
| 528 | @pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="POSIX FIFOs only") |
| 529 | def test_fifo_direct_and_toctou_swap_do_not_hang(self, tmp_path): |
| 530 | fifo = tmp_path / "pipe.json" |
| 531 | os.mkfifo(fifo) |
| 532 | # Direct FIFO fails closed immediately without opening/hanging. |
| 533 | with pytest.raises(reddit_envelope.EnvelopeContractError, match="regular file"): |
| 534 | reddit_envelope.read(fifo, TOPIC) |
| 535 | |
| 536 | # TOCTOU swap from regular file to writerless FIFO after _stat() |
| 537 | # must NOT hang (O_NONBLOCK) and must reject via fstat S_ISREG. |
| 538 | target = _write_json(tmp_path / "race.json", _envelope_payload([{"id": "ok1111"}])) |
| 539 | real_lstat = os.lstat |
| 540 | |
| 541 | def stat_then_swap_to_fifo(path: Path): |
| 542 | info = real_lstat(path) |
| 543 | os.unlink(path) |
| 544 | os.mkfifo(path) |
| 545 | return info |
| 546 | |
| 547 | done = threading.Event() |
| 548 | errors: list[BaseException] = [] |
| 549 | |
| 550 | def run_read(): |
| 551 | try: |
| 552 | with mock.patch.object(reddit_envelope, "_stat", side_effect=stat_then_swap_to_fifo): |
| 553 | reddit_envelope.read(target, TOPIC) |
| 554 | except BaseException as exc: |
| 555 | errors.append(exc) |
| 556 | finally: |
| 557 | done.set() |
| 558 | |
| 559 | worker = threading.Thread(target=run_read, daemon=True) |
| 560 | worker.start() |
| 561 | assert done.wait(timeout=3.0), "FIFO TOCTOU hung in _read_bytes" |
| 562 | assert len(errors) == 1 and isinstance(errors[0], reddit_envelope.EnvelopeContractError) |
| 563 | assert "regular file" in errors[0].message |
| 564 | |
| 565 | def test_inode_swap_toctou_between_stat_and_open_fails_closed(self, tmp_path): |
| 566 | target = _write_json(tmp_path / "threads.json", _envelope_payload([{"id": "orig01"}])) |
| 567 | replacement = _write_json(tmp_path / "other.json", _envelope_payload([{"id": "swap02"}])) |
| 568 | real_lstat = os.lstat |
| 569 | |
| 570 | def stat_then_replace(path: Path): |
| 571 | info = real_lstat(path) |
| 572 | os.replace(replacement, path) |
| 573 | return info |
| 574 | |
| 575 | with mock.patch.object(reddit_envelope, "_stat", side_effect=stat_then_replace), \ |
| 576 | pytest.raises(reddit_envelope.EnvelopeContractError, match="changed while being read"): |
| 577 | reddit_envelope.read(target, TOPIC) |
| 578 | |
| 579 | @pytest.mark.skipif(not Path("/proc/self/fd").is_dir(), reason="Linux /proc/self/fd only") |
| 580 | def test_parent_directory_swap_into_protected_dir_caught_via_fd_path(self, tmp_path): |
| 581 | cfg = tmp_path / "cfg" |
| 582 | cfg.mkdir() |
| 583 | _write_json(cfg / "threads.json", _envelope_payload([{"id": "sec999"}])) |
| 584 | work = tmp_path / "work" |
| 585 | work.mkdir() |
| 586 | target = _write_json(work / "threads.json", _envelope_payload([{"id": "ok1111"}])) |
| 587 | real_lstat = os.lstat |
| 588 | real_realpath = os.path.realpath |
| 589 | |
| 590 | def realpath_then_swap_parent(p): |
| 591 | res = real_realpath(p) |
| 592 | if str(p) == str(target) and not work.is_symlink(): |
| 593 | backup = tmp_path / "work_backup" |
| 594 | os.rename(work, backup) |
| 595 | os.symlink(cfg, work) |
| 596 | return res |
| 597 | |
| 598 | with mock.patch.object(reddit_envelope.env, "CONFIG_DIR", cfg), \ |
| 599 | mock.patch.object(reddit_envelope.os.path, "realpath", side_effect=realpath_then_swap_parent), \ |
| 600 | mock.patch.object(reddit_envelope, "_stat", side_effect=real_lstat), \ |
| 601 | pytest.raises(reddit_envelope.EnvelopeContractError, match="credential directory"): |
| 602 | reddit_envelope.read(target, TOPIC) |
| 603 | |
| 604 | def test_legitimate_symlink_outside_protected_dirs_still_works(self, tmp_path): |
| 605 | target = _write_json(tmp_path / "real.json", _envelope_payload([{"id": "ok1111"}])) |
| 606 | link = tmp_path / "link.json" |
| 607 | link.symlink_to(target) |
| 608 | with redirect_stderr(io.StringIO()): |
| 609 | env_obj = reddit_envelope.read(link, TOPIC) |
| 610 | assert [r.post_id for r in env_obj.refs] == ["ok1111"] |
| 611 | |
| 612 | def test_nul_byte_path_raises_contract_error_and_cli_exits_2(self, tmp_path): |
| 613 | bad_path = str(tmp_path / "evil\x00.json") |
| 614 | with pytest.raises(reddit_envelope.EnvelopeContractError, match="cannot be read"): |
| 615 | reddit_envelope.read(bad_path, TOPIC) |
| 616 | |
| 617 | # CLI must map it to exit code 2 (not exit 1 with unhandled ValueError). |
| 618 | out, err = io.StringIO(), io.StringIO() |
| 619 | cfg_dir = tmp_path / "cfg" |
| 620 | cfg_dir.mkdir(exist_ok=True) |
| 621 | with contextlib.ExitStack() as stack: |
| 622 | stack.enter_context(mock.patch.object(cli.env, "get_config", return_value={})) |
| 623 | stack.enter_context(mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir)) |
| 624 | stack.enter_context(mock.patch.object(cli.env, "CONFIG_FILE", cfg_dir / ".env")) |
| 625 | stack.enter_context(mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock())) |
| 626 | stack.enter_context(mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"})) |
| 627 | stack.enter_context(mock.patch.object(sys, "argv", ["last30days.py", TOPIC, "--reddit-threads", bad_path])) |
| 628 | stack.enter_context(mock.patch.object(cli.pipeline, "diagnose", return_value={"available_sources": ["reddit"]})) |
| 629 | stack.enter_context(mock.patch.object(cli.pipeline, "run", side_effect=AssertionError("must not run"))) |
| 630 | stack.enter_context(redirect_stdout(out)) |
| 631 | stack.enter_context(redirect_stderr(err)) |
| 632 | rc = cli.main() |
| 633 | assert rc == 2 |
| 634 | assert "cannot be read" in err.getvalue() |
| 635 | |
| 636 | def test_stdin_errors_raise_contract_error(self): |
| 637 | # Missing .buffer (e.g., StringIO) |
| 638 | with mock.patch.object(sys, "stdin", io.StringIO("{}")), \ |
| 639 | pytest.raises(reddit_envelope.EnvelopeContractError, match="cannot be read"): |
| 640 | reddit_envelope.read(reddit_envelope.STDIN, TOPIC) |
| 641 | |
| 642 | # sys.stdin is None |
| 643 | with mock.patch.object(sys, "stdin", None), \ |
| 644 | pytest.raises(reddit_envelope.EnvelopeContractError, match="cannot be read"): |
| 645 | reddit_envelope.read(reddit_envelope.STDIN, TOPIC) |
| 646 | |
| 647 | # OSError during read |
| 648 | broken = mock.Mock() |
| 649 | broken.buffer.read.side_effect = BrokenPipeError("pipe closed") |
| 650 | with mock.patch.object(sys, "stdin", broken), \ |
| 651 | pytest.raises(reddit_envelope.EnvelopeContractError, match="cannot be read"): |
| 652 | reddit_envelope.read(reddit_envelope.STDIN, TOPIC) |
| 653 | |
| 654 | # Closed buffer raises ValueError |
| 655 | closed_buf = io.BytesIO(b"{}") |
| 656 | closed_buf.close() |
| 657 | with mock.patch.object(sys, "stdin", mock.Mock(buffer=closed_buf)), \ |
| 658 | pytest.raises(reddit_envelope.EnvelopeContractError, match="cannot be read"): |
| 659 | reddit_envelope.read(reddit_envelope.STDIN, TOPIC) |
| 660 | |
| 661 | # Oversized stdin |
| 662 | oversized = io.BytesIO(b" " * (reddit_envelope.MAX_BYTES + 1)) |
| 663 | with mock.patch.object(sys, "stdin", mock.Mock(buffer=oversized)), \ |
| 664 | pytest.raises(reddit_envelope.EnvelopeContractError, match="KiB limit"): |
| 665 | reddit_envelope.read(reddit_envelope.STDIN, TOPIC) |
| 666 | |
| 667 | def test_shortform_envelope_inherits_read_bytes_protections(self, tmp_path): |
| 668 | cfg = tmp_path / "cfg" |
| 669 | cfg.mkdir() |
| 670 | with mock.patch.object(reddit_envelope.env, "CONFIG_DIR", cfg), \ |
| 671 | pytest.raises(shortform_envelope.EnvelopeContractError, match="credential directory"): |
| 672 | shortform_envelope.read(cfg / "nonexistent.txt", TOPIC) |
| 673 | |
| 674 | with pytest.raises(shortform_envelope.EnvelopeContractError, match="cannot be read"): |
| 675 | shortform_envelope.read(str(tmp_path / "bad\x00.json"), TOPIC) |
| 676 | |
| 677 | with mock.patch.object(sys, "stdin", io.StringIO("{}")), \ |
| 678 | pytest.raises(shortform_envelope.EnvelopeContractError, match="cannot be read"): |
| 679 | shortform_envelope.read(shortform_envelope.STDIN, TOPIC) |
| 680 | |
| 681 | def test_macos_case_insensitive_protected_directory_rejection(self, tmp_path, monkeypatch): |
| 682 | home = tmp_path / "Users" / "alice" |
| 683 | aws = home / ".aws" |
| 684 | cfg = home / ".config" / "last30days" |
| 685 | sibling = home / ".aws-public" |
| 686 | aws.mkdir(parents=True) |
| 687 | cfg.mkdir(parents=True) |
| 688 | sibling.mkdir(parents=True) |
| 689 | |
| 690 | (aws / "credentials").write_text("dummy-secret", encoding="utf-8") |
| 691 | _write_json(aws / "secret.json", _envelope_payload([{"id": "sec111"}])) |
| 692 | _write_json(cfg / "cache.json", _envelope_payload([{"id": "cfg111"}])) |
| 693 | ok_file = _write_json(sibling / "threads.json", _envelope_payload([{"id": "ok1111"}])) |
| 694 | |
| 695 | case_link = tmp_path / "case_link.json" |
| 696 | case_link.symlink_to(home / ".AWS" / "secret.json") |
| 697 | |
| 698 | monkeypatch.setenv("HOME", str(home)) |
| 699 | monkeypatch.setattr(sys, "platform", "darwin") |
| 700 | monkeypatch.setattr(reddit_envelope.env, "CONFIG_DIR", cfg) |
| 701 | monkeypatch.setattr(reddit_envelope.env, "CONFIG_FILE", cfg / ".env") |
| 702 | |
| 703 | probes = [ |
| 704 | home / ".AWS" / "credentials", |
| 705 | home / ".AWS" / "nonexistent", |
| 706 | home / ".Config" / "Last30Days" / "cache.json", |
| 707 | tmp_path / "Users" / "ALICE" / ".CONFIG" / "LAST30DAYS" / "missing.json", |
| 708 | case_link, |
| 709 | ] |
| 710 | with mock.patch.object( |
| 711 | reddit_envelope, "_stat", side_effect=AssertionError("_stat must not run"), |
| 712 | ), mock.patch.object( |
| 713 | reddit_envelope.os, "open", side_effect=AssertionError("os.open must not run"), |
| 714 | ): |
| 715 | templates = [] |
| 716 | for probe in probes: |
| 717 | with pytest.raises(reddit_envelope.EnvelopeContractError) as exc_info: |
| 718 | reddit_envelope.read(probe, TOPIC) |
| 719 | msg = exc_info.value.message |
| 720 | assert "is inside a configuration or credential directory" in msg |
| 721 | templates.append(msg.replace(str(probe), "<PATH>")) |
| 722 | assert len(set(templates)) == 1 |
| 723 | |
| 724 | # Sibling directory sharing only a string prefix (.aws-public vs .aws) stays allowed. |
| 725 | benign_fcntl = mock.Mock( |
| 726 | F_GETPATH=50, |
| 727 | fcntl=mock.Mock(return_value=os.fsencode(str(ok_file)) + b"\x00" * 16), |
| 728 | ) |
| 729 | with mock.patch.object(reddit_envelope, "fcntl", benign_fcntl), redirect_stderr(io.StringIO()): |
| 730 | env_obj = reddit_envelope.read(ok_file, TOPIC) |
| 731 | assert [r.post_id for r in env_obj.refs] == ["ok1111"] |
| 732 | |
| 733 | def test_macos_fd_real_path_uses_f_getpath_and_blocks_parent_swap(self, tmp_path, monkeypatch): |
| 734 | cfg = tmp_path / "cfg" |
| 735 | cfg.mkdir() |
| 736 | work = tmp_path / "work" |
| 737 | work.mkdir() |
| 738 | target = _write_json(work / "threads.json", _envelope_payload([{"id": "ok1111"}])) |
| 739 | |
| 740 | monkeypatch.setattr(sys, "platform", "darwin") |
| 741 | monkeypatch.setattr(reddit_envelope.env, "CONFIG_DIR", cfg) |
| 742 | monkeypatch.setattr(reddit_envelope.env, "CONFIG_FILE", cfg / ".env") |
| 743 | |
| 744 | seen_calls: list[tuple[int, int, int]] = [] |
| 745 | |
| 746 | def fake_fcntl_protected(fd, cmd, buf): |
| 747 | seen_calls.append((fd, cmd, len(buf))) |
| 748 | # Return uppercase case-variant under protected cfg to test both F_GETPATH |
| 749 | # and macOS case-insensitive matching together. |
| 750 | return os.fsencode(str(tmp_path / "CFG" / "threads.json")) + b"\x00" * 32 |
| 751 | |
| 752 | fake_fcntl_mod = mock.Mock(F_GETPATH=50, fcntl=mock.Mock(side_effect=fake_fcntl_protected)) |
| 753 | with mock.patch.object(reddit_envelope, "fcntl", fake_fcntl_mod), \ |
| 754 | pytest.raises(reddit_envelope.EnvelopeContractError, match="credential directory"): |
| 755 | reddit_envelope.read(target, TOPIC) |
| 756 | assert len(seen_calls) == 1 |
| 757 | assert seen_calls[0][1] == 50 |
| 758 | assert seen_calls[0][2] == reddit_envelope._DARWIN_MAXPATHLEN |
| 759 | |
| 760 | # When F_GETPATH returns the benign path, read succeeds normally. |
| 761 | benign_mod = mock.Mock( |
| 762 | F_GETPATH=50, |
| 763 | fcntl=mock.Mock(return_value=os.fsencode(str(target)) + b"\x00" * 16), |
| 764 | ) |
| 765 | with mock.patch.object(reddit_envelope, "fcntl", benign_mod), redirect_stderr(io.StringIO()): |
| 766 | env_obj = reddit_envelope.read(target, TOPIC) |
| 767 | assert [r.post_id for r in env_obj.refs] == ["ok1111"] |
| 768 | |
| 769 | # When F_GETPATH fails with OSError, _fd_real_path returns None and |
| 770 | # _read_bytes fails closed rather than reading an unverified descriptor. |
| 771 | err_mod = mock.Mock(F_GETPATH=50, fcntl=mock.Mock(side_effect=OSError("ENOTSUP"))) |
| 772 | with mock.patch.object(reddit_envelope, "fcntl", err_mod): |
| 773 | assert reddit_envelope._fd_real_path(99999) is None |
| 774 | with pytest.raises(reddit_envelope.EnvelopeContractError, match="could not be verified safely"): |
| 775 | reddit_envelope.read(target, TOPIC) |
| 776 | |
| 777 | def test_linux_proc_fd_unavailable_fails_closed(self, tmp_path, monkeypatch): |
| 778 | target = _write_json(tmp_path / "threads.json", _envelope_payload([{"id": "ok1111"}])) |
| 779 | monkeypatch.setattr(sys, "platform", "linux") |
| 780 | with mock.patch.object(reddit_envelope.os, "readlink", side_effect=FileNotFoundError("/proc unavailable")), \ |
| 781 | pytest.raises(reddit_envelope.EnvelopeContractError, match="could not be verified safely"): |
| 782 | reddit_envelope.read(target, TOPIC) |
| 783 | |
| 784 | def test_win32_fd_real_path_strips_extended_prefix_and_fails_closed(self, tmp_path, monkeypatch): |
| 785 | import ctypes |
| 786 | import types |
| 787 | |
| 788 | cfg = tmp_path / "cfg" |
| 789 | cfg.mkdir() |
| 790 | target = _write_json(tmp_path / "threads.json", _envelope_payload([{"id": "ok1111"}])) |
| 791 | monkeypatch.setattr(sys, "platform", "win32") |
| 792 | monkeypatch.setattr(reddit_envelope.env, "CONFIG_DIR", cfg) |
| 793 | monkeypatch.setattr(reddit_envelope.env, "CONFIG_FILE", cfg / ".env") |
| 794 | |
| 795 | def _make_fake_kernel32(returned_path: str): |
| 796 | def fake_get_path(_handle, buf, size, _flags): |
| 797 | if not returned_path: |
| 798 | return 0 |
| 799 | if buf is None or size == 0: |
| 800 | return len(returned_path) + 1 |
| 801 | buf.value = returned_path |
| 802 | return len(returned_path) |
| 803 | |
| 804 | return types.SimpleNamespace( |
| 805 | kernel32=types.SimpleNamespace(GetFinalPathNameByHandleW=fake_get_path), |
| 806 | ) |
| 807 | |
| 808 | fake_msvcrt = types.SimpleNamespace(get_osfhandle=lambda fd: fd) |
| 809 | monkeypatch.setitem(sys.modules, "msvcrt", fake_msvcrt) |
| 810 | |
| 811 | # Extended-length \\?\ path inside protected dir is stripped and blocked. |
| 812 | with mock.patch.object( |
| 813 | ctypes, "windll", _make_fake_kernel32(r"\\?\\"[:-1] + str(cfg / "threads.json")), create=True, |
| 814 | ): |
| 815 | with pytest.raises(reddit_envelope.EnvelopeContractError, match="credential directory"): |
| 816 | reddit_envelope.read(target, TOPIC) |
| 817 | |
| 818 | # Benign extended-length \\?\ path succeeds. |
| 819 | with mock.patch.object( |
| 820 | ctypes, "windll", _make_fake_kernel32(r"\\?\\"[:-1] + str(target)), create=True, |
| 821 | ), redirect_stderr(io.StringIO()): |
| 822 | env_obj = reddit_envelope.read(target, TOPIC) |
| 823 | assert [r.post_id for r in env_obj.refs] == ["ok1111"] |
| 824 | |
| 825 | # Handle lookup failure (return 0) fails closed. |
| 826 | with mock.patch.object(ctypes, "windll", _make_fake_kernel32(""), create=True), \ |
| 827 | pytest.raises(reddit_envelope.EnvelopeContractError, match="could not be verified safely"): |
| 828 | reddit_envelope.read(target, TOPIC) |
| 829 | |
| 830 | |
| 831 | # --------------------------------------------------------------------------- |
| 832 | # Greptile follow-ups: auto-discovered peer allowlist & archive matched_comment |
| 833 | # --------------------------------------------------------------------------- |
| 834 | |
| 835 | |
| 836 | class TestAutoDiscoveredPeerAndArchiveMatchedComment: |
| 837 | def test_auto_discovered_peer_cannot_grant_named_subreddit_access(self, tmp_path, monkeypatch, no_archive): |
| 838 | """An Exa/SERP-discovered peer containing r/<sub_name> must receive an |
| 839 | empty named allowlist so it cannot expose private/quarantined threads.""" |
| 840 | from lib import competitors as competitors_mod, fanout, resolve as resolve_mod, schema |
| 841 | |
| 842 | captured_configs: dict[str, dict] = {} |
| 843 | cfg_dir = tmp_path / "cfg" |
| 844 | cfg_dir.mkdir() |
| 845 | |
| 846 | def fake_report(label: str) -> schema.Report: |
| 847 | return schema.Report( |
| 848 | topic=label, |
| 849 | range_from=FROM, |
| 850 | range_to=TO, |
| 851 | generated_at="2026-11-15T00:00:00+00:00", |
| 852 | provider_runtime=schema.ProviderRuntime( |
| 853 | reasoning_provider="local", planner_model="d", rerank_model="l", |
| 854 | ), |
| 855 | query_plan=schema.QueryPlan( |
| 856 | intent="general", freshness_mode="balanced_recent", cluster_mode="story", |
| 857 | raw_topic=label, subqueries=[], source_weights={}, |
| 858 | ), |
| 859 | clusters=[], |
| 860 | ranked_candidates=[], |
| 861 | items_by_source={}, |
| 862 | errors_by_source={}, |
| 863 | ) |
| 864 | |
| 865 | def fake_run(**kwargs): |
| 866 | captured_configs[kwargs["topic"]] = dict(kwargs["config"]) |
| 867 | return fake_report(kwargs["topic"]) |
| 868 | |
| 869 | # Drive CLI --competitors 1 where Exa returns an untrusted title containing r/secret_sub. |
| 870 | out, err = io.StringIO(), io.StringIO() |
| 871 | with contextlib.ExitStack() as stack: |
| 872 | stack.enter_context(mock.patch.object(cli.env, "get_config", return_value={})) |
| 873 | stack.enter_context(mock.patch.object(cli.env, "CONFIG_DIR", cfg_dir)) |
| 874 | stack.enter_context(mock.patch.object(cli.env, "CONFIG_FILE", cfg_dir / ".env")) |
| 875 | stack.enter_context(mock.patch.object(cli.ui, "ProgressDisplay", return_value=mock.Mock())) |
| 876 | stack.enter_context(mock.patch.dict(os.environ, {"LAST30DAYS_SKIP_PREFLIGHT": "1"})) |
| 877 | stack.enter_context(mock.patch.object( |
| 878 | sys, "argv", ["last30days.py", "MainApp r/user_private", "--competitors", "1", "--emit", "compact"], |
| 879 | )) |
| 880 | stack.enter_context(mock.patch.object(cli.pipeline, "diagnose", return_value={ |
| 881 | "available_sources": ["reddit"], "x_pending_browser_auth": False, |
| 882 | "native_search": False, "bird_installed": False, "bird_authenticated": False, |
| 883 | "bird_username": None, "native_web_backend": None, "safe": False, |
| 884 | })) |
| 885 | stack.enter_context(mock.patch.object(cli.pipeline, "run", side_effect=fake_run)) |
| 886 | stack.enter_context(mock.patch.object( |
| 887 | competitors_mod, "discover_competitors", return_value=["Acme r/secret_sub"], |
| 888 | )) |
| 889 | stack.enter_context(mock.patch.object(resolve_mod, "_has_backend", return_value=True)) |
| 890 | stack.enter_context(mock.patch.object(resolve_mod, "auto_resolve", return_value={})) |
| 891 | stack.enter_context(mock.patch.object( |
| 892 | fanout, "run_competitor_fanout", |
| 893 | side_effect=lambda *, main_topic, main_runner, competitors, competitor_runner: [ |
| 894 | (main_topic, main_runner()), |
| 895 | *[(c, competitor_runner(c)) for c in competitors], |
| 896 | ], |
| 897 | )) |
| 898 | stack.enter_context(mock.patch.object(cli, "_render_save_and_print", return_value=0)) |
| 899 | stack.enter_context(redirect_stdout(out)) |
| 900 | stack.enter_context(redirect_stderr(err)) |
| 901 | rc = cli.main() |
| 902 | |
| 903 | assert rc == 0, err.getvalue() |
| 904 | assert "MainApp r/user_private" in captured_configs |
| 905 | assert "Acme r/secret_sub" in captured_configs |
| 906 | assert "_reddit_named_subreddits" not in captured_configs["MainApp r/user_private"] |
| 907 | assert captured_configs["Acme r/secret_sub"]["_reddit_named_subreddits"] == frozenset() |
| 908 | |
| 909 | # Verify pipeline + session_for enforce the empty allowlist for that peer |
| 910 | # even when the peer runs first and its topic contains r/secret_sub. |
| 911 | reddit_session.reset_run_state() |
| 912 | peer_cfg = { |
| 913 | "_BROWSER_COOKIE_MODE": "read", |
| 914 | env.REDDIT_CONSENT_VAR: "true", |
| 915 | env.REDDIT_FROM_BROWSER_VAR: "chrome", |
| 916 | "_reddit_named_subreddits": frozenset(), |
| 917 | } |
| 918 | monkeypatch.setattr(env, "read_reddit_session_cookie", lambda *_a, **_k: (DUMMY_COOKIE, "ok")) |
| 919 | secret_thread = _thread_json( |
| 920 | "1sec001", clear_comments=True, subreddit="secret_sub", subreddit_type="private", |
| 921 | title="Acme secret_sub internal roadmap details", |
| 922 | selftext="Acme r/secret_sub roadmap", |
| 923 | ) |
| 924 | monkeypatch.setattr( |
| 925 | http, |
| 926 | "reddit_session_get", |
| 927 | lambda url, _c, **_k: ( |
| 928 | (200, secret_thread, False) if ".json" in url |
| 929 | else (200, "user-logged-in", False) if "type=posts" in url |
| 930 | else (200, NO_COMMENTS_FIXTURE, False) |
| 931 | ), |
| 932 | ) |
| 933 | monkeypatch.setattr( |
| 934 | reddit_search, "parse_page", |
| 935 | lambda _b, _t: ([{ |
| 936 | "title": "Acme secret_sub internal roadmap details", |
| 937 | "url": "https://www.reddit.com/r/secret_sub/comments/1sec001/", |
| 938 | "subreddit": "secret_sub", |
| 939 | "date": "2026-11-11", |
| 940 | "metadata": {"post_id": "1sec001"}, |
| 941 | }], None), |
| 942 | ) |
| 943 | monkeypatch.setattr(reddit_search, "unrecognized_body", lambda _b: None) |
| 944 | monkeypatch.setattr(reddit_search, "next_cursor", lambda _b: None) |
| 945 | monkeypatch.setattr(reddit_search, "search", lambda *_a, **_k: []) |
| 946 | monkeypatch.setattr(reddit_keyless, "_enrich", lambda posts, *_a, **_k: posts) |
| 947 | monkeypatch.setattr( |
| 948 | reddit_keyless, |
| 949 | "_scored_listings_with_state", |
| 950 | lambda *_a, **_k: ([], reddit_keyless.reddit_health.EMPTY), |
| 951 | ) |
| 952 | |
| 953 | plan = { |
| 954 | "intent": "opinion", "freshness_mode": "balanced_recent", "cluster_mode": "story", |
| 955 | "subqueries": [ |
| 956 | {"label": "primary", "search_query": "Acme", "ranking_query": "Acme", "sources": ["reddit"]}, |
| 957 | ], |
| 958 | "source_weights": {"reddit": 1.0}, |
| 959 | } |
| 960 | with redirect_stderr(io.StringIO()): |
| 961 | report = pipeline.run( |
| 962 | topic="Acme r/secret_sub", |
| 963 | config=peer_cfg, |
| 964 | depth="quick", |
| 965 | requested_sources=["reddit"], |
| 966 | mock=False, |
| 967 | external_plan=plan, |
| 968 | web_backend="none", |
| 969 | save_dir="", |
| 970 | as_of_date=TO, |
| 971 | ) |
| 972 | assert (report.items_by_source.get("reddit") or []) == [] |
| 973 | singleton = reddit_session.session_for(peer_cfg, topic="Acme r/secret_sub") |
| 974 | assert singleton is not None and singleton.named == frozenset() |
| 975 | |
| 976 | def test_unverified_archive_copy_omits_logged_in_matched_comment(self, monkeypatch): |
| 977 | """When session budget runs out before thread_post checks a thread and |
| 978 | Arctic Shift returns an archived copy, keep the archive copy but omit |
| 979 | logged-in matched_comment details unless visibility was confirmed or |
| 980 | the subreddit was explicitly named.""" |
| 981 | from lib.reddit_refs import MatchedComment |
| 982 | |
| 983 | def make_archive_post(pid: str, sub: str, created_utc: int = IN_WINDOW_UTC) -> dict: |
| 984 | return { |
| 985 | "id": "", |
| 986 | "title": f"Ghostty terminal thread in {sub}", |
| 987 | "url": f"https://www.reddit.com/r/{sub}/comments/{pid}/", |
| 988 | "score": 42, |
| 989 | "num_comments": 5, |
| 990 | "subreddit": sub, |
| 991 | "created_utc": created_utc, |
| 992 | "author": "op", |
| 993 | "selftext": "", |
| 994 | "date": dates.timestamp_to_date(created_utc), |
| 995 | "engagement": {"score": 42, "num_comments": 5, "upvote_ratio": 0.9}, |
| 996 | "metadata": {"post_id": pid}, |
| 997 | } |
| 998 | |
| 999 | archive_rows = { |
| 1000 | "1arc001": make_archive_post("1arc001", "FormerlyPublic"), |
| 1001 | "1arc002": make_archive_post("1arc002", "Ghostty"), |
| 1002 | "1arc003": make_archive_post("1arc003", "UserNamedSub"), |
| 1003 | "1arc004": make_archive_post("1arc004", "FormerlyPublic", created_utc=1789516800), # 60d old |
| 1004 | "1arc005": make_archive_post("1arc005", "ActualPrivateSub"), |
| 1005 | } |
| 1006 | monkeypatch.setattr( |
| 1007 | reddit_arctic, |
| 1008 | "fetch_posts_by_ids", |
| 1009 | lambda ids, **_k: ({pid: dict(archive_rows[pid]) for pid in ids if pid in archive_rows}, "ok"), |
| 1010 | ) |
| 1011 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 1012 | monkeypatch.setattr(reddit_shreddit, "fetch_comments", lambda *_a, **_k: {}) |
| 1013 | |
| 1014 | def make_ref(pid: str, sub: str) -> object: |
| 1015 | ref = _ref(pid, sub, provenance="session") |
| 1016 | ref.matched_comment = MatchedComment( |
| 1017 | comment_id=f"c_{pid}", |
| 1018 | created_utc=1794700800, # 2026-11-15 (fresh, in-window) |
| 1019 | permalink=f"https://www.reddit.com/r/{sub}/comments/{pid}/t/c_{pid}/", |
| 1020 | ) |
| 1021 | return ref |
| 1022 | |
| 1023 | # Cap=0 simulates budget exhausted before thread_post checked any ref. |
| 1024 | session = _session(cap=0) |
| 1025 | session.mark_public_sub("Ghostty") |
| 1026 | |
| 1027 | refs = [ |
| 1028 | make_ref("1arc001", "FormerlyPublic"), # unverified + unnamed -> omit matched_comment |
| 1029 | make_ref("1arc002", "Ghostty"), # confirmed public -> keep matched_comment |
| 1030 | make_ref("1arc003", "UserNamedSub"), # user-named -> keep matched_comment |
| 1031 | make_ref("1arc004", "FormerlyPublic"), # old archive + unverified comment -> out of window |
| 1032 | make_ref("1arc005", "Ghostty"), # spoofed ref sub vs Arctic ActualPrivateSub -> omit |
| 1033 | ] |
| 1034 | with reddit_session.lane(session, "Ghostty r/UserNamedSub", named=frozenset({"usernamedsub"})): |
| 1035 | hydrated = reddit_hydrate.hydrate( |
| 1036 | refs, |
| 1037 | topic=TOPIC, |
| 1038 | from_date=FROM, |
| 1039 | to_date=TO, |
| 1040 | comments=False, |
| 1041 | session_hydrator=reddit_session.hydrator(session), |
| 1042 | now=1.9e9, |
| 1043 | ) |
| 1044 | |
| 1045 | by_id = {item["metadata"]["post_id"]: item for item in hydrated.items} |
| 1046 | # 1arc001 archive copy survives, but logged-in matched_comment is omitted. |
| 1047 | assert "1arc001" in by_id |
| 1048 | assert "matched_comment" not in by_id["1arc001"] |
| 1049 | # 1arc004 (60 days old) must NOT be kept in window by an unverified logged-in comment. |
| 1050 | assert "1arc004" not in by_id |
| 1051 | # 1arc002 (confirmed public) and 1arc003 (user-named) keep matched_comment. |
| 1052 | assert by_id["1arc002"]["matched_comment"]["id"] == "c_1arc002" |
| 1053 | assert by_id["1arc003"]["matched_comment"]["id"] == "c_1arc003" |
| 1054 | # 1arc005 (ref claimed Ghostty, Arctic revealed ActualPrivateSub) omits matched_comment. |
| 1055 | assert "1arc005" in by_id |
| 1056 | assert "matched_comment" not in by_id["1arc005"] |
| 1057 | |
| 1058 | # Expired session before hydrator runs also strips unverified matched_comment. |
| 1059 | expired = _session(cap=10) |
| 1060 | expired.state = reddit_session.EXPIRED |
| 1061 | hydrated_expired = reddit_hydrate.hydrate( |
| 1062 | [make_ref("1arc001", "FormerlyPublic")], |
| 1063 | topic=TOPIC, |
| 1064 | from_date=FROM, |
| 1065 | to_date=TO, |
| 1066 | comments=False, |
| 1067 | session_hydrator=reddit_session.hydrator(expired), |
| 1068 | now=1.9e9, |
| 1069 | ) |
| 1070 | assert len(hydrated_expired.items) == 1 |
| 1071 | assert "matched_comment" not in hydrated_expired.items[0] |
| 1072 | |
| 1073 | def test_finish_and_hydrate_fail_closed_without_session_hydrator_mutation(self, monkeypatch): |
| 1074 | """Even if session_hydrator is skipped, raises, or _finish is called |
| 1075 | directly, an archive copy with matched_comment_verified=False never |
| 1076 | inherits logged-in matched_comment metadata.""" |
| 1077 | from lib.reddit_refs import ARCTIC, MatchedComment |
| 1078 | |
| 1079 | def make_archive_post(pid: str, sub: str) -> dict: |
| 1080 | return { |
| 1081 | "id": "", |
| 1082 | "title": f"Ghostty terminal thread in {sub}", |
| 1083 | "url": f"https://www.reddit.com/r/{sub}/comments/{pid}/", |
| 1084 | "score": 15, |
| 1085 | "num_comments": 4, |
| 1086 | "subreddit": sub, |
| 1087 | "created_utc": IN_WINDOW_UTC, |
| 1088 | "author": "op", |
| 1089 | "selftext": "", |
| 1090 | "date": dates.timestamp_to_date(IN_WINDOW_UTC), |
| 1091 | "engagement": {"score": 15, "num_comments": 4, "upvote_ratio": 0.9}, |
| 1092 | "engagement_source": ARCTIC, |
| 1093 | "metadata": {"post_id": pid}, |
| 1094 | } |
| 1095 | |
| 1096 | ref_unverified = _ref("1dir001", "FormerlyPublic", provenance="session") |
| 1097 | ref_unverified.matched_comment = MatchedComment( |
| 1098 | comment_id="c_dir1", |
| 1099 | created_utc=1794700800, |
| 1100 | permalink="https://www.reddit.com/r/FormerlyPublic/comments/1dir001/t/c_dir1/", |
| 1101 | ) |
| 1102 | assert ref_unverified.matched_comment_verified is False |
| 1103 | |
| 1104 | # Direct _finish on an archive copy fails closed when unverified. |
| 1105 | finished = reddit_hydrate._finish(make_archive_post("1dir001", "FormerlyPublic"), ref_unverified, TOPIC) |
| 1106 | assert finished["metadata"]["post_id"] == "1dir001" |
| 1107 | assert "matched_comment" not in finished |
| 1108 | |
| 1109 | # Direct _finish attaches matched_comment only when explicitly verified. |
| 1110 | ref_verified = _ref("1dir002", "Ghostty", provenance="session") |
| 1111 | ref_verified.matched_comment = MatchedComment( |
| 1112 | comment_id="c_dir2", |
| 1113 | created_utc=1794700800, |
| 1114 | permalink="https://www.reddit.com/r/Ghostty/comments/1dir002/t/c_dir2/", |
| 1115 | ) |
| 1116 | ref_verified.matched_comment_verified = True |
| 1117 | finished_ok = reddit_hydrate._finish(make_archive_post("1dir002", "Ghostty"), ref_verified, TOPIC) |
| 1118 | assert finished_ok["matched_comment"]["id"] == "c_dir2" |
| 1119 | |
| 1120 | # hydrate() when session_hydrator raises (so it never mutates ref) or is None |
| 1121 | # still keeps the archive copy and omits unverified matched_comment. |
| 1122 | monkeypatch.setattr( |
| 1123 | reddit_arctic, |
| 1124 | "fetch_posts_by_ids", |
| 1125 | lambda ids, **_k: ({"1dir001": make_archive_post("1dir001", "FormerlyPublic")}, "ok"), |
| 1126 | ) |
| 1127 | monkeypatch.setattr(reddit_arctic, "fetch_comment_tree", lambda *_a, **_k: None) |
| 1128 | monkeypatch.setattr(reddit_shreddit, "fetch_comments", lambda *_a, **_k: {}) |
| 1129 | |
| 1130 | def crashing_hydrator(_refs): |
| 1131 | raise RuntimeError("session boom") |
| 1132 | |
| 1133 | for hyd in (None, crashing_hydrator): |
| 1134 | with redirect_stderr(io.StringIO()): |
| 1135 | out = reddit_hydrate.hydrate( |
| 1136 | [ref_unverified], |
| 1137 | topic=TOPIC, |
| 1138 | from_date=FROM, |
| 1139 | to_date=TO, |
| 1140 | comments=False, |
| 1141 | session_hydrator=hyd, |
| 1142 | now=1.9e9, |
| 1143 | ) |
| 1144 | assert len(out.items) == 1 |
| 1145 | assert out.items[0]["metadata"]["post_id"] == "1dir001" |
| 1146 | assert "matched_comment" not in out.items[0] |
| 1147 |