返回 last30days-skill
test_x_extras_gating.py
根目录 / tests / test_x_extras_gating.py
1 """Host-gated X cookie extras: MacBook stays on main; Linux/Mac mini/sink get
2 the two extra bird cookie lookups (agentcookie sidecar, live Chrome CDP).
3
4 Locks the acceptance examples:
5 * AE7 Linux, no bird cookies, grok AUTH_OK + XAI_API_KEY -> xai (not grok).
6 * AE8 MacBook (hw.model MacBookPro), FROM_BROWSER unset, agentcookie on PATH,
7 grok AUTH_OK + XAI_API_KEY -> xai; NO agentcookie subprocess, NO CDP.
8 * AE10 Darwin Mac mini (hw.model Macmini9,1), consented agentcookie sidecar pair,
9 FROM_BROWSER unset -> bird from agentcookie. ~/.hermes never flips a
10 MacBook into extras.
11
12 Only obvious dummy cookie values are used (test-auth-token / test-ct0).
13 """
14
15 import json
16 from unittest import mock
17
18 import pytest
19
20 from lib import env
21
22 _PAIR = {"auth_token": "test-auth-token", "ct0": "test-ct0"}
23
24
25 @pytest.mark.parametrize("system,model,sink", [
26 ("Linux", "", False),
27 ("Darwin", "Macmini9,1", False),
28 ("Darwin", "MacBookPro18,2", True),
29 ])
30 @pytest.mark.parametrize("settings,allowed", [
31 ({}, False),
32 ({"AGENTCOOKIE": "on"}, True),
33 ({"BROWSER_CONSENT": "true"}, True),
34 ({"AGENTCOOKIE": "on", "BROWSER_CONSENT": "false"}, False),
35 ])
36 def test_host_eligibility_does_not_replace_sidecar_consent(system, model, sink, settings, allowed):
37 config = dict(settings)
38 with (
39 mock.patch("platform.system", return_value=system),
40 mock.patch.object(env, "_mac_model", return_value=model),
41 mock.patch("lib.agentcookie.role_is_sink", return_value=sink),
42 mock.patch("shutil.which", return_value="/mock/agentcookie"),
43 mock.patch("subprocess.run", return_value=mock.Mock(
44 returncode=0, stdout=json.dumps(_PAIR), stderr="",
45 )) as run,
46 mock.patch.object(env, "get_x_source", return_value=None),
47 mock.patch("lib.bird_x.is_bird_installed", return_value=True),
48 mock.patch("lib.chrome_cdp.read_x_cookies") as cdp,
49 _no_extract(),
50 ):
51 pending = env.x_pending_browser_auth({**config, "_BROWSER_COOKIE_MODE": "plan_only"})
52 run.assert_not_called()
53 env._discover_and_apply_x_credentials(config)
54 assert run.call_count == int(allowed)
55 assert pending is allowed
56 assert config.get("AUTH_TOKEN") == (_PAIR["auth_token"] if allowed else None)
57 assert config.get("CT0") == (_PAIR["ct0"] if allowed else None)
58 cdp.assert_not_called()
59
60
61 def _no_extract():
62 """Patch the mainline browser extractor to a no-op (FROM_BROWSER unset)."""
63 return mock.patch.object(env, "extract_browser_credentials", return_value={})
64
65
66 @pytest.mark.parametrize("refusal", [
67 {"BROWSER_CONSENT": "false"},
68 {"BROWSER_CONSENT": "unknown"},
69 {"FROM_BROWSER": "off"},
70 {"AGENTCOOKIE": "off"},
71 ])
72 def test_refused_sidecar_prediction_skips_role_path_and_host_probes(refusal):
73 with (
74 mock.patch.object(env, "get_x_source", return_value=None),
75 mock.patch("lib.bird_x.is_bird_installed", return_value=True),
76 mock.patch("platform.system", return_value="Darwin"),
77 mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2") as model,
78 mock.patch("lib.agentcookie.role_is_sink", return_value=True) as sink,
79 mock.patch("shutil.which", return_value="/mock/agentcookie") as which,
80 mock.patch("subprocess.run") as run,
81 ):
82 assert env.x_pending_browser_auth(refusal, local_only=True) is False
83 model.assert_not_called()
84 sink.assert_not_called()
85 which.assert_not_called()
86 run.assert_not_called()
87
88
89 def test_sidecar_off_does_not_disable_selected_native_browser_prediction():
90 with (
91 mock.patch.object(env, "get_x_source", return_value=None),
92 mock.patch("lib.bird_x.is_bird_installed", return_value=True),
93 mock.patch("lib.agentcookie.is_available") as sidecar,
94 ):
95 assert env.x_pending_browser_auth(
96 {"AGENTCOOKIE": "off", "FROM_BROWSER": "firefox"}, local_only=True
97 ) is True
98 sidecar.assert_not_called()
99
100
101 def _stub_backends():
102 """Local-only backend probes so get_x_source touches no network.
103
104 Returns an ExitStack already entered; use as ``with _stub_backends():``.
105 """
106 import contextlib
107 stack = contextlib.ExitStack()
108 stack.enter_context(mock.patch("lib.bird_x.is_bird_installed", return_value=True))
109 stack.enter_context(mock.patch("lib.bird_x.set_credentials", lambda *a, **k: None))
110 stack.enter_context(mock.patch("lib.xurl_x.is_available", return_value=False))
111 return stack
112
113
114 # --- x_extras_enabled matrix ----------------------------------------------
115
116
117 def test_extras_enabled_on_linux():
118 with mock.patch("platform.system", return_value="Linux"):
119 assert env.x_extras_enabled({}) is True
120
121
122 def test_extras_enabled_on_mac_mini():
123 with (
124 mock.patch("platform.system", return_value="Darwin"),
125 mock.patch.object(env, "_mac_model", return_value="Macmini9,1"),
126 ):
127 assert env.x_extras_enabled({}) is True
128
129
130 def test_extras_enabled_on_darwin_sink_role():
131 with (
132 mock.patch("platform.system", return_value="Darwin"),
133 mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
134 mock.patch("lib.agentcookie.role_is_sink", return_value=True),
135 ):
136 assert env.x_extras_enabled({}) is True
137
138
139 def test_extras_disabled_on_plain_macbook():
140 with (
141 mock.patch("platform.system", return_value="Darwin"),
142 mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
143 mock.patch("lib.agentcookie.role_is_sink", return_value=False),
144 ):
145 assert env.x_extras_enabled({}) is False
146
147
148 def test_agentcookie_on_opts_in_a_macbook():
149 with (
150 mock.patch("platform.system", return_value="Darwin"),
151 mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
152 ):
153 assert env.x_extras_enabled({"AGENTCOOKIE": "on"}) is True
154
155
156 def test_agentcookie_off_keeps_macbook_off():
157 with (
158 mock.patch("platform.system", return_value="Darwin"),
159 mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
160 mock.patch("lib.agentcookie.role_is_sink", return_value=False),
161 ):
162 assert env.x_extras_enabled({"AGENTCOOKIE": "off"}) is False
163
164
165 def test_windows_has_no_extras():
166 with mock.patch("platform.system", return_value="Windows"):
167 assert env.x_extras_enabled({}) is False
168
169
170 def test_hermes_home_and_env_never_flip_extras():
171 """~/.hermes / HERMES_AGENT / OPENCLAW_CLI must NOT enable extras (AE10)."""
172 with (
173 mock.patch("platform.system", return_value="Darwin"),
174 mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
175 mock.patch("lib.agentcookie.role_is_sink", return_value=False),
176 mock.patch.dict("os.environ", {"HERMES_AGENT": "1", "OPENCLAW_CLI": "1"}, clear=False),
177 ):
178 assert env.x_extras_enabled({}) is False
179
180
181 # --- AE8: MacBook is untouched --------------------------------------------
182
183
184 def test_ae8_macbook_no_extras_no_subprocess_and_picks_xai():
185 config = {"XAI_API_KEY": "dummy-xai-key"} # no AUTH_TOKEN/CT0, FROM_BROWSER unset
186 with (
187 mock.patch("platform.system", return_value="Darwin"),
188 mock.patch.object(env, "_mac_model", return_value="MacBookPro18,2"),
189 mock.patch("lib.agentcookie.role_is_sink", return_value=False),
190 # These MUST NOT run on a MacBook:
191 mock.patch("lib.agentcookie.read_x_cookies", side_effect=AssertionError("no agentcookie subprocess on MacBook")),
192 mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("no CDP on MacBook")),
193 _no_extract(),
194 ):
195 env._discover_and_apply_x_credentials(config)
196 assert config.get("AUTH_TOKEN") is None
197 assert config.get("CT0") is None
198 # Backend selection: leftover grok + XAI_API_KEY must use xai (grok pin-only).
199 with mock.patch("lib.grok_x.has_stored_auth", return_value=True), _stub_backends():
200 assert env.get_x_source(config) == "xai"
201
202
203 # --- AE10: Mac mini gets the sidecar pair ---------------------------------
204
205
206 def test_ae10_mac_mini_reads_bird_pair_from_agentcookie():
207 config = {"BROWSER_CONSENT": "true"} # FROM_BROWSER unset
208 with (
209 mock.patch("platform.system", return_value="Darwin"),
210 mock.patch.object(env, "_mac_model", return_value="Macmini9,1"),
211 mock.patch("lib.agentcookie.read_x_cookies", return_value=dict(_PAIR)),
212 mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("agentcookie already won")),
213 _no_extract(),
214 ):
215 env._discover_and_apply_x_credentials(config)
216 assert config["AUTH_TOKEN"] == "test-auth-token"
217 assert config["CT0"] == "test-ct0"
218 assert config["_AUTH_TOKEN_SOURCE"] == "agentcookie"
219 with mock.patch("lib.grok_x.has_stored_auth", return_value=False), _stub_backends():
220 assert env.get_x_source(config) == "bird"
221
222
223 # --- AE7: Linux picks xai over a stale grok --------------------------------
224
225
226 def test_ae7_linux_no_cookies_grok_and_xai_picks_xai():
227 config = {"XAI_API_KEY": "dummy-xai-key"}
228 with (
229 mock.patch("platform.system", return_value="Linux"),
230 mock.patch("lib.agentcookie.read_x_cookies", return_value=None),
231 mock.patch("lib.chrome_cdp.read_x_cookies", return_value=None),
232 _no_extract(),
233 ):
234 env._discover_and_apply_x_credentials(config)
235 assert config.get("AUTH_TOKEN") is None
236 assert config.get("CT0") is None
237 with mock.patch("lib.grok_x.has_stored_auth", return_value=True), _stub_backends():
238 assert env.get_x_source(config) == "xai"
239
240
241 # --- discovery ordering / no-overwrite ------------------------------------
242
243
244 def test_explicit_env_pair_not_overwritten_on_extra_host():
245 config = {"AUTH_TOKEN": "explicit-token", "CT0": "explicit-ct0"}
246 with (
247 mock.patch("platform.system", return_value="Linux"),
248 mock.patch("lib.agentcookie.read_x_cookies", side_effect=AssertionError("no discovery with complete env pair")),
249 mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("no discovery with complete env pair")),
250 _no_extract(),
251 ):
252 env._discover_and_apply_x_credentials(config)
253 assert config["AUTH_TOKEN"] == "explicit-token"
254 assert config["CT0"] == "explicit-ct0"
255
256
257 def test_cdp_used_when_agentcookie_empty_on_extra_host():
258 config = {"BROWSER_CONSENT": "true"}
259 with (
260 mock.patch("platform.system", return_value="Linux"),
261 mock.patch("lib.agentcookie.read_x_cookies", return_value=None),
262 mock.patch("lib.chrome_cdp.read_x_cookies", return_value=dict(_PAIR)),
263 _no_extract(),
264 ):
265 env._discover_and_apply_x_credentials(config)
266 assert config["AUTH_TOKEN"] == "test-auth-token"
267 assert config["_AUTH_TOKEN_SOURCE"] == "chrome cdp"
268
269
270 # --- AE1: Grok Bot host, cookies present, no pin ---------------------------
271
272
273 def test_ae1_grok_bot_blocks_scraper_xquik_and_every_cookie_leg():
274 """LAST30DAYS_HOST=grok-bot on Linux with every cookie source armed: the
275 chain has neither bird nor xquik, no sidecar / CDP / browser-store read
276 is made for any cookie domain, and the scraper is never primed."""
277 config = {
278 "LAST30DAYS_HOST": "grok-bot",
279 "FROM_BROWSER": "firefox",
280 "AGENTCOOKIE": "on",
281 "BROWSER_CDP_URL": "http://127.0.0.1:18800",
282 "AUTH_TOKEN": "test-auth-token",
283 "CT0": "test-ct0",
284 "XQUIK_API_KEY": "dummy-xquik-key",
285 }
286 with (
287 mock.patch("platform.system", return_value="Linux"),
288 mock.patch("shutil.which", return_value="/usr/local/bin/agentcookie"),
289 mock.patch("lib.agentcookie.read_x_cookies", side_effect=AssertionError("no sidecar on grok-bot")),
290 mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("no CDP on grok-bot")),
291 mock.patch("lib.cookie_extract.extract_cookies", side_effect=AssertionError("no browser store read on grok-bot")),
292 mock.patch("lib.bird_x.set_credentials", side_effect=AssertionError("scraper must not be primed on grok-bot")),
293 mock.patch("lib.bird_x.is_bird_installed", return_value=True),
294 mock.patch("lib.xurl_x.is_available", return_value=False),
295 mock.patch("lib.xurl_x.has_stored_auth", return_value=False),
296 ):
297 env._discover_and_apply_x_credentials(config)
298 assert env.cookie_extraction_browsers(config) == []
299 chain = env.x_backend_chain(config)
300 assert "bird" not in chain
301 assert "xquik" not in chain
302 assert chain == []
303 assert env.get_x_source(config) is None
304 # Preflight reports browser cookies off: no browser resolves.
305 config["_BROWSER_COOKIE_MODE"] = "plan_only"
306 assert env.x_pending_browser_auth(config) is False
307 # X becomes available only through an official path.
308 assert env.x_backend_chain({**config, "X_BEARER_TOKEN": "dummy-bearer"}) == ["xapi"]
309 assert env.x_backend_chain({**config, "XAI_API_KEY": "dummy-xai-key"}) == ["xai"]
310
311
312 def test_ae1_get_config_read_mode_on_grok_bot_reports_no_browsers(tmp_path, monkeypatch):
313 """The resolved config's _BROWSER_COOKIE_BROWSERS is empty on a Grok Bot
314 host even with FROM_BROWSER set, and read mode performs no cookie leg."""
315 monkeypatch.setenv("LAST30DAYS_CONFIG_DIR", str(tmp_path))
316 monkeypatch.setattr(env, "CONFIG_DIR", tmp_path)
317 monkeypatch.setattr(env, "CONFIG_FILE", tmp_path / "does-not-exist.env")
318 monkeypatch.chdir(tmp_path)
319 monkeypatch.setenv("LAST30DAYS_HOST", "grok-bot")
320 monkeypatch.setenv("FROM_BROWSER", "firefox")
321 monkeypatch.setenv("AGENTCOOKIE", "on")
322 monkeypatch.delenv("LAST30DAYS_X_BACKEND", raising=False)
323 with (
324 mock.patch.object(env, "_load_keychain", return_value={}),
325 mock.patch.object(env, "_load_pass", return_value={}),
326 mock.patch.object(env, "_find_project_env", return_value=None),
327 mock.patch("platform.system", return_value="Linux"),
328 mock.patch("lib.agentcookie.read_x_cookies", side_effect=AssertionError("no sidecar on grok-bot")),
329 mock.patch("lib.chrome_cdp.read_x_cookies", side_effect=AssertionError("no CDP on grok-bot")),
330 mock.patch("lib.cookie_extract.extract_cookies", side_effect=AssertionError("no browser store read on grok-bot")),
331 ):
332 config = env.get_config(env.ConfigLoadPolicy(browser_cookies="read"))
333 assert config["_BROWSER_COOKIE_BROWSERS"] == []
334 assert config["_BROWSER_COOKIE_MODE"] == "read"
335 assert config.get("_AUTH_TOKEN_SOURCE") is None
336
337
338 # --- AE7a: ambient bearer on a non-Grok host never reaches xapi ------------
339
340
341 def test_ae7a_non_grok_host_ambient_bearer_never_reaches_xapi():
342 config = {
343 "AUTH_TOKEN": "test-auth-token",
344 "CT0": "test-ct0",
345 "X_BEARER_TOKEN": "dummy-bearer",
346 }
347 with (
348 mock.patch("platform.system", return_value="Linux"),
349 mock.patch("lib.http.get", side_effect=AssertionError("no X API request off Grok Bot")),
350 _stub_backends(),
351 ):
352 chain = env.x_backend_chain(config)
353 # The X loop fails over only along this chain: bird returning nothing
354 # leaves no next rung, so no X API request is possible.
355 assert chain == ["bird"]
356 assert "xapi" not in chain
357 with _stub_backends():
358 assert env.x_backend_chain({**config, "LAST30DAYS_X_BACKEND": "xapi"}) == ["xapi"]
359
360
361 # --- AE8: Cursor agent chat without the host key is unchanged --------------
362
363
364 def test_ae8_cursor_agent_without_host_key_is_unchanged():
365 config = {"AGENTCOOKIE": "on"}
366 with (
367 mock.patch.dict("os.environ", {"CURSOR_AGENT": "1"}, clear=False),
368 mock.patch("platform.system", return_value="Linux"),
369 mock.patch("lib.agentcookie.read_x_cookies", return_value=dict(_PAIR)) as sidecar,
370 mock.patch("lib.chrome_cdp.read_x_cookies", return_value=None),
371 _no_extract(),
372 ):
373 env._discover_and_apply_x_credentials(config)
374 assert sidecar.called
375 assert config["_AUTH_TOKEN_SOURCE"] == "agentcookie"
376 with _stub_backends():
377 assert env.x_backend_chain(config) == ["bird"]
378
378 lines PYTHON