返回 last30days-skill
test_agentcookie.py
根目录 / tests / test_agentcookie.py
1 """U1/U5: agentcookie sidecar reader (lib/agentcookie.py).
2
3 Subprocess is always mocked; only obvious dummy cookie values are used
4 (test-auth-token / test-ct0). Enforces the soft-dep, AGENTCOOKIE=off,
5 FROM_BROWSER-independence, complete-pair, and no-value-logging contracts.
6 """
7
8 import json
9 import subprocess
10 from unittest import mock
11
12 import pytest
13
14 from lib import agentcookie
15
16 _DUMMY = {"auth_token": "test-auth-token", "ct0": "test-ct0"}
17
18
19 @pytest.mark.parametrize("config,allowed", [
20 ({}, False),
21 ({"FROM_BROWSER": "firefox"}, False),
22 ({"AGENTCOOKIE": "auto"}, False),
23 ({"AGENTCOOKIE": " ON "}, True),
24 ({"BROWSER_CONSENT": "true"}, True),
25 ({"BROWSER_CONSENT": " YES "}, True),
26 ({"BROWSER_CONSENT": "true", "AGENTCOOKIE": "off"}, False),
27 ({"BROWSER_CONSENT": "unknown", "AGENTCOOKIE": "on"}, False),
28 ({"BROWSER_CONSENT": "false", "AGENTCOOKIE": "on"}, False),
29 ({"FROM_BROWSER": "off", "BROWSER_CONSENT": "true", "AGENTCOOKIE": "on"}, False),
30 ])
31 @pytest.mark.parametrize("from_environment", [False, True])
32 def test_sidecar_prediction_and_read_require_positive_consent(config, allowed, from_environment, monkeypatch):
33 if from_environment:
34 for key, value in config.items():
35 monkeypatch.setenv(key, value)
36 config = None
37 with (
38 mock.patch("shutil.which", return_value="/mock/agentcookie"),
39 mock.patch("subprocess.run", return_value=_run_ok(json.dumps(_DUMMY))) as run,
40 ):
41 available = agentcookie.is_available(config)
42 run.assert_not_called()
43 result = agentcookie.read_x_cookies(config)
44 assert run.call_count == int(allowed)
45 assert available is allowed
46 assert result == (_DUMMY if allowed else None)
47
48
49 @pytest.mark.parametrize("refusal", [
50 {"BROWSER_CONSENT": "false"},
51 {"BROWSER_CONSENT": " NO "},
52 {"BROWSER_CONSENT": "unknown"},
53 {"FROM_BROWSER": " OFF ", "BROWSER_CONSENT": "true"},
54 {"AGENTCOOKIE": "off", "BROWSER_CONSENT": "true"},
55 ])
56 @pytest.mark.parametrize("from_environment", [False, True])
57 def test_cookie_refusal_disables_sidecar_even_when_explicitly_enabled(
58 refusal, from_environment, monkeypatch,
59 ):
60 config = {"AGENTCOOKIE": "on", **refusal}
61 if from_environment:
62 for key, value in config.items():
63 monkeypatch.setenv(key, value)
64 config = None
65 with (
66 mock.patch("lib.agentcookie.role_is_sink", return_value=True) as sink,
67 mock.patch("shutil.which", return_value="/mock/agentcookie") as which,
68 mock.patch("subprocess.run") as run,
69 ):
70 assert agentcookie.is_available(config) is False
71 assert agentcookie.read_x_cookies(config) is None
72 run.assert_not_called()
73 sink.assert_not_called()
74 which.assert_not_called()
75
76
77 def _run_ok(stdout):
78 return mock.Mock(returncode=0, stdout=stdout, stderr="")
79
80
81 def test_off_disables_without_subprocess():
82 with (
83 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
84 mock.patch("subprocess.run", side_effect=AssertionError("should not run")),
85 ):
86 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "off"}) is None
87 assert agentcookie.is_disabled({"AGENTCOOKIE": "off"}) is True
88 assert agentcookie.is_available({"AGENTCOOKIE": "off"}) is False
89
90
91 def test_absent_binary_is_soft_skip():
92 with mock.patch("shutil.which", return_value=None):
93 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "on"}) is None
94 assert agentcookie.is_available({"AGENTCOOKIE": "on"}) is False
95
96
97 def test_complete_pair_from_list_json():
98 payload = json.dumps([
99 {"name": "auth_token", "value": "test-auth-token", "domain": ".x.com"},
100 {"name": "ct0", "value": "test-ct0", "domain": ".x.com"},
101 {"name": "guest_id", "value": "irrelevant", "domain": ".x.com"},
102 ])
103 with (
104 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
105 mock.patch("subprocess.run", return_value=_run_ok(payload)) as run,
106 ):
107 result = agentcookie.read_x_cookies({"AGENTCOOKIE": "on"})
108 assert result == _DUMMY
109 # It asks for the x.com domain in JSON.
110 args = run.call_args[0][0]
111 assert "--domain" in args and ".x.com" in args and "--json" in args
112
113
114 def test_complete_pair_from_cookies_wrapper():
115 payload = json.dumps({"cookies": [
116 {"name": "auth_token", "value": "test-auth-token"},
117 {"name": "ct0", "value": "test-ct0"},
118 ]})
119 with (
120 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
121 mock.patch("subprocess.run", return_value=_run_ok(payload)),
122 ):
123 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "on"}) == _DUMMY
124
125
126 def test_complete_pair_from_flat_mapping():
127 payload = json.dumps({"auth_token": "test-auth-token", "ct0": "test-ct0"})
128 with (
129 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
130 mock.patch("subprocess.run", return_value=_run_ok(payload)),
131 ):
132 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "on"}) == _DUMMY
133
134
135 def test_half_pair_is_rejected():
136 payload = json.dumps([{"name": "auth_token", "value": "test-auth-token"}])
137 with (
138 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
139 mock.patch("subprocess.run", return_value=_run_ok(payload)),
140 ):
141 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "on"}) is None
142
143
144 def test_nonzero_exit_is_none():
145 with (
146 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
147 mock.patch("subprocess.run", return_value=mock.Mock(returncode=2, stdout="", stderr="nope")),
148 ):
149 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "on"}) is None
150
151
152 def test_timeout_is_none():
153 with (
154 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
155 mock.patch("subprocess.run", side_effect=subprocess.TimeoutExpired("agentcookie", 10)),
156 ):
157 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "on"}) is None
158
159
160 def test_non_json_is_none():
161 with (
162 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
163 mock.patch("subprocess.run", return_value=_run_ok("<html>blocked</html>")),
164 ):
165 assert agentcookie.read_x_cookies({"AGENTCOOKIE": "on"}) is None
166
167
168 def test_never_logs_cookie_values():
169 payload = json.dumps({"auth_token": "test-auth-token", "ct0": "test-ct0"})
170 logged = []
171 with (
172 mock.patch("shutil.which", return_value="/usr/bin/agentcookie"),
173 mock.patch("subprocess.run", return_value=_run_ok(payload)),
174 mock.patch("lib.agentcookie.log.source_log", lambda src, msg, **k: logged.append(msg)),
175 ):
176 agentcookie.read_x_cookies({"AGENTCOOKIE": "on"})
177 joined = "\n".join(logged)
178 assert "test-auth-token" not in joined
179 assert "test-ct0" not in joined
180
181
182 # --- role detection (subprocess-free config read) --------------------------
183
184
185 def test_role_is_sink_reads_config_file(tmp_path):
186 cfg = tmp_path / "config.json"
187 cfg.write_text(json.dumps({"role": "sink"}))
188 config = {"AGENTCOOKIE_CONFIG": str(cfg)}
189 # No subprocess is spawned to classify the role.
190 with mock.patch("subprocess.run", side_effect=AssertionError("no subprocess for role")):
191 assert agentcookie.role(config) == "sink"
192 assert agentcookie.role_is_sink(config) is True
193
194
195 def test_role_source_is_not_sink(tmp_path):
196 cfg = tmp_path / "config.json"
197 cfg.write_text(json.dumps({"role": "source"}))
198 config = {"AGENTCOOKIE_CONFIG": str(cfg)}
199 assert agentcookie.role_is_sink(config) is False
200
201
202 def test_role_missing_or_unparsable_is_not_sink(tmp_path):
203 missing = {"AGENTCOOKIE_CONFIG": str(tmp_path / "nope.json")}
204 assert agentcookie.role_is_sink(missing) is False
205 bad = tmp_path / "bad.json"
206 bad.write_text("not json {")
207 assert agentcookie.role_is_sink({"AGENTCOOKIE_CONFIG": str(bad)}) is False
208
208 lines PYTHON