| 1 | """Regression tests for PR 14: CLI flag injection & env isolation in subprocess sources. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-182: Bright Data ambient BRIGHTDATA_API_KEY consistency + credential scrubbing |
| 5 | - HIGH-187: Bright Data Windows PATHEXT binary resolution (.cmd/.bat/.exe) without shell=True |
| 6 | - HIGH-191: Digg CLI `--` separator, upstream cluster ID validation, outdated flag matching, and child env isolation |
| 7 | - HIGH-192: Techmeme CLI `--` separator, exact `--pages` unknown-flag matching, and child env isolation |
| 8 | - HIGH-199: Trustpilot CLI option-shaped topic/domain/hit rejection + `--` separator |
| 9 | - HIGH-200: Trustpilot child env allowlist stripping unrelated provider secrets and NODE_OPTIONS |
| 10 | - HIGH-216: evaluate_search_quality.py `--research-only` / `--` topic isolation and git rev validation |
| 11 | """ |
| 12 | |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import json |
| 16 | import os |
| 17 | import subprocess |
| 18 | import sys |
| 19 | from pathlib import Path |
| 20 | from unittest import mock |
| 21 | |
| 22 | import pytest |
| 23 | |
| 24 | import evaluate_search_quality as evaluator |
| 25 | from lib import brightdata, digg, subproc, techmeme, trustpilot |
| 26 | |
| 27 | |
| 28 | @pytest.fixture(autouse=True) |
| 29 | def _reset_module_state(monkeypatch): |
| 30 | monkeypatch.setattr(digg, "_all_topic_search", None) |
| 31 | trustpilot._reset_state_for_tests() |
| 32 | yield |
| 33 | trustpilot._reset_state_for_tests() |
| 34 | |
| 35 | |
| 36 | def _proc(stdout: str = "", stderr: str = "", returncode: int = 0) -> subproc.SubprocResult: |
| 37 | return subproc.SubprocResult(returncode=returncode, stdout=stdout, stderr=stderr) |
| 38 | |
| 39 | |
| 40 | # ===================================================================== |
| 41 | # HIGH-182: Bright Data ambient API key consistency & secret scrubbing |
| 42 | # ===================================================================== |
| 43 | |
| 44 | |
| 45 | def test_high182_ambient_key_recognized_by_has_credentials_and_scrubbed(monkeypatch, tmp_path): |
| 46 | secret = "bd-ambient-secret-token-98765" |
| 47 | monkeypatch.setenv("BRIGHTDATA_API_KEY", f" {secret} ") |
| 48 | monkeypatch.setattr(brightdata, "_config_dir", lambda: tmp_path / "absent") |
| 49 | monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata") |
| 50 | |
| 51 | assert brightdata._api_key(None) == secret |
| 52 | assert brightdata._api_key({}) == secret |
| 53 | assert brightdata.has_credentials(None) is True |
| 54 | assert brightdata.has_credentials({}) is True |
| 55 | |
| 56 | logged: list[str] = [] |
| 57 | seen_env: dict[str, str] = {} |
| 58 | monkeypatch.setattr(brightdata.log, "source_log", lambda _n, msg, **k: logged.append(msg)) |
| 59 | |
| 60 | def fake_run(cmd, *, timeout, env=None): |
| 61 | seen_env.update(env or {}) |
| 62 | return _proc( |
| 63 | returncode=1, |
| 64 | stderr=( |
| 65 | f"Warning: 401 unauthorized for key {secret}\n" |
| 66 | f"Error: 401 rejected api_key={secret}" |
| 67 | ), |
| 68 | ) |
| 69 | |
| 70 | monkeypatch.setattr(subproc, "run_with_timeout", fake_run) |
| 71 | for cfg in (None, {}): |
| 72 | logged.clear() |
| 73 | seen_env.clear() |
| 74 | out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30, config=cfg) |
| 75 | assert seen_env["BRIGHTDATA_API_KEY"] == secret |
| 76 | assert out["records"] == [] |
| 77 | assert secret not in out["error"] |
| 78 | assert not any(secret in m for m in logged) |
| 79 | |
| 80 | |
| 81 | def test_high182_credentials_json_auth_scrubs_bearer_kv_and_userinfo(monkeypatch, tmp_path): |
| 82 | monkeypatch.delenv("BRIGHTDATA_API_KEY", raising=False) |
| 83 | monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata") |
| 84 | logged: list[str] = [] |
| 85 | monkeypatch.setattr(brightdata.log, "source_log", lambda _n, msg, **k: logged.append(msg)) |
| 86 | |
| 87 | stderr = ( |
| 88 | "Warning: 401 Bearer bd_live_bearer_secret_xyz at https://user:pass123@proxy.brightdata.test/api\n" |
| 89 | "Warning: 401 Authorization: Basic dXNlcjpwYXNzd29yZA== socks5://puser:ppass@proxy.local:1080\n" |
| 90 | "Warning: token expired - run brightdata login\n" |
| 91 | "Error: 401 BRIGHTDATA_API_KEY=creds_json_secret_12345 " |
| 92 | 'api_key=bd_kv_secret_111 token="bd_quoted_222" ' |
| 93 | '"access_token": "bd_escaped_\\"333\\"_secret" ' |
| 94 | "token 'bd_single_quoted_555' token bd_spaced_444444" |
| 95 | ) |
| 96 | monkeypatch.setattr(subproc, "run_with_timeout", lambda *a, **k: _proc(returncode=1, stderr=stderr)) |
| 97 | |
| 98 | out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30, config={}) |
| 99 | combined = "\n".join(logged + [out["error"]]) |
| 100 | for leaked in ( |
| 101 | "bd_live_bearer_secret_xyz", |
| 102 | "user:pass123", |
| 103 | "dXNlcjpwYXNzd29yZA==", |
| 104 | "puser:ppass", |
| 105 | "creds_json_secret_12345", |
| 106 | "bd_kv_secret_111", |
| 107 | "bd_quoted_222", |
| 108 | "bd_escaped_", |
| 109 | "bd_single_quoted_555", |
| 110 | "bd_spaced_444444", |
| 111 | ): |
| 112 | assert leaked not in combined |
| 113 | # Legitimate auth warning prose must survive redaction intact. |
| 114 | assert any("token expired" in msg for msg in logged) |
| 115 | |
| 116 | |
| 117 | def test_high182_url_encoded_secret_and_whitespace_child_env_fallback(monkeypatch): |
| 118 | raw_secret = "bd+key/123=secret" |
| 119 | encoded_secret = "bd%2Bkey%2F123%3Dsecret" |
| 120 | monkeypatch.setenv("BRIGHTDATA_API_KEY", f" {raw_secret} ") |
| 121 | |
| 122 | child = brightdata._child_env(" ") |
| 123 | assert child["BRIGHTDATA_API_KEY"] == raw_secret |
| 124 | |
| 125 | scrubbed = brightdata._scrub( |
| 126 | f"Error: request failed for https://api.test/?k={encoded_secret} raw={raw_secret}", |
| 127 | raw_secret, |
| 128 | ) |
| 129 | assert raw_secret not in scrubbed |
| 130 | assert encoded_secret not in scrubbed |
| 131 | |
| 132 | |
| 133 | def test_high182_json_authorization_and_hyphen_prefixed_api_key_redacted(monkeypatch): |
| 134 | monkeypatch.setenv("BRIGHTDATA_API_KEY", "different-env-key") |
| 135 | payload = ( |
| 136 | '{"Authorization": "Basic ZHVtbXk6c2VjcmV0", ' |
| 137 | '"x-api-key": "dummy_secret_123", ' |
| 138 | '"status": "unauthorized"} ' |
| 139 | "x-api-key: header_secret_456" |
| 140 | ) |
| 141 | scrubbed = brightdata._scrub(payload, "different-env-key") |
| 142 | assert "ZHVtbXk6c2VjcmV0" not in scrubbed |
| 143 | assert "dummy_secret_123" not in scrubbed |
| 144 | assert "header_secret_456" not in scrubbed |
| 145 | assert '"status": "unauthorized"' in scrubbed |
| 146 | |
| 147 | |
| 148 | def test_high182_exception_messages_also_scrub_secrets(monkeypatch): |
| 149 | secret = "bd-exc-secret-777" |
| 150 | monkeypatch.setenv("BRIGHTDATA_API_KEY", secret) |
| 151 | monkeypatch.setattr(brightdata.shutil, "which", lambda _: "/usr/local/bin/brightdata") |
| 152 | logged: list[str] = [] |
| 153 | monkeypatch.setattr(brightdata.log, "source_log", lambda _n, msg, **k: logged.append(msg)) |
| 154 | |
| 155 | def boom(*a, **k): |
| 156 | raise OSError(f"spawn failed with Bearer tok_999 and {secret}") |
| 157 | |
| 158 | monkeypatch.setattr(subproc, "run_with_timeout", boom) |
| 159 | out = brightdata.run_pipeline("gd_x", {"url": "u"}, timeout=30) |
| 160 | assert secret not in out["error"] |
| 161 | assert "tok_999" not in out["error"] |
| 162 | assert not any(secret in m or "tok_999" in m for m in logged) |
| 163 | |
| 164 | |
| 165 | # ===================================================================== |
| 166 | # HIGH-187: Bright Data Windows PATHEXT resolution & BatBadBut defense |
| 167 | # ===================================================================== |
| 168 | |
| 169 | |
| 170 | @pytest.mark.parametrize( |
| 171 | "resolved_binary", |
| 172 | [ |
| 173 | r"C:\Tools\brightdata.exe", |
| 174 | "/home/dev/.local/bin/brightdata", |
| 175 | ], |
| 176 | ) |
| 177 | def test_high187_native_binary_resolved_once_and_passed_directly(monkeypatch, resolved_binary): |
| 178 | which_calls: list[str] = [] |
| 179 | |
| 180 | def fake_which(name): |
| 181 | which_calls.append(name) |
| 182 | return resolved_binary if name == "brightdata" else None |
| 183 | |
| 184 | monkeypatch.setattr(brightdata.shutil, "which", fake_which) |
| 185 | seen: dict = {} |
| 186 | |
| 187 | def fake_run(cmd, *, timeout, env=None): |
| 188 | seen["cmd"] = list(cmd) |
| 189 | return _proc(stdout="[]") |
| 190 | |
| 191 | monkeypatch.setattr(subproc, "run_with_timeout", fake_run) |
| 192 | out = brightdata.run_pipeline("gd_test", {"url": "https://example.com"}, timeout=30) |
| 193 | assert "error" not in out |
| 194 | assert which_calls == ["brightdata"] |
| 195 | assert seen["cmd"][0] == resolved_binary |
| 196 | assert seen["cmd"][1:5] == ["pipelines", "run", "gd_test", "collect_by_url"] |
| 197 | |
| 198 | |
| 199 | @pytest.mark.parametrize( |
| 200 | "shim_name,bin_manifest,entry_rel", |
| 201 | [ |
| 202 | ("brightdata.CMD", '{"bin": "dist/index.js"}', "dist/index.js"), |
| 203 | ("brightdata.cmd", '{"bin": {"brightdata": "dist/cli.js"}}', "dist/cli.js"), |
| 204 | ("brightdata.bat", "{}", "dist/index.js"), |
| 205 | ], |
| 206 | ) |
| 207 | def test_high187_windows_batch_shim_unwraps_to_node_and_preserves_metacharacters( |
| 208 | monkeypatch, tmp_path, shim_name, bin_manifest, entry_rel |
| 209 | ): |
| 210 | shim = tmp_path / shim_name |
| 211 | shim.write_text("@echo off\r\n", encoding="utf-8") |
| 212 | node_exe = tmp_path / "node.exe" |
| 213 | node_exe.write_bytes(b"MZ") |
| 214 | pkg_dir = tmp_path / "node_modules" / "@brightdata" / "cli" |
| 215 | entry = pkg_dir / entry_rel |
| 216 | entry.parent.mkdir(parents=True) |
| 217 | entry.write_text("// entrypoint\n", encoding="utf-8") |
| 218 | (pkg_dir / "package.json").write_text(bin_manifest, encoding="utf-8") |
| 219 | |
| 220 | monkeypatch.setattr( |
| 221 | brightdata.shutil, "which", lambda name: str(shim) if name == "brightdata" else None |
| 222 | ) |
| 223 | seen: dict = {} |
| 224 | |
| 225 | def fake_run(cmd, *, timeout, env=None): |
| 226 | seen["cmd"] = list(cmd) |
| 227 | return _proc(stdout="[]") |
| 228 | |
| 229 | monkeypatch.setattr(subproc, "run_with_timeout", fake_run) |
| 230 | payload_record = {"keyword": "USB-C & Lightning | 100% ^ calc.exe"} |
| 231 | out = brightdata.run_pipeline("gd_test", payload_record, timeout=30) |
| 232 | assert "error" not in out |
| 233 | assert seen["cmd"][0] == str(node_exe) |
| 234 | assert seen["cmd"][1] == str(entry.resolve()) |
| 235 | assert seen["cmd"][2:6] == ["pipelines", "run", "gd_test", "collect_by_url"] |
| 236 | assert json.loads(seen["cmd"][seen["cmd"].index("--input") + 1]) == [payload_record] |
| 237 | |
| 238 | |
| 239 | @pytest.mark.parametrize( |
| 240 | "shim_name", |
| 241 | [ |
| 242 | r"C:\Users\dev\AppData\Roaming\npm\brightdata.CMD", |
| 243 | r"C:\Tools\brightdata.bat", |
| 244 | ], |
| 245 | ) |
| 246 | def test_high187_unwrappable_batch_shim_fails_closed_without_invoking_cmd_exe( |
| 247 | monkeypatch, shim_name |
| 248 | ): |
| 249 | monkeypatch.setattr( |
| 250 | brightdata.shutil, "which", lambda name: shim_name if name == "brightdata" else None |
| 251 | ) |
| 252 | called = [] |
| 253 | monkeypatch.setattr(subproc, "run_with_timeout", lambda *a, **k: called.append(a)) |
| 254 | out = brightdata.run_pipeline( |
| 255 | "gd_test", {"keyword": "router & calc.exe"}, timeout=30 |
| 256 | ) |
| 257 | assert out["records"] == [] |
| 258 | assert "batch shim" in out["error"] |
| 259 | assert called == [] |
| 260 | |
| 261 | |
| 262 | def test_high187_batch_shim_rejects_package_json_path_traversal(monkeypatch, tmp_path): |
| 263 | shim = tmp_path / "brightdata.cmd" |
| 264 | shim.write_text("@echo off\r\n", encoding="utf-8") |
| 265 | (tmp_path / "node.exe").write_bytes(b"MZ") |
| 266 | outside = tmp_path / "evil.js" |
| 267 | outside.write_text("// outside pkg\n", encoding="utf-8") |
| 268 | pkg_dir = tmp_path / "node_modules" / "@brightdata" / "cli" |
| 269 | pkg_dir.mkdir(parents=True) |
| 270 | (pkg_dir / "package.json").write_text('{"bin": "../../../evil.js"}', encoding="utf-8") |
| 271 | |
| 272 | monkeypatch.setattr( |
| 273 | brightdata.shutil, "which", lambda name: str(shim) if name == "brightdata" else None |
| 274 | ) |
| 275 | called = [] |
| 276 | monkeypatch.setattr(subproc, "run_with_timeout", lambda *a, **k: called.append(a)) |
| 277 | out = brightdata.run_pipeline("gd_test", {"url": "https://example.com"}, timeout=30) |
| 278 | assert out["records"] == [] |
| 279 | assert "batch shim" in out["error"] |
| 280 | assert called == [] |
| 281 | |
| 282 | |
| 283 | def test_high187_batch_shim_rejects_node_cmd_fallback_and_fails_closed(monkeypatch, tmp_path): |
| 284 | shim = tmp_path / "brightdata.cmd" |
| 285 | shim.write_text("@echo off\r\n", encoding="utf-8") |
| 286 | pkg_dir = tmp_path / "node_modules" / "@brightdata" / "cli" |
| 287 | entry = pkg_dir / "dist" / "index.js" |
| 288 | entry.parent.mkdir(parents=True) |
| 289 | entry.write_text("// ok\n", encoding="utf-8") |
| 290 | (pkg_dir / "package.json").write_text('{"bin": "dist/index.js"}', encoding="utf-8") |
| 291 | |
| 292 | def fake_which(name): |
| 293 | if name == "brightdata": |
| 294 | return str(shim) |
| 295 | if name == "node": |
| 296 | return r"C:\Tools\node.cmd" |
| 297 | return None |
| 298 | |
| 299 | monkeypatch.setattr(brightdata.shutil, "which", fake_which) |
| 300 | called = [] |
| 301 | monkeypatch.setattr(subproc, "run_with_timeout", lambda *a, **k: called.append(a)) |
| 302 | out = brightdata.run_pipeline("gd_test", {"keyword": "router & calc.exe"}, timeout=30) |
| 303 | assert out["records"] == [] |
| 304 | assert "batch shim" in out["error"] |
| 305 | assert called == [] |
| 306 | |
| 307 | |
| 308 | def test_high187_build_args_defaults_to_cli_bin_for_direct_callers(): |
| 309 | args = brightdata._build_args("gd_test", {"url": "u"}, cli_timeout=20) |
| 310 | assert args[0] == brightdata.CLI_BIN |
| 311 | |
| 312 | |
| 313 | # ===================================================================== |
| 314 | # HIGH-191: Digg CLI `--` separator, upstream ID validation & env isolation |
| 315 | # ===================================================================== |
| 316 | |
| 317 | |
| 318 | @pytest.mark.parametrize( |
| 319 | "topic", |
| 320 | [ |
| 321 | "--config=/tmp/evil.yaml", |
| 322 | "--deliver=file:/tmp/pwn", |
| 323 | "--dangerously-skip-permissions", |
| 324 | "--help", |
| 325 | "-O3", |
| 326 | "-x", |
| 327 | ], |
| 328 | ) |
| 329 | @pytest.mark.parametrize("all_topics", [True, False]) |
| 330 | def test_high191_digg_search_args_put_flags_before_double_dash(topic, all_topics): |
| 331 | args = digg._build_search_args(topic, 20, all_topics=all_topics, by_score=all_topics) |
| 332 | sep = args.index("--") |
| 333 | assert sep == len(args) - 2 |
| 334 | assert args[0:2] == [digg.CLI_BIN, "search"] |
| 335 | assert "--since" in args[:sep] |
| 336 | assert "--agent" in args[:sep] |
| 337 | assert "--limit" in args[:sep] |
| 338 | if all_topics: |
| 339 | assert "--sort" in args[:sep] |
| 340 | assert args[-1] == digg._fit_query(topic) |
| 341 | else: |
| 342 | assert "--topic" in args[:sep] |
| 343 | assert args[-1] == topic |
| 344 | |
| 345 | |
| 346 | def test_high191_outdated_cli_error_only_matches_known_digg_search_flags(): |
| 347 | for flag in ("--topic", "--since", "--agent", "--limit", "--sort"): |
| 348 | assert digg.outdated_cli_error(f"Error: unknown flag: {flag}") is not None |
| 349 | for bogus in ("--dangerously-skip-permissions", "--config", "--deliver", "--help"): |
| 350 | assert digg.outdated_cli_error(f"Error: unknown flag: {bogus}") is None |
| 351 | |
| 352 | |
| 353 | @pytest.mark.parametrize( |
| 354 | "bad_id", |
| 355 | [ |
| 356 | "", |
| 357 | "-x", |
| 358 | "--deliver=file:/tmp/pwn", |
| 359 | "--config=/etc/passwd", |
| 360 | "../admin", |
| 361 | "abc/def", |
| 362 | "abc?x=1", |
| 363 | "abc#frag", |
| 364 | "abc def", |
| 365 | "abc\n--evil", |
| 366 | "_leading_underscore", |
| 367 | ], |
| 368 | ) |
| 369 | def test_high191_digg_rejects_invalid_cluster_ids_across_all_sinks(monkeypatch, bad_id): |
| 370 | with pytest.raises(ValueError): |
| 371 | digg._build_posts_args(bad_id, 5) |
| 372 | with pytest.raises(ValueError): |
| 373 | digg._build_sources_args(bad_id) |
| 374 | with pytest.raises(ValueError): |
| 375 | digg._build_url(bad_id) |
| 376 | |
| 377 | called = [] |
| 378 | monkeypatch.setattr(digg.shutil, "which", lambda _: "/usr/bin/digg-pp-cli") |
| 379 | monkeypatch.setattr(digg.subproc, "run_with_timeout", lambda *a, **k: called.append(a)) |
| 380 | |
| 381 | assert digg.fetch_top_posts(bad_id, posts_per=5) == [] |
| 382 | |
| 383 | class _Item: |
| 384 | source = "digg" |
| 385 | engagement = {"digg_score": 500} |
| 386 | metadata = {digg.STORY_ID_KEY: bad_id} |
| 387 | |
| 388 | assert digg.fetch_story_sources([_Item()], depth="default") == {} |
| 389 | assert called == [] |
| 390 | |
| 391 | |
| 392 | def test_high191_digg_parse_drops_invalid_url_id_and_strips_invalid_cluster_id(): |
| 393 | payload = { |
| 394 | "results": [ |
| 395 | { |
| 396 | "clusterUrlId": "--deliver=file:/tmp/pwn", |
| 397 | "clusterId": "11111111-2222-3333-4444-000000000001", |
| 398 | "url": "https://digg.com/tech/bad", |
| 399 | "title": "Bad url id", |
| 400 | "publishedAt": "2026-11-08T10:00:00Z", |
| 401 | }, |
| 402 | { |
| 403 | "clusterUrlId": "../traverse", |
| 404 | "title": "Bad legacy url id", |
| 405 | "firstPostAge": "2d", |
| 406 | }, |
| 407 | { |
| 408 | "clusterUrlId": "good1234", |
| 409 | "clusterId": "--deliver=webhook:https://evil.example", |
| 410 | "url": "https://digg.com/tech/good1234", |
| 411 | "title": "Good story with poisoned clusterId", |
| 412 | "publishedAt": "2026-11-08T10:00:00Z", |
| 413 | }, |
| 414 | ] |
| 415 | } |
| 416 | items = digg.parse_digg_response(payload, from_date="2026-10-12") |
| 417 | assert [it["id"] for it in items] == ["good1234"] |
| 418 | assert items[0]["cluster_id"] == "" |
| 419 | |
| 420 | |
| 421 | def test_high191_digg_posts_and_sources_args_use_double_dash(): |
| 422 | posts = digg._build_posts_args("abc123xy", 5) |
| 423 | assert posts == [digg.CLI_BIN, "posts", "--agent", "--by", "rank", "--limit", "5", "--", "abc123xy"] |
| 424 | sources = digg._build_sources_args("6043f14d-1717-4b75-8fb2-3a596fe44df5") |
| 425 | assert sources == [ |
| 426 | digg.CLI_BIN, "posts", "--agent", "--limit", str(digg.SOURCES_PER_STORY), "--", |
| 427 | "6043f14d-1717-4b75-8fb2-3a596fe44df5", |
| 428 | ] |
| 429 | |
| 430 | |
| 431 | # ===================================================================== |
| 432 | # HIGH-192: Techmeme CLI `--` separator & exact `--pages` flag match |
| 433 | # ===================================================================== |
| 434 | |
| 435 | |
| 436 | @pytest.mark.parametrize( |
| 437 | "topic", |
| 438 | [ |
| 439 | "-O3 compiler", |
| 440 | "--pages=99", |
| 441 | "--pages-router", |
| 442 | "--config=/tmp/x", |
| 443 | "--deliver=file:/tmp/pwn", |
| 444 | ], |
| 445 | ) |
| 446 | def test_high192_techmeme_search_args_put_flags_before_double_dash(topic): |
| 447 | args = techmeme._build_search_args(topic, "2026-10-01", "2026-10-31", pages=2) |
| 448 | assert args == [ |
| 449 | techmeme.CLI_BIN, |
| 450 | "search", |
| 451 | "--json", |
| 452 | "--pages", |
| 453 | "2", |
| 454 | "--", |
| 455 | f"{topic} date:[10/1/26 TO 10/31/26]", |
| 456 | ] |
| 457 | single = techmeme._build_search_args(topic, pages=1) |
| 458 | assert single == [techmeme.CLI_BIN, "search", "--json", "--", topic] |
| 459 | |
| 460 | |
| 461 | def test_high192_rejects_pages_flag_requires_complete_token_and_avoids_bogus_retry(monkeypatch): |
| 462 | assert techmeme._rejects_pages_flag({"error": "Error: unknown flag: --pages"}) is True |
| 463 | assert techmeme._rejects_pages_flag({"error": "unknown flag: --pages\nUsage: ..."}) is True |
| 464 | assert techmeme._rejects_pages_flag({"error": "Error: unknown flag: --pages-router"}) is False |
| 465 | assert techmeme._rejects_pages_flag({"error": "Error: unknown flag: --config (see --pages)"}) is False |
| 466 | |
| 467 | calls: list[list[str]] = [] |
| 468 | |
| 469 | def fake_run(cmd, *, timeout, env=None): |
| 470 | calls.append(list(cmd)) |
| 471 | return _proc(returncode=1, stderr="Error: unknown flag: --pages-router\n") |
| 472 | |
| 473 | monkeypatch.setattr(techmeme, "_is_available", lambda: True) |
| 474 | monkeypatch.setattr(techmeme.subproc, "run_with_timeout", fake_run) |
| 475 | out = techmeme.search_techmeme("--pages-router", "2026-10-01", "2026-10-31") |
| 476 | assert len(calls) == 1 |
| 477 | assert out["error"] == "Error: unknown flag: --pages-router" |
| 478 | |
| 479 | |
| 480 | # ===================================================================== |
| 481 | # HIGH-199: Trustpilot option-shaped input rejection & `--` separator |
| 482 | # ===================================================================== |
| 483 | |
| 484 | |
| 485 | @pytest.mark.parametrize( |
| 486 | "bad_topic", |
| 487 | [ |
| 488 | "-x Brand", |
| 489 | "--deliver=file:/tmp/pwn Brand", |
| 490 | "--help", |
| 491 | "-x chownow.com", |
| 492 | "Brand\n--deliver=file:/tmp/pwn", |
| 493 | "Brand\x00", |
| 494 | ], |
| 495 | ) |
| 496 | def test_high199_trustpilot_is_brand_shaped_rejects_option_and_control_topics(bad_topic): |
| 497 | assert trustpilot.is_brand_shaped(bad_topic) is False |
| 498 | |
| 499 | |
| 500 | @pytest.mark.parametrize( |
| 501 | "bad_domain", |
| 502 | [ |
| 503 | "--deliver=file:/tmp/pwn", |
| 504 | "-bad.com", |
| 505 | "bad-.com", |
| 506 | "foo bar.com", |
| 507 | "example.com\n--flag", |
| 508 | "example.com/path", |
| 509 | "localhost", |
| 510 | "127.0.0.1", |
| 511 | "example.xn---", |
| 512 | "example.xn--a-", |
| 513 | "example.xn--", |
| 514 | ], |
| 515 | ) |
| 516 | @pytest.mark.parametrize("domain_is_hint", [False, True]) |
| 517 | def test_high199_trustpilot_rejects_invalid_explicit_domain_before_cli( |
| 518 | monkeypatch, bad_domain, domain_is_hint |
| 519 | ): |
| 520 | called = [] |
| 521 | logged: list[tuple[str, bool]] = [] |
| 522 | monkeypatch.setattr(trustpilot, "_is_available", lambda: True) |
| 523 | monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {}) |
| 524 | monkeypatch.setattr( |
| 525 | trustpilot.log, "source_log", |
| 526 | lambda _n, msg, **k: logged.append((msg, k.get("tty_only", True))), |
| 527 | ) |
| 528 | out = trustpilot.search_trustpilot( |
| 529 | "ChowNow", "2026-10-01", "2026-10-31", |
| 530 | explicit_domain=bad_domain, domain_is_hint=domain_is_hint, |
| 531 | ) |
| 532 | assert out == { |
| 533 | "results": [], |
| 534 | "error": "Invalid Trustpilot domain: use a bare hostname without a scheme or path.", |
| 535 | } |
| 536 | assert bad_domain not in out["error"] |
| 537 | assert called == [] |
| 538 | assert logged == [(out["error"], False)] |
| 539 | assert all(bad_domain not in msg for msg, _ in logged) |
| 540 | |
| 541 | |
| 542 | @pytest.mark.parametrize("valid_domain", ["example.xn--p1ai", "example.XN--P1AI", "example.xn--a"]) |
| 543 | def test_high199_trustpilot_accepts_valid_punycode_tlds(valid_domain): |
| 544 | assert trustpilot._is_valid_domain(valid_domain) is True |
| 545 | |
| 546 | |
| 547 | def test_high199_trustpilot_rejects_malicious_domains_from_search_hits(): |
| 548 | hits = [ |
| 549 | {"displayName": "ChowNow", "domain": "--deliver=file:/tmp/pwn", "numberOfReviews": 999999}, |
| 550 | {"displayName": "ChowNow", "identifyingName": "-evil.com", "numberOfReviews": 999999}, |
| 551 | {"displayName": "ChowNow", "domain": "chownow.com\n--flag", "numberOfReviews": 999999}, |
| 552 | {"displayName": "ChowNow", "domain": "chownow.com/review", "numberOfReviews": 999999}, |
| 553 | ] |
| 554 | assert trustpilot._select_search_hit("ChowNow", hits) is None |
| 555 | |
| 556 | |
| 557 | def test_high199_trustpilot_builders_use_double_dash_and_reject_leading_dash(monkeypatch): |
| 558 | assert trustpilot._build_info_args("chownow.com") == [ |
| 559 | trustpilot.CLI_BIN, "info", "--agent", "--", "chownow.com" |
| 560 | ] |
| 561 | with pytest.raises(ValueError): |
| 562 | trustpilot._build_info_args("--deliver=file:/tmp/pwn") |
| 563 | |
| 564 | called = [] |
| 565 | monkeypatch.setattr(trustpilot, "_is_available", lambda: True) |
| 566 | monkeypatch.setattr(trustpilot, "_run_cli", lambda *a, **k: called.append(a) or {}) |
| 567 | |
| 568 | assert trustpilot._search_domain("-x Brand") is None |
| 569 | assert trustpilot._cached_info("--deliver=file:/tmp/pwn") is None |
| 570 | assert trustpilot._cached_info("not a domain") is None |
| 571 | assert called == [] |
| 572 | |
| 573 | |
| 574 | # ===================================================================== |
| 575 | # HIGH-200 (+ digg/techmeme): Subprocess environment allowlist isolation |
| 576 | # ===================================================================== |
| 577 | |
| 578 | |
| 579 | _SECRET_VARS = { |
| 580 | "OPENAI_API_KEY": "fake-openai", |
| 581 | "PERPLEXITY_API_KEY": "fake-perplexity", |
| 582 | "SCRAPECREATORS_API_KEY": "fake-sc", |
| 583 | "XAI_API_KEY": "fake-xai", |
| 584 | "GITHUB_TOKEN": "fake-gh", |
| 585 | "OPENROUTER_API_KEY": "fake-or", |
| 586 | "AUTH_TOKEN": "fake-auth-token", |
| 587 | "CT0": "fake-ct0", |
| 588 | "BRIGHTDATA_API_KEY": "fake-bd", |
| 589 | "GOOGLE_API_KEY": "fake-google", |
| 590 | "NODE_OPTIONS": "--require /tmp/untrusted.js", |
| 591 | "PYTHONPATH": "/tmp/untrusted", |
| 592 | "LD_PRELOAD": "/tmp/untrusted.so", |
| 593 | } |
| 594 | |
| 595 | _ESSENTIAL_VARS = { |
| 596 | "PATH": "/usr/local/bin:/usr/bin", |
| 597 | "HOME": "/home/tester", |
| 598 | "USERPROFILE": r"C:\Users\tester", |
| 599 | "HOMEDRIVE": "C:", |
| 600 | "HOMEPATH": r"\Users\tester", |
| 601 | "APPDATA": r"C:\Users\tester\AppData\Roaming", |
| 602 | "LOCALAPPDATA": r"C:\Users\tester\AppData\Local", |
| 603 | "XDG_CONFIG_HOME": "/home/tester/.config", |
| 604 | "XDG_DATA_HOME": "/home/tester/.local/share", |
| 605 | "XDG_CACHE_HOME": "/home/tester/.cache", |
| 606 | "SystemRoot": r"C:\Windows", |
| 607 | "WINDIR": r"C:\Windows", |
| 608 | "SystemDrive": "C:", |
| 609 | "COMSPEC": r"C:\Windows\System32\cmd.exe", |
| 610 | "PATHEXT": ".COM;.EXE;.BAT;.CMD", |
| 611 | "TMPDIR": "/tmp", |
| 612 | "TEMP": r"C:\Temp", |
| 613 | "TMP": r"C:\Temp", |
| 614 | "LANG": "en_US.UTF-8", |
| 615 | "LC_ALL": "en_US.UTF-8", |
| 616 | "LC_MESSAGES": "C", |
| 617 | "SSL_CERT_FILE": "/etc/ssl/certs/ca-certificates.crt", |
| 618 | "SSL_CERT_DIR": "/etc/ssl/certs", |
| 619 | "HTTP_PROXY": "http://proxy.internal:8080", |
| 620 | "https_proxy": "http://proxy.internal:8080", |
| 621 | "NO_PROXY": "localhost,127.0.0.1", |
| 622 | } |
| 623 | |
| 624 | |
| 625 | @pytest.mark.parametrize("module", [trustpilot, digg, techmeme]) |
| 626 | def test_high200_child_env_strips_secrets_and_preserves_cross_platform_vars(module): |
| 627 | combined = {**_ESSENTIAL_VARS, **_SECRET_VARS} |
| 628 | with mock.patch.object(module.os, "environ", combined): |
| 629 | child = module._child_env() |
| 630 | for secret_key in _SECRET_VARS: |
| 631 | assert secret_key not in child |
| 632 | for keep_key, keep_val in _ESSENTIAL_VARS.items(): |
| 633 | assert child[keep_key] == keep_val |
| 634 | |
| 635 | |
| 636 | def test_high200_real_child_subprocesses_do_not_receive_parent_secrets(monkeypatch): |
| 637 | probe = ( |
| 638 | "import json, os; " |
| 639 | "leaked = [k for k in ('OPENAI_API_KEY','XAI_API_KEY','SCRAPECREATORS_API_KEY'," |
| 640 | "'AUTH_TOKEN','CT0','GITHUB_TOKEN','NODE_OPTIONS','PERPLEXITY_API_KEY') if k in os.environ]; " |
| 641 | "print(json.dumps({'results': [{'leaked': leaked, 'has_path': 'PATH' in os.environ}], 'leaked': leaked}))" |
| 642 | ) |
| 643 | monkeypatch.setattr(trustpilot, "_is_available", lambda: True) |
| 644 | monkeypatch.setattr(digg, "_is_available", lambda: True) |
| 645 | monkeypatch.setattr(techmeme, "_is_available", lambda: True) |
| 646 | |
| 647 | with mock.patch.dict(os.environ, _SECRET_VARS, clear=False): |
| 648 | tp_out = trustpilot._run_cli([sys.executable, "-I", "-c", probe], timeout=10) |
| 649 | digg_out = digg._run_cli([sys.executable, "-I", "-c", probe], timeout=10) |
| 650 | tm_out = techmeme._run_cli([sys.executable, "-I", "-c", probe], timeout=10) |
| 651 | |
| 652 | assert tp_out["leaked"] == [] |
| 653 | assert digg_out["results"] == [{"leaked": [], "has_path": True}] |
| 654 | assert tm_out["results"] == [{"leaked": [], "has_path": True}] |
| 655 | |
| 656 | |
| 657 | @pytest.mark.parametrize("module", [digg, techmeme, trustpilot]) |
| 658 | def test_high200_proxy_userinfo_is_scrubbed_from_cli_stderr_and_logs(monkeypatch, module): |
| 659 | logged: list[str] = [] |
| 660 | monkeypatch.setattr(module, "_is_available", lambda: True) |
| 661 | monkeypatch.setattr(module, "_log", lambda msg: logged.append(msg)) |
| 662 | stderr = "proxyconnect tcp: http://proxyuser:supersecret@proxy.corp:8080: 407 Proxy Auth Required\n" |
| 663 | monkeypatch.setattr( |
| 664 | module.subproc, "run_with_timeout", |
| 665 | lambda *a, **k: _proc(returncode=1, stderr=stderr), |
| 666 | ) |
| 667 | |
| 668 | out = module._run_cli([module.CLI_BIN, "search"], timeout=10) |
| 669 | combined = "\n".join(logged + [out.get("error", "")]) |
| 670 | assert "proxyuser" not in combined |
| 671 | assert "supersecret" not in combined |
| 672 | assert "http://proxy.corp:8080" in out["error"] |
| 673 | |
| 674 | |
| 675 | # ===================================================================== |
| 676 | # HIGH-216: evaluate_search_quality.py topic & git rev isolation |
| 677 | # ===================================================================== |
| 678 | |
| 679 | |
| 680 | @pytest.mark.parametrize( |
| 681 | "topic", |
| 682 | [ |
| 683 | "--publish-html", |
| 684 | "--store", |
| 685 | "--corpus=/etc", |
| 686 | "setup", |
| 687 | "library feed --publish", |
| 688 | ], |
| 689 | ) |
| 690 | def test_high216_run_last30days_uses_research_only_and_double_dash(tmp_path, topic): |
| 691 | engine = tmp_path / "skills" / "last30days" / "scripts" / "last30days.py" |
| 692 | engine.parent.mkdir(parents=True) |
| 693 | engine.write_text('parser.add_argument("--research-only")\nparser.add_argument("--json-profile")\n') |
| 694 | |
| 695 | completed = mock.Mock(returncode=0, stdout='{"ranked_candidates": []}', stderr="") |
| 696 | with mock.patch.object(evaluator.subprocess, "run", return_value=completed) as run: |
| 697 | evaluator.run_last30days( |
| 698 | tmp_path, topic, search="reddit", timeout_seconds=30, quick=True, mock=True, env={"PATH": "/bin"}, |
| 699 | ) |
| 700 | |
| 701 | cmd = run.call_args.args[0] |
| 702 | sep = cmd.index("--") |
| 703 | assert "--research-only" in cmd[:sep] |
| 704 | assert "--json-profile=raw" in cmd[:sep] |
| 705 | assert "--emit=json" in cmd[:sep] |
| 706 | assert cmd[sep:] == ["--", topic] |
| 707 | |
| 708 | |
| 709 | def test_high216_run_last30days_omits_research_only_for_legacy_engine(tmp_path): |
| 710 | engine = tmp_path / "skills" / "last30days" / "scripts" / "last30days.py" |
| 711 | engine.parent.mkdir(parents=True) |
| 712 | engine.write_text('parser.add_argument("--emit")\n') |
| 713 | |
| 714 | completed = mock.Mock(returncode=0, stdout='{"reddit": []}', stderr="") |
| 715 | with mock.patch.object(evaluator.subprocess, "run", return_value=completed) as run: |
| 716 | evaluator.run_last30days( |
| 717 | tmp_path, "--store", search="", timeout_seconds=30, quick=False, mock=False, env={"PATH": "/bin"}, |
| 718 | ) |
| 719 | |
| 720 | cmd = run.call_args.args[0] |
| 721 | assert "--research-only" not in cmd |
| 722 | assert "--json-profile=raw" not in cmd |
| 723 | assert cmd[-2:] == ["--", "--store"] |
| 724 | |
| 725 | |
| 726 | @pytest.mark.parametrize( |
| 727 | "reserved_topic", |
| 728 | [ |
| 729 | "setup", |
| 730 | "SETUP", |
| 731 | "doctor", |
| 732 | "library feed --publish", |
| 733 | "library search secrets", |
| 734 | "queue list", |
| 735 | "watchlist add foo", |
| 736 | "update", |
| 737 | "briefing", |
| 738 | ], |
| 739 | ) |
| 740 | def test_high216_run_last30days_rejects_reserved_admin_topics_on_legacy_engine( |
| 741 | tmp_path, reserved_topic |
| 742 | ): |
| 743 | engine = tmp_path / "skills" / "last30days" / "scripts" / "last30days.py" |
| 744 | engine.parent.mkdir(parents=True) |
| 745 | engine.write_text('parser.add_argument("--emit")\n') |
| 746 | |
| 747 | with mock.patch.object(evaluator.subprocess, "run") as run: |
| 748 | with pytest.raises(ValueError, match="without --research-only"): |
| 749 | evaluator.run_last30days( |
| 750 | tmp_path, reserved_topic, search="", timeout_seconds=30, |
| 751 | quick=False, mock=False, env={"PATH": "/bin"}, |
| 752 | ) |
| 753 | run.assert_not_called() |
| 754 | |
| 755 | |
| 756 | @pytest.mark.parametrize("bad_rev", ["--orphan", "-b", "--checkout", "", " HEAD ", "HEAD\n--evil", "HEAD\x00"]) |
| 757 | def test_high216_create_worktree_rejects_option_and_malformed_revs(bad_rev): |
| 758 | with mock.patch.object(evaluator.subprocess, "run") as run, \ |
| 759 | mock.patch.object(evaluator.tempfile, "mkdtemp") as mkdtemp: |
| 760 | with pytest.raises(ValueError): |
| 761 | evaluator.create_worktree(bad_rev) |
| 762 | run.assert_not_called() |
| 763 | mkdtemp.assert_not_called() |
| 764 | |
| 765 | |
| 766 | def test_high216_create_worktree_resolves_commit_with_end_of_options_and_cleans_up_on_error(tmp_path): |
| 767 | sha = "a" * 40 |
| 768 | wt_path = tmp_path / "wt-ok" |
| 769 | wt_path.mkdir() |
| 770 | |
| 771 | with mock.patch.object(evaluator.tempfile, "mkdtemp", return_value=str(wt_path)), \ |
| 772 | mock.patch.object( |
| 773 | evaluator.subprocess, "run", |
| 774 | side_effect=[ |
| 775 | mock.Mock(returncode=0, stdout=f"{sha}\n", stderr=""), |
| 776 | mock.Mock(returncode=0, stdout="", stderr=""), |
| 777 | ], |
| 778 | ) as run: |
| 779 | result = evaluator.create_worktree("HEAD~1") |
| 780 | |
| 781 | assert result == wt_path |
| 782 | assert run.call_args_list[0].args[0] == [ |
| 783 | "git", "rev-parse", "--verify", "--end-of-options", "HEAD~1^{commit}" |
| 784 | ] |
| 785 | assert run.call_args_list[1].args[0] == [ |
| 786 | "git", "worktree", "add", "--detach", str(wt_path), sha |
| 787 | ] |
| 788 | |
| 789 | # Verify failed worktree creation removes partially populated dir & git worktree metadata. |
| 790 | wt_fail = tmp_path / "wt-fail" |
| 791 | nested = wt_fail / "sub" |
| 792 | nested.mkdir(parents=True) |
| 793 | (nested / "partial.txt").write_text("partial", encoding="utf-8") |
| 794 | with mock.patch.object(evaluator.tempfile, "mkdtemp", return_value=str(wt_fail)), \ |
| 795 | mock.patch.object(evaluator, "remove_worktree", wraps=evaluator.remove_worktree) as rm_wt, \ |
| 796 | mock.patch.object( |
| 797 | evaluator.subprocess, "run", |
| 798 | side_effect=[ |
| 799 | mock.Mock(returncode=0, stdout=f"{sha}\n", stderr=""), |
| 800 | subprocess.CalledProcessError(128, ["git", "worktree", "add"]), |
| 801 | mock.Mock(returncode=0, stdout="", stderr=""), |
| 802 | ], |
| 803 | ): |
| 804 | with pytest.raises(subprocess.CalledProcessError): |
| 805 | evaluator.create_worktree("HEAD") |
| 806 | rm_wt.assert_called_once_with(wt_fail) |
| 807 | assert not wt_fail.exists() |
| 808 |