| 1 | """X browser-session failover: an expired session in an earlier browser must |
| 2 | not shadow a live session in a later browser (FROM_BROWSER=auto).""" |
| 3 | |
| 4 | from unittest import mock |
| 5 | |
| 6 | import pytest |
| 7 | |
| 8 | from lib import bird_x, env, health |
| 9 | from lib.subproc import SubprocResult |
| 10 | |
| 11 | DEAD = {"auth_token": "dead-session-token-0000", "ct0": "dead-ct0-0000000000"} |
| 12 | LIVE = {"auth_token": "live-session-token-1111", "ct0": "live-ct0-1111111111"} |
| 13 | |
| 14 | SEARCH_500 = '{"error": "Internal server error", "items": []}' |
| 15 | SEARCH_401 = '{"error": "HTTP 401: {\\"errors\\":[{\\"message\\":\\"Could not authenticate you\\",\\"code\\":32}]}", "items": []}' |
| 16 | SEARCH_OK = '[{"id": "1", "text": "tweet"}]' |
| 17 | |
| 18 | |
| 19 | @pytest.fixture(autouse=True) |
| 20 | def _reset_bird_state(): |
| 21 | saved = dict(bird_x._credentials) |
| 22 | bird_x._credentials.clear() |
| 23 | bird_x.set_session_failover(None, None) |
| 24 | yield |
| 25 | bird_x._credentials.clear() |
| 26 | bird_x._credentials.update(saved) |
| 27 | bird_x.set_session_failover(None, None) |
| 28 | |
| 29 | |
| 30 | def _config(**overrides): |
| 31 | cfg = { |
| 32 | "AUTH_TOKEN": None, |
| 33 | "CT0": None, |
| 34 | "TRUTHSOCIAL_TOKEN": None, |
| 35 | "FROM_BROWSER": "auto", |
| 36 | "BROWSER_CONSENT": "true", |
| 37 | "SETUP_COMPLETE": None, |
| 38 | } |
| 39 | cfg.update(overrides) |
| 40 | return cfg |
| 41 | |
| 42 | |
| 43 | def _browser_cookies(by_browser): |
| 44 | def fake(browser, domain, names): |
| 45 | if domain != ".x.com": |
| 46 | return None |
| 47 | return by_browser.get(browser) |
| 48 | return fake |
| 49 | |
| 50 | |
| 51 | def _bird_outputs(*stdouts): |
| 52 | return [(SubprocResult(returncode=0, stdout=s, stderr=""), None) for s in stdouts] |
| 53 | |
| 54 | |
| 55 | def _discover(cfg, by_browser): |
| 56 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies(by_browser)): |
| 57 | env._apply_browser_extract(cfg) |
| 58 | return cfg |
| 59 | |
| 60 | |
| 61 | class TestEnvBookkeeping: |
| 62 | def test_records_source_browser_and_remaining_browsers(self): |
| 63 | cfg = _discover(_config(), {"safari": DEAD, "chrome": LIVE}) |
| 64 | assert cfg["AUTH_TOKEN"] == DEAD["auth_token"] |
| 65 | state = cfg[env.X_SESSION_STATE_KEY] |
| 66 | assert state["browser"] == "safari" |
| 67 | assert state["remaining"][0] == "chrome" |
| 68 | assert "firefox" not in state["remaining"] |
| 69 | |
| 70 | def test_explicit_env_pair_records_nothing(self): |
| 71 | cfg = _discover(_config(AUTH_TOKEN="x" * 20, CT0="y" * 20), {"safari": DEAD}) |
| 72 | assert env.X_SESSION_STATE_KEY not in cfg |
| 73 | |
| 74 | def test_next_pair_skips_incomplete_and_same_session(self): |
| 75 | cfg = _discover(_config(), {"safari": DEAD, "chrome": {"auth_token": DEAD["auth_token"], "ct0": "z" * 12}, |
| 76 | "brave": {"ct0": "only-ct0"}, "edge": LIVE}) |
| 77 | with mock.patch("lib.cookie_extract.extract_cookies", |
| 78 | side_effect=_browser_cookies({"chrome": {"auth_token": DEAD["auth_token"], "ct0": "z" * 12}, |
| 79 | "brave": {"ct0": "only-ct0"}, "edge": LIVE})): |
| 80 | pair = env.next_x_browser_pair(cfg) |
| 81 | assert pair == (LIVE["auth_token"], LIVE["ct0"], "edge") |
| 82 | assert cfg["AUTH_TOKEN"] == LIVE["auth_token"] |
| 83 | assert cfg[env.X_SESSION_STATE_KEY]["browser"] == "edge" |
| 84 | |
| 85 | def test_next_pair_none_when_exhausted(self): |
| 86 | cfg = _discover(_config(), {"safari": DEAD}) |
| 87 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies({})): |
| 88 | assert env.next_x_browser_pair(cfg) is None |
| 89 | assert env.next_x_browser_pair(cfg) is None |
| 90 | |
| 91 | def test_next_pair_never_replaces_non_browser_session(self): |
| 92 | cfg = _config(AUTH_TOKEN="a" * 20, CT0="b" * 20, _AUTH_TOKEN_SOURCE="agentcookie", |
| 93 | **{env.X_SESSION_STATE_KEY: {"browser": "safari", "remaining": ["chrome"], |
| 94 | "rejected": set(), "auth_token": "a" * 20, "ct0": "b" * 20}}) |
| 95 | with mock.patch("lib.cookie_extract.extract_cookies") as extract: |
| 96 | assert env.next_x_browser_pair(cfg) is None |
| 97 | extract.assert_not_called() |
| 98 | |
| 99 | def test_inject_registers_failover_only_for_browser_sessions(self): |
| 100 | cfg = _config(AUTH_TOKEN="a" * 20, CT0="b" * 20, _AUTH_TOKEN_SOURCE="env") |
| 101 | env._inject_bird_credentials(cfg) |
| 102 | assert bird_x._next_session is None |
| 103 | cfg = _discover(_config(), {"safari": DEAD}) |
| 104 | env._inject_bird_credentials(cfg) |
| 105 | assert bird_x._session_browser == "safari" |
| 106 | assert bird_x._next_session is not None |
| 107 | |
| 108 | |
| 109 | class TestBirdFailover: |
| 110 | def _inject(self, by_browser): |
| 111 | cfg = _discover(_config(), by_browser) |
| 112 | env._inject_bird_credentials(cfg) |
| 113 | return cfg |
| 114 | |
| 115 | def test_stale_first_browser_fails_over_to_live_session(self): |
| 116 | cfg = self._inject({"safari": DEAD, "chrome": LIVE}) |
| 117 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies({"chrome": LIVE})), \ |
| 118 | mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=_bird_outputs(SEARCH_500, SEARCH_OK)) as run: |
| 119 | response = bird_x._run_bird_search("kanye", count=10, timeout=30) |
| 120 | assert response["items"] == [{"id": "1", "text": "tweet"}] |
| 121 | assert run.call_count == 2 |
| 122 | assert bird_x._credentials["AUTH_TOKEN"] == LIVE["auth_token"] |
| 123 | assert cfg[env.X_SESSION_STATE_KEY]["browser"] == "chrome" |
| 124 | |
| 125 | def test_switched_session_sticks_for_later_searches(self): |
| 126 | self._inject({"safari": DEAD, "chrome": LIVE}) |
| 127 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies({"chrome": LIVE})) as extract, \ |
| 128 | mock.patch.object(bird_x, "_invoke_bird_subprocess", |
| 129 | side_effect=_bird_outputs(SEARCH_401, SEARCH_OK, SEARCH_OK)): |
| 130 | bird_x._run_bird_search("one", count=10, timeout=30) |
| 131 | bird_x._run_bird_search("two", count=10, timeout=30) |
| 132 | assert extract.call_count == 1 |
| 133 | |
| 134 | def test_rejected_session_without_alternate_is_auth_failed(self): |
| 135 | self._inject({"safari": DEAD}) |
| 136 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies({})), \ |
| 137 | mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=_bird_outputs(SEARCH_401)): |
| 138 | response = bird_x._run_bird_search("kanye", count=10, timeout=30) |
| 139 | assert "session rejected (cookies from safari)" in response["error"] |
| 140 | assert bird_x.classify_run_failure(response["error"]) == health.AUTH_FAILED |
| 141 | |
| 142 | def test_internal_error_without_alternate_hints_but_stays_generic(self): |
| 143 | self._inject({"safari": DEAD}) |
| 144 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies({})), \ |
| 145 | mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=_bird_outputs(SEARCH_500)): |
| 146 | response = bird_x._run_bird_search("kanye", count=10, timeout=30) |
| 147 | assert response["error"].startswith("Internal server error") |
| 148 | assert "safari session" in response["error"] |
| 149 | assert bird_x.classify_run_failure(response["error"]) != health.AUTH_FAILED |
| 150 | |
| 151 | def test_no_failover_registered_leaves_error_untouched(self): |
| 152 | bird_x.set_credentials("a" * 20, "b" * 20) |
| 153 | with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=_bird_outputs(SEARCH_500)) as run: |
| 154 | response = bird_x._run_bird_search("kanye", count=10, timeout=30) |
| 155 | assert response["error"] == "Internal server error" |
| 156 | assert run.call_count == 1 |
| 157 | |
| 158 | def test_unrelated_error_does_not_read_other_browsers(self): |
| 159 | self._inject({"safari": DEAD, "chrome": LIVE}) |
| 160 | timeout_error = (None, {"error": "Search timed out after 30s", "items": []}) |
| 161 | with mock.patch("lib.cookie_extract.extract_cookies") as extract, \ |
| 162 | mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=[timeout_error]): |
| 163 | response = bird_x._run_bird_search("kanye", count=10, timeout=30) |
| 164 | assert response["error"] == "Search timed out after 30s" |
| 165 | extract.assert_not_called() |
| 166 | |
| 167 | def test_failover_respects_exhausted_deadline(self): |
| 168 | self._inject({"safari": DEAD, "chrome": LIVE}) |
| 169 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies({"chrome": LIVE})) as extract, \ |
| 170 | mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=_bird_outputs(SEARCH_500)) as run, \ |
| 171 | mock.patch.object(bird_x, "_clamped_bird_timeout", return_value=None): |
| 172 | response = bird_x._run_bird_search("kanye", count=10, timeout=30, deadline=1.0) |
| 173 | assert response["error"].startswith("Internal server error") |
| 174 | assert run.call_count == 1 |
| 175 | assert extract.call_count == 0 |
| 176 | |
| 177 | |
| 178 | class TestGreptileRegressions: |
| 179 | def test_config_copy_cannot_reinject_rejected_session(self): |
| 180 | """pipeline.run searches on dict(config); a later phase reuses config.""" |
| 181 | cfg = _discover(_config(), {"safari": DEAD, "chrome": LIVE}) |
| 182 | run_copy = dict(cfg) |
| 183 | env._inject_bird_credentials(run_copy) |
| 184 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies({"chrome": LIVE})), \ |
| 185 | mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=_bird_outputs(SEARCH_500, SEARCH_OK)): |
| 186 | bird_x._run_bird_search("kanye", count=10, timeout=30) |
| 187 | assert cfg["AUTH_TOKEN"] == DEAD["auth_token"] # the original copy is stale |
| 188 | env._inject_bird_credentials(cfg) # supplemental phase re-injects |
| 189 | assert bird_x._credentials["AUTH_TOKEN"] == LIVE["auth_token"] |
| 190 | |
| 191 | def test_rejected_sessions_are_never_retried(self): |
| 192 | """Browser order A, B, A, C: after A and B fail, go straight to C.""" |
| 193 | b_pair = {"auth_token": "second-dead-token-2222", "ct0": "second-dead-ct0-22"} |
| 194 | c_pair = {"auth_token": "third-live-token-3333", "ct0": "third-live-ct0-333"} |
| 195 | cfg = _discover(_config(FROM_BROWSER="safari,chrome,brave,edge"), {"safari": DEAD}) |
| 196 | env._inject_bird_credentials(cfg) |
| 197 | others = {"chrome": b_pair, "brave": DEAD, "edge": c_pair} |
| 198 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=_browser_cookies(others)), \ |
| 199 | mock.patch.object(bird_x, "_invoke_bird_subprocess", |
| 200 | side_effect=_bird_outputs(SEARCH_401, SEARCH_401, SEARCH_OK)) as run: |
| 201 | response = bird_x._run_bird_search("kanye", count=10, timeout=30) |
| 202 | assert response["items"] == [{"id": "1", "text": "tweet"}] |
| 203 | assert run.call_count == 3 |
| 204 | assert bird_x._credentials["AUTH_TOKEN"] == c_pair["auth_token"] |
| 205 | |
| 206 | def test_browser_walk_stops_at_deadline(self): |
| 207 | cfg = _discover(_config(), {"safari": DEAD}) |
| 208 | with mock.patch("lib.cookie_extract.extract_cookies") as extract, \ |
| 209 | mock.patch("time.monotonic", return_value=100.0): |
| 210 | assert env.next_x_browser_pair(cfg, deadline=101.0) is None |
| 211 | extract.assert_not_called() |
| 212 | assert cfg[env.X_SESSION_STATE_KEY]["remaining"] # left for a later search |
| 213 | |
| 214 | def test_browser_walk_stops_on_cancel(self): |
| 215 | import threading |
| 216 | cfg = _discover(_config(), {"safari": DEAD}) |
| 217 | cancel = threading.Event(); cancel.set() |
| 218 | with mock.patch("lib.cookie_extract.extract_cookies") as extract: |
| 219 | assert env.next_x_browser_pair(cfg, cancel=cancel) is None |
| 220 | extract.assert_not_called() |
| 221 | |
| 222 | def test_lock_wait_is_bounded_by_deadline(self): |
| 223 | import time |
| 224 | cfg = _discover(_config(), {"safari": DEAD, "chrome": LIVE}) |
| 225 | env._inject_bird_credentials(cfg) |
| 226 | bird_x._session_lock.acquire() |
| 227 | try: |
| 228 | with mock.patch.object(bird_x, "_invoke_bird_subprocess", side_effect=_bird_outputs(SEARCH_401)): |
| 229 | started = time.monotonic() |
| 230 | response = bird_x._run_bird_search("kanye", count=10, timeout=30, |
| 231 | deadline=time.monotonic() + 1.5) |
| 232 | assert time.monotonic() - started < 5 |
| 233 | assert "session rejected (cookies from safari)" in response["error"] |
| 234 | finally: |
| 235 | bird_x._session_lock.release() |
| 236 | |
| 237 | def test_slow_keychain_read_cannot_outlast_deadline(self): |
| 238 | import threading |
| 239 | import time |
| 240 | cfg = _discover(_config(), {"safari": DEAD}) |
| 241 | release = threading.Event() |
| 242 | |
| 243 | def slow_read(browser, domain, names): |
| 244 | release.wait(10) # a Keychain prompt nobody answers |
| 245 | return LIVE |
| 246 | |
| 247 | try: |
| 248 | with mock.patch("lib.cookie_extract.extract_cookies", side_effect=slow_read): |
| 249 | started = time.monotonic() |
| 250 | pair = env.next_x_browser_pair(cfg, deadline=time.monotonic() + 3.0) |
| 251 | elapsed = time.monotonic() - started |
| 252 | finally: |
| 253 | release.set() |
| 254 | assert pair is None |
| 255 | assert elapsed < 3.0 |
| 256 |