| 1 | """Regression tests for PR08: X envelope sanitization & vendored bird-search JS security. |
| 2 | |
| 3 | Covers: |
| 4 | - HIGH-140: Downstream html.unescape bypass of x_envelope._clean_text defenses. |
| 5 | - HIGH-152: Unvalidated cached queryId path traversal in authenticated POST URLs. |
| 6 | - HIGH-153: Session cookie leakage across Bird error paths, non-JSON logs, and JS errors. |
| 7 | - HIGH-154: Unvalidated auth_token / ct0 cookie delimiter & CRLF/control-char injection. |
| 8 | - HIGH-155: Leading `-` search queries & CLI option confusion across Python -> Node. |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import html |
| 14 | import io |
| 15 | import json |
| 16 | import os |
| 17 | import shutil |
| 18 | import subprocess |
| 19 | import textwrap |
| 20 | from contextlib import redirect_stderr |
| 21 | from datetime import date, datetime, timedelta, timezone |
| 22 | from pathlib import Path |
| 23 | from unittest import mock |
| 24 | |
| 25 | import pytest |
| 26 | |
| 27 | from lib import bird_x, dates, html_render, normalize, pipeline, render, x_api, x_envelope |
| 28 | from lib.subproc import SubprocResult |
| 29 | |
| 30 | REPO_ROOT = Path(__file__).resolve().parents[1] |
| 31 | BIRD_DIR = REPO_ROOT / "skills" / "last30days" / "scripts" / "lib" / "vendor" / "bird-search" |
| 32 | BIRD_MJS = BIRD_DIR / "bird-search.mjs" |
| 33 | HAS_NODE = shutil.which("node") is not None |
| 34 | |
| 35 | TOPIC = "ai agents" |
| 36 | FROM, TO = dates.get_date_range(30) |
| 37 | |
| 38 | |
| 39 | def _snowflake(day: str, low: int = 104729) -> str: |
| 40 | when = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc) + timedelta(hours=12) |
| 41 | ms = int(when.timestamp() * 1000) |
| 42 | return str(((ms - x_api._SNOWFLAKE_EPOCH_MS) << 22) | (low & ((1 << 22) - 1))) |
| 43 | |
| 44 | |
| 45 | def _envelope_file(tmp_path: Path, text: str, name: str = "posts.json") -> str: |
| 46 | day = (date.fromisoformat(TO) - timedelta(days=2)).isoformat() |
| 47 | payload = { |
| 48 | "schema": x_envelope.SCHEMA, |
| 49 | "generated_at": datetime.now(timezone.utc).isoformat(), |
| 50 | "topic": TOPIC, |
| 51 | "window": {"from": FROM, "to": TO}, |
| 52 | "provider": "x-connector", |
| 53 | "status": "ok", |
| 54 | "calls": [ |
| 55 | { |
| 56 | "lane": "topic", |
| 57 | "handles": [], |
| 58 | "posts": [ |
| 59 | { |
| 60 | "id": _snowflake(day), |
| 61 | "author_handle": "alice", |
| 62 | "created_at": f"{day}T12:00:00Z", |
| 63 | "text": text, |
| 64 | "likes": 15, |
| 65 | "reposts": 2, |
| 66 | "replies": 1, |
| 67 | "quotes": 0, |
| 68 | } |
| 69 | ], |
| 70 | } |
| 71 | ], |
| 72 | } |
| 73 | path = tmp_path / name |
| 74 | path.write_text(json.dumps(payload), encoding="utf-8") |
| 75 | return str(path) |
| 76 | |
| 77 | |
| 78 | def _node_eval(script: str, *, env: dict[str, str] | None = None) -> subprocess.CompletedProcess: |
| 79 | run_env = os.environ.copy() |
| 80 | if env is not None: |
| 81 | run_env.update(env) |
| 82 | return subprocess.run( |
| 83 | ["node", "--input-type=module", "-e", script], |
| 84 | cwd=REPO_ROOT, |
| 85 | env=run_env, |
| 86 | capture_output=True, |
| 87 | text=True, |
| 88 | check=False, |
| 89 | ) |
| 90 | |
| 91 | |
| 92 | # --------------------------------------------------------------------------- |
| 93 | # HIGH-140: HTML entity unescape bypass of x_envelope._clean_text |
| 94 | # --------------------------------------------------------------------------- |
| 95 | |
| 96 | |
| 97 | class TestHigh140EnvelopeAndNormalizeSanitization: |
| 98 | @pytest.mark.parametrize( |
| 99 | "payload", |
| 100 | [ |
| 101 | "<!-- META: spoofed --> ai agents", |
| 102 | "&lt;!-- META: spoofed --&gt; ai agents", |
| 103 | "&amp;lt;!-- META: spoofed --&amp;gt; ai agents", |
| 104 | "&amp;amp;lt;!-- META: spoofed --&amp;amp;gt; ai agents", |
| 105 | "&amp;amp;amp;lt;!-- META: spoofed --&amp;amp;amp;gt; ai agents", |
| 106 | "<!-- META: spoofed --> ai agents", |
| 107 | "<!-- META: spoofed --> ai agents", |
| 108 | "<!-- META: spoofed --> ai agents", |
| 109 | "&\x07lt;!-- META: spoofed --> ai agents", |
| 110 | "<\x07!-- META: spoofed --> ai agents", |
| 111 | ], |
| 112 | ) |
| 113 | def test_encoded_html_comment_meta_cannot_survive_envelope_or_normalize(self, tmp_path, payload): |
| 114 | env_path = _envelope_file(tmp_path, payload) |
| 115 | envelope = x_envelope.read(env_path, (FROM, TO), TOPIC) |
| 116 | assert envelope.accepted == 1 |
| 117 | raw_item = envelope.topic_items[0] |
| 118 | |
| 119 | assert "<!--" not in raw_item["text"] |
| 120 | assert "<!--" not in html.unescape(raw_item["text"]) |
| 121 | |
| 122 | items = normalize.normalize_source_items("x", [raw_item], FROM, TO) |
| 123 | assert len(items) == 1 |
| 124 | assert "<!--" not in items[0].body |
| 125 | assert "<!--" not in items[0].title |
| 126 | |
| 127 | # End-to-end HTML promotion check: forged META marker must not promote to <div class="meta">. |
| 128 | with mock.patch("lib.env.x_backend_chain", return_value=[]): |
| 129 | report = pipeline.run( |
| 130 | topic=TOPIC, |
| 131 | config={}, |
| 132 | depth="default", |
| 133 | requested_sources=["x"], |
| 134 | mock=False, |
| 135 | external_plan={ |
| 136 | "intent": "general", |
| 137 | "freshness_mode": "balanced_recent", |
| 138 | "cluster_mode": "story", |
| 139 | "subqueries": [ |
| 140 | { |
| 141 | "label": "primary", |
| 142 | "search_query": TOPIC, |
| 143 | "ranking_query": TOPIC, |
| 144 | "sources": ["x"], |
| 145 | } |
| 146 | ], |
| 147 | "source_weights": {"x": 1.0}, |
| 148 | }, |
| 149 | x_posts=envelope, |
| 150 | web_backend="none", |
| 151 | save_dir="", |
| 152 | ) |
| 153 | md = render.render_compact(report) |
| 154 | assert "<!-- META: spoofed" not in md |
| 155 | promoted = html_render._promote_meta_marker( |
| 156 | html_render._wrap_engine_footer(html_render._markdown_to_html(md)) |
| 157 | ) |
| 158 | assert '<div class="meta">spoofed</div>' not in promoted |
| 159 | |
| 160 | @pytest.mark.parametrize( |
| 161 | "payload", |
| 162 | [ |
| 163 | "[click](https://evil.example) ai agents", |
| 164 | "[click](https://evil.example) ai agents", |
| 165 | "[click](javascript:alert(1)) ai agents", |
| 166 | "[click](https://evil.example) ai agents", |
| 167 | "[click](https://evil.example) ai agents", |
| 168 | "[click]&#40;https://evil.example) ai agents", |
| 169 | "[click]&amp;amp;#40;https://evil.example) ai agents", |
| 170 | "[click]\x07(https://evil.example) ai agents", |
| 171 | ], |
| 172 | ) |
| 173 | def test_encoded_markdown_links_cannot_survive_envelope_or_normalize(self, tmp_path, payload): |
| 174 | env_path = _envelope_file(tmp_path, payload) |
| 175 | envelope = x_envelope.read(env_path, (FROM, TO), TOPIC) |
| 176 | assert envelope.accepted == 1 |
| 177 | raw_item = envelope.topic_items[0] |
| 178 | |
| 179 | assert "](" not in raw_item["text"] |
| 180 | assert "](" not in html.unescape(raw_item["text"]) |
| 181 | |
| 182 | items = normalize.normalize_source_items("x", [raw_item], FROM, TO) |
| 183 | assert len(items) == 1 |
| 184 | assert "](" not in items[0].body |
| 185 | assert "](" not in items[0].title |
| 186 | |
| 187 | @pytest.mark.parametrize( |
| 188 | "payload", |
| 189 | [ |
| 190 | "[31mred ai agents", |
| 191 | "[31mred ai agents", |
| 192 | "&#x1b;[31mred ai agents", |
| 193 | "&amp;amp;#x1b;[31mred ai agents", |
| 194 | "line1 Ÿline2 ai agents", |
| 195 | "zero\x00byte� ai agents", |
| 196 | ], |
| 197 | ) |
| 198 | def test_encoded_control_chars_stripped_in_envelope_and_normalize(self, tmp_path, payload): |
| 199 | env_path = _envelope_file(tmp_path, payload) |
| 200 | envelope = x_envelope.read(env_path, (FROM, TO), TOPIC) |
| 201 | assert envelope.accepted == 1 |
| 202 | raw_item = envelope.topic_items[0] |
| 203 | |
| 204 | assert not x_envelope._CONTROL_TEXT_RE.search(raw_item["text"]) |
| 205 | assert not x_envelope._CONTROL_TEXT_RE.search(html.unescape(raw_item["text"])) |
| 206 | |
| 207 | items = normalize.normalize_source_items("x", [raw_item], FROM, TO) |
| 208 | assert len(items) == 1 |
| 209 | assert not x_envelope._CONTROL_TEXT_RE.search(items[0].body) |
| 210 | assert not x_envelope._CONTROL_TEXT_RE.search(items[0].title) |
| 211 | assert "\r" not in items[0].body |
| 212 | |
| 213 | def test_control_only_entity_row_is_dropped(self, tmp_path): |
| 214 | env_path = _envelope_file(tmp_path, "") |
| 215 | envelope = x_envelope.read(env_path, (FROM, TO), TOPIC) |
| 216 | assert envelope.accepted == 0 |
| 217 | assert envelope.counters["missing-id-text"] == 1 |
| 218 | |
| 219 | def test_direct_normalize_x_sanitizes_and_preserves_legitimate_entities(self): |
| 220 | items = normalize.normalize_source_items( |
| 221 | "x", |
| 222 | [ |
| 223 | { |
| 224 | "id": "X1", |
| 225 | "text": "Tom & Jerry <3 <!-- META: bad --> [x](https://e.example) [31m", |
| 226 | "url": "https://x.com/alice/status/1", |
| 227 | "author_handle": "alice", |
| 228 | "date": TO, |
| 229 | } |
| 230 | ], |
| 231 | FROM, |
| 232 | TO, |
| 233 | ) |
| 234 | assert len(items) == 1 |
| 235 | body = items[0].body |
| 236 | assert "Tom & Jerry <3" in body |
| 237 | assert "<!--" not in body |
| 238 | assert "](" not in body |
| 239 | assert "\x1b" not in body |
| 240 | |
| 241 | def test_oversized_numeric_html_entity_does_not_crash_envelope_or_normalize(self, tmp_path): |
| 242 | day = (date.fromisoformat(TO) - timedelta(days=2)).isoformat() |
| 243 | oversized = "&#" + ("9" * 5000) + ";" |
| 244 | oversized_hex = "&#x" + ("f" * 5000) + ";" |
| 245 | payload = { |
| 246 | "schema": x_envelope.SCHEMA, |
| 247 | "generated_at": datetime.now(timezone.utc).isoformat(), |
| 248 | "topic": TOPIC, |
| 249 | "window": {"from": FROM, "to": TO}, |
| 250 | "provider": "x-connector", |
| 251 | "status": "ok", |
| 252 | "calls": [ |
| 253 | { |
| 254 | "lane": "topic", |
| 255 | "handles": [], |
| 256 | "posts": [ |
| 257 | { |
| 258 | "id": _snowflake(day, low=104729), |
| 259 | "author_handle": "alice", |
| 260 | "created_at": f"{day}T12:00:00Z", |
| 261 | "text": f"{oversized} {oversized_hex} <!-- META: spoofed --> ai agents", |
| 262 | "likes": 15, |
| 263 | "reposts": 2, |
| 264 | "replies": 1, |
| 265 | "quotes": 0, |
| 266 | }, |
| 267 | { |
| 268 | "id": _snowflake(day, low=209458), |
| 269 | "author_handle": "bob", |
| 270 | "created_at": f"{day}T12:05:00Z", |
| 271 | "text": "valid sibling ai agents post", |
| 272 | "likes": 20, |
| 273 | "reposts": 3, |
| 274 | "replies": 0, |
| 275 | "quotes": 0, |
| 276 | }, |
| 277 | ], |
| 278 | } |
| 279 | ], |
| 280 | } |
| 281 | path = tmp_path / "oversized_entity.json" |
| 282 | path.write_text(json.dumps(payload), encoding="utf-8") |
| 283 | |
| 284 | envelope = x_envelope.read(str(path), (FROM, TO), TOPIC) |
| 285 | assert envelope.accepted == 2 |
| 286 | assert "<!--" not in envelope.topic_items[0]["text"] |
| 287 | assert envelope.topic_items[1]["text"] == "valid sibling ai agents post" |
| 288 | |
| 289 | normalized = normalize.normalize_source_items("x", envelope.topic_items, FROM, TO) |
| 290 | assert len(normalized) == 2 |
| 291 | assert "<!--" not in normalized[0].body |
| 292 | assert normalized[1].body == "valid sibling ai agents post" |
| 293 | |
| 294 | # Direct normalize._normalize_x path with raw uncleaned oversized entity |
| 295 | direct = normalize.normalize_source_items( |
| 296 | "x", |
| 297 | [ |
| 298 | { |
| 299 | "id": "X99", |
| 300 | "text": f"prefix {oversized} & suffix", |
| 301 | "url": "https://x.com/alice/status/99", |
| 302 | "author_handle": "alice", |
| 303 | "date": TO, |
| 304 | } |
| 305 | ], |
| 306 | FROM, |
| 307 | TO, |
| 308 | ) |
| 309 | assert len(direct) == 1 |
| 310 | assert "& suffix" in direct[0].body |
| 311 | |
| 312 | |
| 313 | # --------------------------------------------------------------------------- |
| 314 | # HIGH-152: Cached queryId validation & path traversal blocking |
| 315 | # --------------------------------------------------------------------------- |
| 316 | |
| 317 | |
| 318 | @pytest.mark.skipif(not HAS_NODE, reason="node is required") |
| 319 | class TestHigh152QueryIdValidation: |
| 320 | def test_parse_snapshot_rejects_traversal_and_proto_pollution(self): |
| 321 | script = textwrap.dedent( |
| 322 | """ |
| 323 | import { parseSnapshot, createRuntimeQueryIdStore } from './skills/last30days/scripts/lib/vendor/bird-search/lib/runtime-query-ids.js'; |
| 324 | |
| 325 | const raw = JSON.parse(`{ |
| 326 | "fetchedAt": "2026-11-23T00:00:00.000Z", |
| 327 | "ttlMs": 86400000, |
| 328 | "ids": { |
| 329 | "SearchTimeline": "../../1.1/statuses/update.json?status=pwned", |
| 330 | "CreateTweet": "abc123/CreateTweet#", |
| 331 | "UserTweets": "valid_Query-Id123", |
| 332 | "BadSpace": "abc def", |
| 333 | "BadQuery": "abc?x=1", |
| 334 | "__proto__": "polluted_id", |
| 335 | "constructor": "ctor_id", |
| 336 | "prototype": "proto_id" |
| 337 | }, |
| 338 | "discovery": { "pages": ["https://x.com/?lang=en"], "bundles": ["main.js"] } |
| 339 | }`); |
| 340 | |
| 341 | const snap = parseSnapshot(raw); |
| 342 | process.stdout.write(JSON.stringify({ |
| 343 | nullProto: Object.getPrototypeOf(snap.ids) === null, |
| 344 | keys: Object.keys(snap.ids), |
| 345 | userTweets: snap.ids.UserTweets ?? null, |
| 346 | searchTimeline: snap.ids.SearchTimeline ?? null, |
| 347 | toStringLookup: snap.ids.toString ?? null, |
| 348 | })); |
| 349 | """ |
| 350 | ) |
| 351 | res = _node_eval(script) |
| 352 | assert res.returncode == 0, res.stderr |
| 353 | data = json.loads(res.stdout) |
| 354 | assert data["nullProto"] is True |
| 355 | assert data["keys"] == ["UserTweets"] |
| 356 | assert data["userTweets"] == "valid_Query-Id123" |
| 357 | assert data["searchTimeline"] is None |
| 358 | assert data["toStringLookup"] is None |
| 359 | |
| 360 | def test_poisoned_cache_file_cannot_hijack_authenticated_post_url(self, tmp_path): |
| 361 | cache_file = tmp_path / "query-ids-cache.json" |
| 362 | cache_file.write_text( |
| 363 | json.dumps( |
| 364 | { |
| 365 | "fetchedAt": datetime.now(timezone.utc).isoformat(), |
| 366 | "ttlMs": 86_400_000, |
| 367 | "ids": { |
| 368 | "SearchTimeline": "../../1.1/statuses/update.json?status=pwned#", |
| 369 | }, |
| 370 | "discovery": {"pages": ["https://x.com/?lang=en"], "bundles": ["main.js"]}, |
| 371 | } |
| 372 | ), |
| 373 | encoding="utf-8", |
| 374 | ) |
| 375 | stub = tmp_path / "stub.mjs" |
| 376 | stub.write_text( |
| 377 | textwrap.dedent( |
| 378 | """ |
| 379 | globalThis.fetch = async (url) => { |
| 380 | process.stderr.write(`FETCH_URL=${String(url)}\\n`); |
| 381 | const body = {data: {search_by_raw_query: {search_timeline: {timeline: {instructions: []}}}}}; |
| 382 | return new Response(JSON.stringify(body), {status: 200, headers: {'content-type': 'application/json'}}); |
| 383 | }; |
| 384 | """ |
| 385 | ), |
| 386 | encoding="utf-8", |
| 387 | ) |
| 388 | env = os.environ.copy() |
| 389 | env.update( |
| 390 | AUTH_TOKEN="dummy-auth-token-1234", |
| 391 | CT0="dummy-ct0-token-5678", |
| 392 | BIRD_DISABLE_BROWSER_COOKIES="1", |
| 393 | BIRD_QUERY_IDS_CACHE=str(cache_file), |
| 394 | ) |
| 395 | res = subprocess.run( |
| 396 | ["node", "--import", stub.as_uri(), str(BIRD_MJS), "--count", "1", "--json", "--", "hello"], |
| 397 | cwd=REPO_ROOT, |
| 398 | env=env, |
| 399 | capture_output=True, |
| 400 | text=True, |
| 401 | check=False, |
| 402 | ) |
| 403 | assert res.returncode == 0, res.stderr |
| 404 | urls = [line.split("=", 1)[1] for line in res.stderr.splitlines() if line.startswith("FETCH_URL=")] |
| 405 | assert urls |
| 406 | for url in urls: |
| 407 | assert "statuses/update" not in url |
| 408 | assert ".." not in url |
| 409 | assert url.startswith("https://x.com/i/api/graphql/") |
| 410 | assert "/SearchTimeline?" in url |
| 411 | |
| 412 | def test_search_interpolation_site_skips_invalid_query_ids(self): |
| 413 | script = textwrap.dedent( |
| 414 | """ |
| 415 | import { TwitterClientBase } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js'; |
| 416 | import { withSearch } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-search.js'; |
| 417 | |
| 418 | const Client = withSearch(TwitterClientBase); |
| 419 | const seenUrls = []; |
| 420 | globalThis.fetch = async (url) => { |
| 421 | seenUrls.push(String(url)); |
| 422 | const body = {data: {search_by_raw_query: {search_timeline: {timeline: {instructions: []}}}}}; |
| 423 | return new Response(JSON.stringify(body), {status: 200, headers: {'content-type': 'application/json'}}); |
| 424 | }; |
| 425 | const client = new Client({ cookies: { authToken: 'dummy-auth-1234', ct0: 'dummy-ct0-5678' } }); |
| 426 | client.getSearchTimelineQueryIds = async () => [ |
| 427 | '../../1.1/statuses/update.json?status=hi#', |
| 428 | 'mutId/CreateTweet#', |
| 429 | 'M1jEez78PEfVfbQLvlWMvQ', |
| 430 | ]; |
| 431 | const res = await client.search('hello', 5); |
| 432 | process.stdout.write(JSON.stringify({ ok: res.success, seenUrls })); |
| 433 | """ |
| 434 | ) |
| 435 | res = _node_eval(script) |
| 436 | assert res.returncode == 0, res.stderr |
| 437 | data = json.loads(res.stdout) |
| 438 | assert data["ok"] is True |
| 439 | assert len(data["seenUrls"]) == 1 |
| 440 | assert "/M1jEez78PEfVfbQLvlWMvQ/SearchTimeline?" in data["seenUrls"][0] |
| 441 | |
| 442 | |
| 443 | # --------------------------------------------------------------------------- |
| 444 | # HIGH-153: Credential scrubbing in bird_x.py and vendored JS |
| 445 | # --------------------------------------------------------------------------- |
| 446 | |
| 447 | |
| 448 | class TestHigh153CredentialScrubbingPython: |
| 449 | def setup_method(self): |
| 450 | self._saved_creds = dict(bird_x._credentials) |
| 451 | self._saved_seen = set(bird_x._seen_secrets) |
| 452 | bird_x._credentials.clear() |
| 453 | bird_x._seen_secrets.clear() |
| 454 | |
| 455 | def teardown_method(self): |
| 456 | bird_x._credentials.clear() |
| 457 | bird_x._credentials.update(self._saved_creds) |
| 458 | bird_x._seen_secrets.clear() |
| 459 | bird_x._seen_secrets.update(self._saved_seen) |
| 460 | |
| 461 | def test_scrubs_both_injected_and_ambient_env_and_trimmed_variants(self, monkeypatch): |
| 462 | injected_auth = "fake-injected-auth-1111" |
| 463 | ambient_auth = " fake-ambient-auth-2222 " |
| 464 | ambient_tw_ct0 = " fake-twitter-ct0-3333 " |
| 465 | |
| 466 | bird_x.set_credentials(injected_auth, "fake-injected-ct0-4444") |
| 467 | monkeypatch.setenv("AUTH_TOKEN", ambient_auth) |
| 468 | monkeypatch.setenv("TWITTER_CT0", ambient_tw_ct0) |
| 469 | |
| 470 | msg = ( |
| 471 | f"failed: {injected_auth} / {ambient_auth.strip()} / " |
| 472 | f"{ambient_tw_ct0.strip()} / {ambient_auth}" |
| 473 | ) |
| 474 | scrubbed = bird_x._scrub_credentials(msg) |
| 475 | assert injected_auth not in scrubbed |
| 476 | assert ambient_auth.strip() not in scrubbed |
| 477 | assert ambient_tw_ct0.strip() not in scrubbed |
| 478 | assert "<redacted>" in scrubbed |
| 479 | |
| 480 | def test_scrubs_retired_failover_credentials(self): |
| 481 | retired_auth = "fake-safari-retired-auth-0001" |
| 482 | retired_ct0 = "fake-safari-retired-ct0-0002" |
| 483 | live_auth = "fake-chrome-live-auth-0003" |
| 484 | live_ct0 = "fake-chrome-live-ct0-0004" |
| 485 | |
| 486 | bird_x.set_credentials(retired_auth, retired_ct0) |
| 487 | bird_x.set_credentials(live_auth, live_ct0) |
| 488 | |
| 489 | scrubbed = bird_x._scrub_credentials( |
| 490 | f"first attempt rejected auth={retired_auth} ct0={retired_ct0} then {live_auth}" |
| 491 | ) |
| 492 | assert retired_auth not in scrubbed |
| 493 | assert retired_ct0 not in scrubbed |
| 494 | assert live_auth not in scrubbed |
| 495 | |
| 496 | def test_primary_search_paths_scrub_stderr_json_error_and_non_json_logs(self): |
| 497 | secret_auth = "fake-primary-auth-secret-9999" |
| 498 | secret_ct0 = "fake-primary-ct0-secret-8888" |
| 499 | bird_x.set_credentials(secret_auth, secret_ct0) |
| 500 | |
| 501 | # 1) Non-zero exit with empty stdout -> stderr scrubbed |
| 502 | proc_stderr = SubprocResult( |
| 503 | returncode=1, |
| 504 | stdout="", |
| 505 | stderr=f"Headers.append: '{secret_ct0}' auth={secret_auth}", |
| 506 | ) |
| 507 | with mock.patch.object(bird_x, "_invoke_bird_subprocess", return_value=(proc_stderr, None)): |
| 508 | res = bird_x._run_bird_search_once("test", count=5, timeout=10) |
| 509 | assert secret_auth not in res["error"] |
| 510 | assert secret_ct0 not in res["error"] |
| 511 | assert "<redacted>" in res["error"] |
| 512 | |
| 513 | # 2) JSON stdout with error key -> parsed["error"] scrubbed |
| 514 | proc_json_err = SubprocResult( |
| 515 | returncode=1, |
| 516 | stdout=json.dumps({"error": f"invalid header {secret_auth} {secret_ct0}", "items": []}), |
| 517 | stderr="", |
| 518 | ) |
| 519 | with mock.patch.object(bird_x, "_invoke_bird_subprocess", return_value=(proc_json_err, None)): |
| 520 | res = bird_x._run_bird_search_once("test", count=5, timeout=10) |
| 521 | assert secret_auth not in res["error"] |
| 522 | assert secret_ct0 not in res["error"] |
| 523 | |
| 524 | # 3) Non-JSON stdout with secret straddling char 80 -> log output scrubbed before slicing |
| 525 | prefix = "x" * 65 |
| 526 | non_json = f"{prefix}{secret_auth} trailing html" |
| 527 | proc_non_json = SubprocResult(returncode=0, stdout=non_json, stderr="") |
| 528 | logged = [] |
| 529 | with mock.patch.object( |
| 530 | bird_x, "_invoke_bird_subprocess", side_effect=[(proc_non_json, None), (proc_non_json, None)] |
| 531 | ), mock.patch.object(bird_x.time, "sleep"), mock.patch.object( |
| 532 | bird_x.log, "source_log", side_effect=lambda src, msg, **kw: logged.append(msg) |
| 533 | ): |
| 534 | res = bird_x._run_bird_search_once("test", count=5, timeout=10) |
| 535 | combined_logs = "\n".join(logged) |
| 536 | assert secret_auth not in combined_logs |
| 537 | assert secret_auth[:12] not in combined_logs |
| 538 | assert secret_auth not in res["error"] |
| 539 | |
| 540 | # 4) _invoke_bird_subprocess unexpected exception -> str(e) scrubbed |
| 541 | with mock.patch.object( |
| 542 | bird_x.subproc, "run_with_timeout", side_effect=RuntimeError(f"boom {secret_auth}") |
| 543 | ): |
| 544 | _, err_dict = bird_x._invoke_bird_subprocess("test", count=5, timeout=10) |
| 545 | assert secret_auth not in err_dict["error"] |
| 546 | assert "<redacted>" in err_dict["error"] |
| 547 | |
| 548 | # 5) parse_bird_response -> logged response["error"] scrubbed |
| 549 | err_buf = io.StringIO() |
| 550 | with redirect_stderr(err_buf): |
| 551 | bird_x.parse_bird_response({"error": f"bad token {secret_auth} {secret_ct0}"}) |
| 552 | assert secret_auth not in err_buf.getvalue() |
| 553 | assert secret_ct0 not in err_buf.getvalue() |
| 554 | |
| 555 | |
| 556 | @pytest.mark.skipif(not HAS_NODE, reason="node is required") |
| 557 | class TestHigh153CredentialScrubbingJS: |
| 558 | def test_js_fetch_error_never_echoes_secrets_or_header_values(self, tmp_path): |
| 559 | fake_auth = "fake-js-auth-secret-77777" |
| 560 | fake_ct0 = "fake-js-ct0-secret-66666" |
| 561 | stub = tmp_path / "stub-err.mjs" |
| 562 | stub.write_text( |
| 563 | textwrap.dedent( |
| 564 | f""" |
| 565 | globalThis.fetch = async () => {{ |
| 566 | throw new TypeError('Headers.append: "auth_token={fake_auth}; ct0={fake_ct0}" is an invalid header value.'); |
| 567 | }}; |
| 568 | """ |
| 569 | ), |
| 570 | encoding="utf-8", |
| 571 | ) |
| 572 | env = os.environ.copy() |
| 573 | env.update( |
| 574 | AUTH_TOKEN=fake_auth, |
| 575 | CT0=fake_ct0, |
| 576 | BIRD_DISABLE_BROWSER_COOKIES="1", |
| 577 | ) |
| 578 | res = subprocess.run( |
| 579 | ["node", "--import", stub.as_uri(), str(BIRD_MJS), "--count", "1", "--json", "--", "hello"], |
| 580 | cwd=REPO_ROOT, |
| 581 | env=env, |
| 582 | capture_output=True, |
| 583 | text=True, |
| 584 | check=False, |
| 585 | ) |
| 586 | assert res.returncode == 1 |
| 587 | combined = res.stdout + res.stderr |
| 588 | assert fake_auth not in combined |
| 589 | assert fake_ct0 not in combined |
| 590 | payload = json.loads(res.stdout) |
| 591 | assert "<redacted>" in payload["error"] |
| 592 | |
| 593 | def test_custom_cookie_header_extra_cookies_are_fully_redacted(self): |
| 594 | script = textwrap.dedent( |
| 595 | """ |
| 596 | import { redactSecrets } from './skills/last30days/scripts/lib/vendor/bird-search/lib/cookies.js'; |
| 597 | import { TwitterClientBase } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js'; |
| 598 | |
| 599 | const authToken = 'fake-auth-token-1111'; |
| 600 | const ct0 = 'fake-ct0-token-2222'; |
| 601 | const cookieHeader = `auth_token=${authToken}; ct0=${ct0}; twid=u%3D12345; kdt=supersecretkdt`; |
| 602 | const client = new TwitterClientBase({ cookies: { authToken, ct0, cookieHeader } }); |
| 603 | const rawErr = `Upstream rejected request with Cookie: ${cookieHeader} (HTTP 403)`; |
| 604 | |
| 605 | const viaClient = client.redactError(rawErr); |
| 606 | const viaHelper = redactSecrets(rawErr, [authToken, ct0, cookieHeader]); |
| 607 | process.stdout.write(JSON.stringify({ viaClient, viaHelper })); |
| 608 | """ |
| 609 | ) |
| 610 | res = _node_eval(script) |
| 611 | assert res.returncode == 0, res.stderr |
| 612 | data = json.loads(res.stdout) |
| 613 | for out in (data["viaClient"], data["viaHelper"]): |
| 614 | assert "<redacted>" in out |
| 615 | for secret in ("fake-auth-token-1111", "fake-ct0-token-2222", "twid", "u%3D12345", "kdt", "supersecretkdt"): |
| 616 | assert secret not in out, f"leaked {secret!r} in {out!r}" |
| 617 | |
| 618 | |
| 619 | # --------------------------------------------------------------------------- |
| 620 | # HIGH-154: Cookie delimiter & CRLF/control-char validation |
| 621 | # --------------------------------------------------------------------------- |
| 622 | |
| 623 | |
| 624 | @pytest.mark.skipif(not HAS_NODE, reason="node is required") |
| 625 | class TestHigh154CookieValidation: |
| 626 | @pytest.mark.parametrize( |
| 627 | "bad_auth,bad_ct0", |
| 628 | [ |
| 629 | ("fake-auth-1111; ct0=evil", "fake-ct0-2222"), |
| 630 | ("fake-auth-1111,extra", "fake-ct0-2222"), |
| 631 | ("fake-auth-1111", "fake-ct0-2222\r\nX-Injected: 1"), |
| 632 | ("fake-auth-1111\n", "fake-ct0-2222"), |
| 633 | ("fake-auth-1111", "fake-ct0-2222\r"), |
| 634 | ("fake-auth-1111", "fake-ct0-2222\x00tail"), |
| 635 | ("fake auth 1111", "fake-ct0-2222"), |
| 636 | ("fake-auth-1111", "fake-ct0-2222\u00e9"), |
| 637 | ('fake"auth1111', "fake-ct0-2222"), |
| 638 | ("fake\\auth1111", "fake-ct0-2222"), |
| 639 | ], |
| 640 | ) |
| 641 | def test_cookies_and_client_reject_invalid_tokens_without_echoing_secrets(self, bad_auth, bad_ct0): |
| 642 | script = textwrap.dedent( |
| 643 | """ |
| 644 | import { resolveCredentials } from './skills/last30days/scripts/lib/vendor/bird-search/lib/cookies.js'; |
| 645 | import { TwitterClientBase } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js'; |
| 646 | |
| 647 | const badAuth = JSON.parse(process.env.TEST_BAD_AUTH); |
| 648 | const badCt0 = JSON.parse(process.env.TEST_BAD_CT0); |
| 649 | |
| 650 | let resolveErr = null; |
| 651 | try { |
| 652 | await resolveCredentials({ authToken: badAuth, ct0: badCt0 }); |
| 653 | } catch (e) { |
| 654 | resolveErr = e.message; |
| 655 | } |
| 656 | |
| 657 | let ctorErr = null; |
| 658 | try { |
| 659 | new TwitterClientBase({ cookies: { authToken: badAuth, ct0: badCt0 } }); |
| 660 | } catch (e) { |
| 661 | ctorErr = e.message; |
| 662 | } |
| 663 | |
| 664 | process.stdout.write(JSON.stringify({ resolveErr, ctorErr })); |
| 665 | """ |
| 666 | ) |
| 667 | res = _node_eval( |
| 668 | script, |
| 669 | env={ |
| 670 | "TEST_BAD_AUTH": json.dumps(bad_auth), |
| 671 | "TEST_BAD_CT0": json.dumps(bad_ct0), |
| 672 | "BIRD_DISABLE_BROWSER_COOKIES": "1", |
| 673 | }, |
| 674 | ) |
| 675 | assert res.returncode == 0, res.stderr |
| 676 | data = json.loads(res.stdout) |
| 677 | assert data["resolveErr"] == "Invalid auth_token/ct0 format" |
| 678 | assert data["ctorErr"] == "Invalid auth_token/ct0 format" |
| 679 | |
| 680 | def test_client_rejects_invalid_cookie_header_with_crlf_or_nul(self): |
| 681 | script = textwrap.dedent( |
| 682 | """ |
| 683 | import { TwitterClientBase } from './skills/last30days/scripts/lib/vendor/bird-search/lib/twitter-client-base.js'; |
| 684 | const results = []; |
| 685 | for (const header of [ |
| 686 | 'auth_token=good; ct0=good\\r\\nX-Evil: 1', |
| 687 | 'auth_token=good; ct0=good\\n', |
| 688 | 'auth_token=good; ct0=good\\0', |
| 689 | 'auth_token=good; ct0=good\\u00e9', |
| 690 | ]) { |
| 691 | try { |
| 692 | new TwitterClientBase({ cookies: { authToken: 'good-auth', ct0: 'good-ct0', cookieHeader: header } }); |
| 693 | results.push('accepted'); |
| 694 | } catch (e) { |
| 695 | results.push(e.message); |
| 696 | } |
| 697 | } |
| 698 | process.stdout.write(JSON.stringify(results)); |
| 699 | """ |
| 700 | ) |
| 701 | res = _node_eval(script) |
| 702 | assert res.returncode == 0, res.stderr |
| 703 | assert json.loads(res.stdout) == ["Invalid auth_token/ct0 format"] * 4 |
| 704 | |
| 705 | def test_cli_fails_fast_with_generic_error_on_malformed_env_token(self): |
| 706 | bad_secret = "fake-secret-value; ct0=injected-9999" |
| 707 | env = os.environ.copy() |
| 708 | env.update( |
| 709 | AUTH_TOKEN=bad_secret, |
| 710 | CT0="fake-valid-ct0-1234", |
| 711 | BIRD_DISABLE_BROWSER_COOKIES="1", |
| 712 | ) |
| 713 | for cli_args in (["--check"], ["--whoami"], ["--count", "1", "--json", "--", "hello"]): |
| 714 | res = subprocess.run( |
| 715 | ["node", str(BIRD_MJS), *cli_args], |
| 716 | cwd=REPO_ROOT, |
| 717 | env=env, |
| 718 | capture_output=True, |
| 719 | text=True, |
| 720 | check=False, |
| 721 | ) |
| 722 | assert res.returncode == 1 |
| 723 | combined = res.stdout + res.stderr |
| 724 | assert "Invalid auth_token/ct0 format" in combined |
| 725 | assert bad_secret not in combined |
| 726 | assert "fake-secret-value" not in combined |
| 727 | |
| 728 | def test_malformed_first_browser_cookie_warns_and_fails_over_to_next_browser(self, tmp_path): |
| 729 | loader = tmp_path / "sweet-cookie-loader.mjs" |
| 730 | loader.write_text( |
| 731 | textwrap.dedent( |
| 732 | """ |
| 733 | export async function resolve(specifier, context, nextResolve) { |
| 734 | if (specifier === '@steipete/sweet-cookie') { |
| 735 | return { url: 'sweet-cookie-stub://mock', shortCircuit: true }; |
| 736 | } |
| 737 | return nextResolve(specifier, context); |
| 738 | } |
| 739 | export async function load(url, context, nextLoad) { |
| 740 | if (url === 'sweet-cookie-stub://mock') { |
| 741 | return { |
| 742 | format: 'module', |
| 743 | shortCircuit: true, |
| 744 | source: ` |
| 745 | export async function getCookies(options) { |
| 746 | const browser = options.browsers?.[0]; |
| 747 | if (browser === 'safari') { |
| 748 | return { |
| 749 | cookies: [ |
| 750 | { name: 'auth_token', value: 'bad-safari-secret; evil=1', domain: 'x.com' }, |
| 751 | { name: 'ct0', value: 'safari-ct0-1234', domain: 'x.com' }, |
| 752 | ], |
| 753 | warnings: [], |
| 754 | }; |
| 755 | } |
| 756 | if (browser === 'chrome') { |
| 757 | return { |
| 758 | cookies: [ |
| 759 | { name: 'auth_token', value: 'good-chrome-auth-5678', domain: 'x.com' }, |
| 760 | { name: 'ct0', value: 'good-chrome-ct0-9012', domain: 'x.com' }, |
| 761 | ], |
| 762 | warnings: [], |
| 763 | }; |
| 764 | } |
| 765 | return { cookies: [], warnings: [] }; |
| 766 | } |
| 767 | `, |
| 768 | }; |
| 769 | } |
| 770 | return nextLoad(url, context); |
| 771 | } |
| 772 | """ |
| 773 | ), |
| 774 | encoding="utf-8", |
| 775 | ) |
| 776 | register_file = tmp_path / "register-loader.mjs" |
| 777 | register_file.write_text( |
| 778 | "import { register } from 'node:module';\n" |
| 779 | f"register({json.dumps(loader.as_uri())});\n", |
| 780 | encoding="utf-8", |
| 781 | ) |
| 782 | env = os.environ.copy() |
| 783 | for key in ( |
| 784 | "AUTH_TOKEN", |
| 785 | "CT0", |
| 786 | "TWITTER_AUTH_TOKEN", |
| 787 | "TWITTER_CT0", |
| 788 | "BIRD_DISABLE_BROWSER_COOKIES", |
| 789 | "LAST30DAYS_DISABLE_BROWSER_COOKIES", |
| 790 | ): |
| 791 | env.pop(key, None) |
| 792 | |
| 793 | script = textwrap.dedent( |
| 794 | """ |
| 795 | import { resolveCredentials } from './skills/last30days/scripts/lib/vendor/bird-search/lib/cookies.js'; |
| 796 | const res = await resolveCredentials({ cookieSource: ['safari', 'chrome'] }); |
| 797 | process.stdout.write(JSON.stringify(res)); |
| 798 | """ |
| 799 | ) |
| 800 | res = subprocess.run( |
| 801 | ["node", "--import", register_file.as_uri(), "--input-type=module", "-e", script], |
| 802 | cwd=REPO_ROOT, |
| 803 | env=env, |
| 804 | capture_output=True, |
| 805 | text=True, |
| 806 | check=False, |
| 807 | ) |
| 808 | assert res.returncode == 0, res.stderr |
| 809 | data = json.loads(res.stdout) |
| 810 | assert data["cookies"]["authToken"] == "good-chrome-auth-5678" |
| 811 | assert data["cookies"]["ct0"] == "good-chrome-ct0-9012" |
| 812 | assert data["cookies"]["source"] == "Chrome default profile" |
| 813 | assert "Invalid auth_token/ct0 format" in data["warnings"] |
| 814 | joined_warnings = "\n".join(data["warnings"]) |
| 815 | assert "bad-safari-secret" not in joined_warnings |
| 816 | assert "evil=1" not in joined_warnings |
| 817 | assert "bad-safari-secret" not in res.stderr |
| 818 | |
| 819 | |
| 820 | # --------------------------------------------------------------------------- |
| 821 | # HIGH-155: Leading `-` queries & CLI option parsing across Python -> Node |
| 822 | # --------------------------------------------------------------------------- |
| 823 | |
| 824 | |
| 825 | class TestHigh155CliOptionBoundary: |
| 826 | def test_python_invocations_place_flags_before_double_dash_and_query_after(self): |
| 827 | cmds = [] |
| 828 | |
| 829 | def fake_run(cmd, timeout=None, env=None, **_kwargs): |
| 830 | cmds.append(cmd) |
| 831 | return SubprocResult(returncode=0, stdout="[]", stderr="") |
| 832 | |
| 833 | with mock.patch.object(bird_x.subproc, "run_with_timeout", side_effect=fake_run): |
| 834 | bird_x._invoke_bird_subprocess("--check", count=10, timeout=15, top=True) |
| 835 | bird_x._invoke_bird_subprocess("-is:retweet claude", count=5, timeout=15, top=False) |
| 836 | bird_x.search_handles(["alice"], "topic", "2026-05-01", count_per=3) |
| 837 | bird_x.search_mentions(["alice"], "2026-05-01", count_per=3) |
| 838 | |
| 839 | assert len(cmds) == 4 |
| 840 | for cmd in cmds: |
| 841 | assert "--" in cmd |
| 842 | sep = cmd.index("--") |
| 843 | assert sep == len(cmd) - 2 |
| 844 | assert "--json" in cmd[:sep] |
| 845 | assert "--count" in cmd[:sep] |
| 846 | assert cmds[0][-1] == "--check" |
| 847 | assert "--top" in cmds[0][: cmds[0].index("--")] |
| 848 | assert cmds[1][-1] == "-is:retweet claude" |
| 849 | assert "--top" not in cmds[1][: cmds[1].index("--")] |
| 850 | |
| 851 | @pytest.mark.skipif(not HAS_NODE, reason="node is required") |
| 852 | @pytest.mark.parametrize( |
| 853 | "query", |
| 854 | [ |
| 855 | "-is:retweet claude", |
| 856 | "-crypto news", |
| 857 | "--verbose curl", |
| 858 | "-10% inflation", |
| 859 | "--check", |
| 860 | "--whoami", |
| 861 | "--count", |
| 862 | "-n", |
| 863 | ], |
| 864 | ) |
| 865 | def test_bird_search_mjs_accepts_leading_dash_and_flag_named_queries_after_double_dash( |
| 866 | self, tmp_path, query |
| 867 | ): |
| 868 | stub = tmp_path / "stub-q.mjs" |
| 869 | stub.write_text( |
| 870 | textwrap.dedent( |
| 871 | """ |
| 872 | globalThis.fetch = async (url) => { |
| 873 | const u = new URL(String(url)); |
| 874 | const v = JSON.parse(u.searchParams.get('variables')); |
| 875 | process.stderr.write(`RAW_QUERY=${JSON.stringify(v.rawQuery)}\\n`); |
| 876 | const body = {data: {search_by_raw_query: {search_timeline: {timeline: {instructions: []}}}}}; |
| 877 | return new Response(JSON.stringify(body), {status: 200, headers: {'content-type': 'application/json'}}); |
| 878 | }; |
| 879 | """ |
| 880 | ), |
| 881 | encoding="utf-8", |
| 882 | ) |
| 883 | env = os.environ.copy() |
| 884 | env.update( |
| 885 | AUTH_TOKEN="dummy-auth-token-1234", |
| 886 | CT0="dummy-ct0-token-5678", |
| 887 | BIRD_DISABLE_BROWSER_COOKIES="1", |
| 888 | ) |
| 889 | res = subprocess.run( |
| 890 | ["node", "--import", stub.as_uri(), str(BIRD_MJS), "--count", "3", "--json", "--", query], |
| 891 | cwd=REPO_ROOT, |
| 892 | env=env, |
| 893 | capture_output=True, |
| 894 | text=True, |
| 895 | check=False, |
| 896 | ) |
| 897 | assert res.returncode == 0, res.stderr |
| 898 | assert json.loads(res.stdout) == [] |
| 899 | seen = [ |
| 900 | json.loads(line.split("=", 1)[1]) |
| 901 | for line in res.stderr.splitlines() |
| 902 | if line.startswith("RAW_QUERY=") |
| 903 | ] |
| 904 | assert seen == [query] |
| 905 | |
| 906 | @pytest.mark.skipif(not HAS_NODE, reason="node is required") |
| 907 | @pytest.mark.parametrize( |
| 908 | "bad_args", |
| 909 | [ |
| 910 | ["--count", "abc", "--json", "--", "hello"], |
| 911 | ["--count", "0", "--json", "--", "hello"], |
| 912 | ["--count", "-5", "--json", "--", "hello"], |
| 913 | ["--count", "10abc", "--json", "--", "hello"], |
| 914 | ["-n", "NaN", "--json", "--", "hello"], |
| 915 | ["--count"], |
| 916 | ["--unknown-flag", "hello"], |
| 917 | ], |
| 918 | ) |
| 919 | def test_bird_search_mjs_rejects_invalid_counts_and_unknown_flags(self, bad_args): |
| 920 | env = os.environ.copy() |
| 921 | env.update( |
| 922 | AUTH_TOKEN="dummy-auth-token-1234", |
| 923 | CT0="dummy-ct0-token-5678", |
| 924 | BIRD_DISABLE_BROWSER_COOKIES="1", |
| 925 | ) |
| 926 | res = subprocess.run( |
| 927 | ["node", str(BIRD_MJS), *bad_args], |
| 928 | cwd=REPO_ROOT, |
| 929 | env=env, |
| 930 | capture_output=True, |
| 931 | text=True, |
| 932 | check=False, |
| 933 | ) |
| 934 | assert res.returncode == 1 |
| 935 | assert res.stdout == "" |
| 936 | assert res.stderr.strip() != "" |
| 937 | |
| 938 | @pytest.mark.skipif(not HAS_NODE, reason="node is required") |
| 939 | def test_unknown_option_does_not_echo_inline_token_to_stderr(self): |
| 940 | env = os.environ.copy() |
| 941 | env.update( |
| 942 | AUTH_TOKEN="dummy-auth-token-1234", |
| 943 | CT0="dummy-ct0-token-5678", |
| 944 | BIRD_DISABLE_BROWSER_COOKIES="1", |
| 945 | ) |
| 946 | inline_secret = "secret_inline_token_12345" |
| 947 | res = subprocess.run( |
| 948 | ["node", str(BIRD_MJS), f"--auth-token={inline_secret}", "hello"], |
| 949 | cwd=REPO_ROOT, |
| 950 | env=env, |
| 951 | capture_output=True, |
| 952 | text=True, |
| 953 | check=False, |
| 954 | ) |
| 955 | assert res.returncode == 1 |
| 956 | assert res.stdout == "" |
| 957 | assert "Unknown option" in res.stderr |
| 958 | assert inline_secret not in res.stderr |
| 959 | assert "--auth-token" not in res.stderr |
| 960 |