返回 last30days-skill
test_chromium_browsers.py
根目录 / tests / test_chromium_browsers.py
1 """Tests for the extended Chromium-family browser cookie support.
2
3 Covers the three layers wired up for Brave/Edge/Vivaldi/Opera/Arc/Chromium:
4 - env.extract_browser_credentials (which browsers FROM_BROWSER selects)
5 - cookie_extract (routing browser name -> extractor)
6 - chrome_cookies (registry, profile finder, extraction)
7 """
8
9 import sqlite3
10 from unittest.mock import patch
11
12 import pytest
13
14 from lib.env import extract_browser_credentials
15 from lib.cookie_extract import extract_cookies
16 from lib.chrome_cookies import (
17 CHROMIUM_BROWSER_PROFILES,
18 _find_chromium_cookies_db,
19 extract_chromium_browser_cookies_macos,
20 )
21
22 # The Chromium-based browsers added on top of the original Chrome support.
23 NEW_CHROMIUM_BROWSERS = ["brave", "edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium"]
24 ALL_AUTO_BROWSERS = ["firefox", "safari", "chrome", *NEW_CHROMIUM_BROWSERS]
25
26
27 def _base_config(**overrides):
28 cfg = {
29 "AUTH_TOKEN": None,
30 "CT0": None,
31 "TRUTHSOCIAL_TOKEN": None,
32 "FROM_BROWSER": None,
33 "SETUP_COMPLETE": None,
34 }
35 cfg.update(overrides)
36 return cfg
37
38
39 def _make_cookies_db(path, rows, db_version: int = 20) -> None:
40 """Create a minimal Chromium Cookies SQLite DB with plain (unencrypted) values."""
41 conn = sqlite3.connect(str(path))
42 c = conn.cursor()
43 c.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
44 c.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", (str(db_version),))
45 c.execute(
46 "CREATE TABLE cookies ("
47 " host_key TEXT NOT NULL,"
48 " name TEXT NOT NULL,"
49 " value TEXT NOT NULL DEFAULT '',"
50 " encrypted_value BLOB NOT NULL DEFAULT x''"
51 ")"
52 )
53 for host_key, name, value in rows:
54 c.execute(
55 "INSERT INTO cookies (host_key, name, value, encrypted_value) VALUES (?, ?, ?, ?)",
56 (host_key, name, value, b""),
57 )
58 conn.commit()
59 conn.close()
60
61
62 def _make_encrypted_cookies_db(path, rows, db_version: int = 24) -> None:
63 """Create a Cookies DB with v10-encrypted_value rows (empty value column)."""
64 conn = sqlite3.connect(str(path))
65 c = conn.cursor()
66 c.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
67 c.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", (str(db_version),))
68 c.execute(
69 "CREATE TABLE cookies ("
70 " host_key TEXT NOT NULL,"
71 " name TEXT NOT NULL,"
72 " value TEXT NOT NULL DEFAULT '',"
73 " encrypted_value BLOB NOT NULL DEFAULT x''"
74 ")"
75 )
76 for host_key, name, encrypted_value in rows:
77 c.execute(
78 "INSERT INTO cookies (host_key, name, value, encrypted_value) VALUES (?, ?, ?, ?)",
79 (host_key, name, "", encrypted_value),
80 )
81 conn.commit()
82 conn.close()
83
84
85 # ---------------------------------------------------------------------------
86 # env.py: FROM_BROWSER selects the right browsers
87 # ---------------------------------------------------------------------------
88
89
90 class TestEnvBrowserSelection:
91 @pytest.mark.parametrize("browser", NEW_CHROMIUM_BROWSERS)
92 @patch("lib.cookie_extract.extract_cookies")
93 def test_explicit_chromium_browser_is_used(self, mock_extract, browser):
94 """FROM_BROWSER=<chromium browser> routes extraction to that browser."""
95 mock_extract.return_value = {"auth_token": "tok", "ct0": "ct0val"}
96 config = _base_config(FROM_BROWSER=browser)
97
98 result = extract_browser_credentials(config)
99
100 assert result["AUTH_TOKEN"] == "tok"
101 assert result["CT0"] == "ct0val"
102 # Every extraction call targeted exactly the requested browser.
103 assert mock_extract.call_args_list
104 for call in mock_extract.call_args_list:
105 assert call[0][0] == browser
106
107 @patch("lib.cookie_extract.extract_cookies")
108 def test_auto_tries_every_chromium_browser(self, mock_extract):
109 """FROM_BROWSER=auto tries Firefox/Safari plus the whole Chromium family."""
110 mock_extract.return_value = None # force it to try them all
111 config = _base_config(FROM_BROWSER="auto")
112
113 extract_browser_credentials(config)
114
115 tried = {call[0][0] for call in mock_extract.call_args_list}
116 for browser in ALL_AUTO_BROWSERS:
117 assert browser in tried, f"auto should try {browser}"
118
119 @patch("lib.cookie_extract.extract_cookies")
120 def test_default_skips_browser_cookie_reads(self, mock_extract):
121 """Default (no FROM_BROWSER) reads no local browser cookies."""
122 mock_extract.return_value = None
123 config = _base_config()
124
125 extract_browser_credentials(config)
126
127 mock_extract.assert_not_called()
128
129
130 # ---------------------------------------------------------------------------
131 # cookie_extract.py: browser name routes to the chrome_cookies registry
132 # ---------------------------------------------------------------------------
133
134
135 class TestCookieExtractRouting:
136 @pytest.mark.parametrize("browser", ["edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium"])
137 def test_routes_to_registry(self, browser):
138 with (
139 patch("lib.cookie_extract.platform.system", return_value="Darwin"),
140 patch(
141 "lib.chrome_cookies.extract_chromium_browser_cookies_macos",
142 return_value={"auth_token": f"{browser}_tok"},
143 ) as mock_macos,
144 ):
145 result = extract_cookies(browser, ".x.com", ["auth_token"])
146
147 assert result == {"auth_token": f"{browser}_tok"}
148 # The browser key is threaded through to the macOS extractor.
149 assert mock_macos.call_args[0][0] == browser
150
151 @pytest.mark.parametrize("browser", ["edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium"])
152 def test_non_macos_returns_none(self, browser):
153 with patch("lib.cookie_extract.platform.system", return_value="Linux"):
154 assert extract_cookies(browser, ".x.com", ["auth_token"]) is None
155
156 def test_auto_macos_order_includes_chromium_family(self):
157 """auto on macOS calls every Chromium-family extractor when all miss."""
158 with (
159 patch("lib.cookie_extract.platform.system", return_value="Darwin"),
160 patch("lib.cookie_extract._extract_firefox_with_source", return_value=None),
161 patch("lib.cookie_extract.extract_chrome_cookies", return_value=None) as m_chrome,
162 patch("lib.cookie_extract.extract_brave_cookies", return_value=None) as m_brave,
163 patch("lib.cookie_extract.extract_edge_cookies", return_value=None) as m_edge,
164 patch("lib.cookie_extract.extract_vivaldi_cookies", return_value=None) as m_viv,
165 patch("lib.cookie_extract.extract_opera_cookies", return_value=None) as m_opera,
166 patch("lib.cookie_extract.extract_arc_cookies", return_value=None) as m_arc,
167 patch("lib.cookie_extract.extract_dia_cookies", return_value=None) as m_dia,
168 patch("lib.cookie_extract.extract_ardia_cookies", return_value=None) as m_ardia,
169 patch("lib.cookie_extract.extract_chromium_cookies", return_value=None) as m_chr,
170 patch("lib.cookie_extract.extract_safari_cookies", return_value=None),
171 ):
172 result = extract_cookies("auto", ".x.com", ["auth_token"])
173
174 assert result is None
175 for mock_fn in (m_chrome, m_brave, m_edge, m_viv, m_opera, m_arc, m_dia, m_ardia, m_chr):
176 mock_fn.assert_called_once_with(".x.com", ["auth_token"])
177
178
179 # ---------------------------------------------------------------------------
180 # chrome_cookies.py: registry, profile finder, generic extraction
181 # ---------------------------------------------------------------------------
182
183
184 class TestChromiumRegistry:
185 def test_registry_has_expected_browsers(self):
186 assert set(CHROMIUM_BROWSER_PROFILES) == {"edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium"}
187 for base_dir, service in CHROMIUM_BROWSER_PROFILES.values():
188 assert service.endswith("Safe Storage")
189 assert base_dir is not None
190
191 def test_unknown_browser_returns_none(self):
192 assert extract_chromium_browser_cookies_macos("netscape", ".x.com", ["auth_token"]) is None
193
194 def test_generic_extraction_plain_values(self, tmp_path):
195 """A registry browser extracts unencrypted cookies via the shared core."""
196 base = tmp_path / "Edge"
197 (base / "Default").mkdir(parents=True)
198 _make_cookies_db(
199 base / "Default" / "Cookies",
200 [
201 (".x.com", "auth_token", "edge_auth"),
202 (".x.com", "ct0", "edge_ct0"),
203 (".other.com", "session", "nope"),
204 ],
205 )
206
207 with (
208 patch.dict(
209 "lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
210 {"edge": (base, "Microsoft Edge Safe Storage")},
211 ),
212 # Plain values need no Keychain; ensure we never prompt.
213 patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=None),
214 ):
215 result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token", "ct0"])
216
217 assert result == {"auth_token": "edge_auth", "ct0": "edge_ct0"}
218
219 def test_db_not_found_returns_none(self, tmp_path):
220 empty = tmp_path / "Vivaldi"
221 empty.mkdir()
222 with patch.dict(
223 "lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
224 {"vivaldi": (empty, "Vivaldi Safe Storage")},
225 ):
226 assert extract_chromium_browser_cookies_macos("vivaldi", ".x.com", ["auth_token"]) is None
227
228
229 class TestFindChromiumCookiesDb:
230 def test_prefers_default_profile(self, tmp_path):
231 (tmp_path / "Default").mkdir()
232 default_db = tmp_path / "Default" / "Cookies"
233 default_db.touch()
234 (tmp_path / "Cookies").touch() # direct file should be ignored
235 assert _find_chromium_cookies_db(tmp_path) == default_db
236
237 def test_falls_back_to_direct_cookies(self, tmp_path):
238 """Opera-style layout: Cookies directly under the base dir."""
239 direct = tmp_path / "Cookies"
240 direct.touch()
241 assert _find_chromium_cookies_db(tmp_path) == direct
242
243 def test_falls_back_to_numbered_profile(self, tmp_path):
244 prof = tmp_path / "Profile 2"
245 prof.mkdir()
246 db = prof / "Cookies"
247 db.touch()
248 assert _find_chromium_cookies_db(tmp_path) == db
249
250 def test_returns_none_when_missing(self, tmp_path):
251 assert _find_chromium_cookies_db(tmp_path) is None
252
253 def test_prefers_network_cookies_over_flat(self, tmp_path):
254 """Modern Chromium (>=96) stores under Default/Network/Cookies."""
255 (tmp_path / "Default" / "Network").mkdir(parents=True)
256 net = tmp_path / "Default" / "Network" / "Cookies"
257 net.touch()
258 (tmp_path / "Default" / "Cookies").touch() # legacy flat also present
259 assert _find_chromium_cookies_db(tmp_path) == net
260
261 def test_network_cookies_in_numbered_profile(self, tmp_path):
262 (tmp_path / "Profile 1" / "Network").mkdir(parents=True)
263 net = tmp_path / "Profile 1" / "Network" / "Cookies"
264 net.touch()
265 assert _find_chromium_cookies_db(tmp_path) == net
266
267
268 class TestLazyKeychain:
269 """The Keychain key is fetched only when an encrypted cookie must be decrypted.
270
271 This keeps FROM_BROWSER=auto from prompting for every installed Chromium
272 browser - only the one actually holding the requested cookie prompts.
273 """
274
275 def _edge_at(self, tmp_path, rows, encrypted=False):
276 base = tmp_path / "Edge"
277 (base / "Default").mkdir(parents=True)
278 db = base / "Default" / "Cookies"
279 if encrypted:
280 _make_encrypted_cookies_db(db, rows)
281 else:
282 _make_cookies_db(db, rows)
283 return base
284
285 def test_keychain_not_fetched_for_plain_values(self, tmp_path):
286 base = self._edge_at(tmp_path, [(".x.com", "auth_token", "plain_tok")])
287 with (
288 patch.dict("lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
289 {"edge": (base, "Microsoft Edge Safe Storage")}),
290 patch("lib.chrome_cookies._get_chromium_encryption_key") as key_mock,
291 ):
292 result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token"])
293 assert result == {"auth_token": "plain_tok"}
294 key_mock.assert_not_called() # no decryption needed -> no Keychain prompt
295
296 def test_keychain_not_fetched_when_no_match(self, tmp_path):
297 base = self._edge_at(tmp_path, [(".other.com", "auth_token", "x")])
298 with (
299 patch.dict("lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
300 {"edge": (base, "Microsoft Edge Safe Storage")}),
301 patch("lib.chrome_cookies._get_chromium_encryption_key") as key_mock,
302 ):
303 result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token"])
304 assert result is None
305 key_mock.assert_not_called() # cookie absent -> no Keychain prompt
306
307 def test_keychain_fetched_and_decrypts_v10(self, tmp_path):
308 base = self._edge_at(tmp_path, [(".x.com", "auth_token", b"v10ciphertextbytes")], encrypted=True)
309 with (
310 patch.dict("lib.chrome_cookies.CHROMIUM_BROWSER_PROFILES",
311 {"edge": (base, "Microsoft Edge Safe Storage")}),
312 patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=b"passphrase") as key_mock,
313 patch("lib.chrome_cookies._decrypt_v10_value", return_value="decrypted_tok") as dec_mock,
314 ):
315 result = extract_chromium_browser_cookies_macos("edge", ".x.com", ["auth_token"])
316 assert result == {"auth_token": "decrypted_tok"}
317 key_mock.assert_called_once_with("Microsoft Edge Safe Storage")
318 assert dec_mock.called
319
319 lines PYTHON