返回 last30days-skill
test_cookie_extract.py
根目录 / tests / test_cookie_extract.py
1 """Tests for browser cookie extraction module."""
2
3 import configparser
4 import os
5 import sqlite3
6 import tempfile
7 import textwrap
8 from contextlib import closing
9 from pathlib import Path
10 from typing import Dict, List, Optional, Tuple
11 from unittest.mock import patch
12
13 import pytest
14
15 from lib import cookie_extract, env, setup_wizard
16 from lib.cookie_extract import (
17 extract_cookies,
18 extract_firefox_cookies,
19 has_complete_pair,
20 _query_cookies_db,
21 _find_default_profile,
22 _get_firefox_profiles_dir,
23 )
24
25
26 @pytest.mark.parametrize("domain", [".x.com", "x.com", ".example.test", "example.test"])
27 def test_firefox_cookie_host_family_and_requested_names(tmp_path, domain):
28 host = domain.lstrip(".")
29 db = tmp_path / "cookies.sqlite"
30 with sqlite3.connect(db) as conn:
31 conn.execute("CREATE TABLE moz_cookies (host TEXT, name TEXT, value TEXT)")
32 conn.executemany("INSERT INTO moz_cookies VALUES (?, ?, ?)", [
33 (host, "auth_token", "dummy-auth"),
34 ("." + host, "ct0", "dummy-ct0"),
35 ("sub." + host, "sub_cookie", "dummy-sub"),
36 ("not" + host, "near_cookie", "dummy-near"),
37 (host + ".example", "suffix_cookie", "dummy-suffix"),
38 (host, "unrequested", "dummy-other"),
39 ])
40 assert _query_cookies_db(
41 db, domain, ["auth_token", "ct0", "sub_cookie", "near_cookie", "suffix_cookie"],
42 ) == {"auth_token": "dummy-auth", "ct0": "dummy-ct0"}
43
44
45 @pytest.fixture
46 def standalone_browsers(monkeypatch):
47 """Replace every browser boundary, including Firefox's source label."""
48 calls = []
49 results = {}
50 order = ["chrome", "brave", "edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium", "firefox", "safari"]
51 monkeypatch.setattr(cookie_extract.platform, "system", lambda: "Darwin")
52
53 def extractor(name):
54 def extract(domain, names):
55 assert domain == ".x.com"
56 assert names == ["auth_token", "ct0"]
57 calls.append(name)
58 result = results.get(name)
59 if isinstance(result, Exception):
60 raise result
61 if name == "firefox" and result is not None:
62 return result, "firefox-wsl"
63 return result
64 return extract
65
66 for name in order:
67 target = "_extract_firefox_with_source" if name == "firefox" else f"extract_{name}_cookies"
68 monkeypatch.setattr(cookie_extract, target, extractor(name))
69 return results, calls, order
70
71
72 @pytest.mark.parametrize("first", [{"ct0": "dummy-partial"}, PermissionError("dummy-denial")])
73 def test_standalone_auto_continues_to_complete_browser(standalone_browsers, first):
74 results, calls, order = standalone_browsers
75 complete = {"auth_token": "dummy-auth", "ct0": "dummy-complete"}
76 results.update(chrome=first, firefox=complete)
77 assert cookie_extract.extract_cookies_with_source(
78 "auto", ".x.com", ["auth_token", "ct0"],
79 ) == (complete, "firefox-wsl")
80 assert calls == order[:-1]
81
82
83 def test_standalone_auto_keeps_first_partial_without_combining_browsers(standalone_browsers):
84 results, calls, order = standalone_browsers
85 partial = {"ct0": "dummy-partial"}
86 results.update(chrome=partial, brave={"auth_token": "dummy-other"}, edge=PermissionError("dummy-denial"))
87 assert cookie_extract.extract_cookies_with_source(
88 "auto", ".x.com", ["auth_token", "ct0"],
89 ) == (partial, "chrome")
90 assert calls == order
91
92
93 def test_standalone_auto_raises_first_denial_after_trying_every_browser(standalone_browsers):
94 results, calls, order = standalone_browsers
95 denial = PermissionError("dummy-first-denial")
96 results.update({name: PermissionError("dummy-other-denial") for name in order})
97 results["chrome"] = denial
98 with pytest.raises(PermissionError) as caught:
99 cookie_extract.extract_cookies_with_source("auto", ".x.com", ["auth_token", "ct0"])
100 assert caught.value is denial
101 assert calls == order
102
103
104 @pytest.mark.parametrize("later_cookies", [None, {"auth_token": "dummy-auth", "ct0": "dummy-ct0"}])
105 def test_standalone_auto_continues_after_cookie_database_read_error(standalone_browsers, later_cookies):
106 results, calls, order = standalone_browsers
107 error = cookie_extract.CookieDatabaseReadError("dummy-read-error")
108 results.update(firefox=error, safari=later_cookies)
109
110 if later_cookies is None:
111 with pytest.raises(cookie_extract.CookieDatabaseReadError) as caught:
112 cookie_extract.extract_cookies_with_source("auto", ".x.com", ["auth_token", "ct0"])
113 assert caught.value is error
114 else:
115 assert cookie_extract.extract_cookies_with_source(
116 "auto", ".x.com", ["auth_token", "ct0"],
117 ) == (later_cookies, "safari")
118 assert calls == order
119
120
121 @pytest.mark.parametrize("system", ["Linux", "Windows"])
122 def test_standalone_auto_other_platforms_only_try_firefox(standalone_browsers, monkeypatch, system):
123 _results, calls, _ = standalone_browsers
124 monkeypatch.setattr(cookie_extract.platform, "system", lambda: system)
125 assert cookie_extract.extract_cookies_with_source("auto", ".x.com", ["auth_token", "ct0"]) is None
126 assert calls == ["firefox"]
127
128
129 def test_standalone_explicit_browser_preserves_partial_and_denial(standalone_browsers):
130 results, calls, _ = standalone_browsers
131 partial = {"ct0": "dummy-partial"}
132 results["chrome"] = partial
133 assert cookie_extract.extract_cookies_with_source(
134 "chrome", ".x.com", ["auth_token", "ct0"],
135 ) == (partial, "chrome")
136 results["chrome"] = PermissionError("dummy-denial")
137 with pytest.raises(PermissionError):
138 cookie_extract.extract_cookies_with_source("chrome", ".x.com", ["auth_token", "ct0"])
139 assert calls == ["chrome", "chrome"]
140
141
142 def test_firefox_database_permission_denial_survives_extractor(tmp_path):
143 db = tmp_path / "cookies.sqlite"
144 db.touch()
145 with patch(
146 "lib.cookie_extract.copy_snapshot",
147 side_effect=PermissionError(1, "Operation not permitted", str(db)),
148 ):
149 with pytest.raises(PermissionError):
150 _query_cookies_db(db, ".x.com", ["auth_token", "ct0"])
151
152
153 def test_firefox_database_discovery_preserves_stat_permission_denial(tmp_path):
154 db = tmp_path / "cookies.sqlite"
155 real_stat = Path.stat
156 real_is_file = Path.is_file
157
158 def guarded_stat(path, *args, **kwargs):
159 if path == db:
160 raise PermissionError(1, "Operation not permitted", str(path))
161 return real_stat(path, *args, **kwargs)
162
163 def simulated_py314_is_file(path, *args, **kwargs):
164 if path == db:
165 return False
166 return real_is_file(path, *args, **kwargs)
167
168 with patch.object(Path, "stat", guarded_stat), patch.object(
169 Path, "is_file", simulated_py314_is_file
170 ):
171 with pytest.raises(PermissionError):
172 _query_cookies_db(db, ".x.com", ["auth_token", "ct0"])
173
174
175 def test_wsl_firefox_directory_skips_denied_user_for_accessible_user(tmp_path):
176 users = tmp_path / "Users"
177 denied_user = users / "aaa"
178 available = users / "bbb" / "AppData" / "Roaming" / "Mozilla" / "Firefox"
179 denied_user.mkdir(parents=True)
180 available.mkdir(parents=True)
181 real_stat = Path.stat
182 real_is_dir = Path.is_dir
183
184 def guarded_stat(path, *args, **kwargs):
185 if path == denied_user:
186 raise PermissionError(1, "Operation not permitted", str(path))
187 return real_stat(path, *args, **kwargs)
188
189 def simulated_py314_is_dir(path, *args, **kwargs):
190 if path == denied_user:
191 return False
192 return real_is_dir(path, *args, **kwargs)
193
194 with patch("lib.cookie_extract.Path", return_value=users), patch.object(
195 Path, "stat", guarded_stat
196 ), patch.object(Path, "is_dir", simulated_py314_is_dir):
197 found = cookie_extract._get_wsl_firefox_profiles_dir()
198 assert found == available
199
200
201 def test_linux_firefox_directory_tries_xdg_after_default_denial(tmp_path, monkeypatch):
202 blocked = tmp_path / ".mozilla" / "firefox"
203 available = tmp_path / "xdg" / "mozilla" / "firefox"
204 available.mkdir(parents=True)
205 monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
206 real_stat = Path.stat
207 real_is_dir = Path.is_dir
208
209 def guarded_stat(path, *args, **kwargs):
210 if path == blocked:
211 raise PermissionError(1, "Operation not permitted", str(path))
212 return real_stat(path, *args, **kwargs)
213
214 def simulated_py314_is_dir(path, *args, **kwargs):
215 if path == blocked:
216 return False
217 return real_is_dir(path, *args, **kwargs)
218
219 with patch("lib.cookie_extract.Path.home", return_value=tmp_path), patch(
220 "lib.cookie_extract.platform.system", return_value="Linux"
221 ), patch.object(Path, "stat", guarded_stat), patch.object(
222 Path, "is_dir", simulated_py314_is_dir
223 ):
224 found = _get_firefox_profiles_dir()
225 assert found == available
226
227 @pytest.fixture
228 def mock_firefox_env(tmp_path):
229 """Create a mock Firefox profiles directory with cookies.sqlite.
230
231 Returns (profiles_dir, profile_dir) for patching.
232 """
233
234 def _make(
235 *,
236 profiles_ini=None, # type: Optional[str]
237 profiles=None, # type: Optional[Dict[str, List[Tuple[str, str, str]]]]
238 default_profile="abc123.default-release", # type: str
239 ):
240 profiles_dir = tmp_path / "Firefox"
241 profiles_dir.mkdir(parents=True, exist_ok=True)
242
243 # Default: one profile with X cookies
244 if profiles is None:
245 profiles = {
246 default_profile: [
247 (".x.com", "auth_token", "tok_abc123"),
248 (".x.com", "ct0", "ct0_xyz789"),
249 (".x.com", "session", "sess_unrequested"),
250 (".example.com", "auth_token", "foreign_auth_token"),
251 (".example.com", "ct0", "foreign_ct0"),
252 (".example.com", "session", "sess_other"),
253 ],
254 }
255
256 # Create profile directories with cookies databases
257 for profile_name, cookies in profiles.items():
258 profile_dir = profiles_dir / profile_name
259 profile_dir.mkdir(parents=True, exist_ok=True)
260 db_path = profile_dir / "cookies.sqlite"
261 conn = sqlite3.connect(str(db_path))
262 conn.execute(
263 "CREATE TABLE moz_cookies ("
264 " id INTEGER PRIMARY KEY,"
265 " name TEXT NOT NULL,"
266 " value TEXT NOT NULL,"
267 " host TEXT NOT NULL,"
268 " path TEXT DEFAULT '/',"
269 " expiry INTEGER DEFAULT 0,"
270 " isSecure INTEGER DEFAULT 1,"
271 " isHttpOnly INTEGER DEFAULT 1,"
272 " sameSite INTEGER DEFAULT 0,"
273 " schemeMap INTEGER DEFAULT 0"
274 ")"
275 )
276 for host, name, value in cookies:
277 conn.execute(
278 "INSERT INTO moz_cookies (name, value, host) VALUES (?, ?, ?)",
279 (name, value, host),
280 )
281 conn.commit()
282 conn.close()
283
284 # Write profiles.ini
285 if profiles_ini is None:
286 profiles_ini = textwrap.dedent(f"""\
287 [General]
288 StartWithLastProfile=1
289
290 [Profile0]
291 Name=default-release
292 IsRelative=1
293 Path={default_profile}
294 Default=1
295 """)
296
297 (profiles_dir / "profiles.ini").write_text(profiles_ini)
298
299 return profiles_dir
300
301 return _make
302
303
304 def simulate_wsl_firefox(monkeypatch, profiles, blocked_database, error_code):
305 monkeypatch.setattr(cookie_extract.platform, "system", lambda: "Linux")
306 monkeypatch.setattr(cookie_extract, "_is_wsl", lambda: True)
307 monkeypatch.setattr(cookie_extract, "_get_firefox_profiles_dir", lambda: None)
308 monkeypatch.setattr(cookie_extract, "_get_wsl_firefox_profiles_dir", lambda: profiles)
309 monkeypatch.setattr(env, "REDDIT_SETUP_BROWSERS", ("firefox",))
310 real_connect = sqlite3.connect
311 blocked_uri = blocked_database.resolve().as_uri() + "?mode=ro"
312
313 def connect(database, *args, **kwargs):
314 if database == blocked_uri:
315 error = sqlite3.OperationalError("disk I/O error")
316 error.sqlite_errorcode = error_code
317 raise error
318 return real_connect(database, *args, **kwargs)
319
320 monkeypatch.setattr(sqlite3, "connect", connect)
321
322
323 def test_reddit_setup_reads_committed_windows_firefox_wal_after_shm_error(
324 tmp_path, monkeypatch, mock_firefox_env,
325 ):
326 profiles = mock_firefox_env(profiles={"abc123.default-release": []})
327 database = profiles / "abc123.default-release" / "cookies.sqlite"
328 scratch = tmp_path / "scratch"
329 scratch.mkdir()
330 monkeypatch.setattr(tempfile, "tempdir", str(scratch))
331 simulate_wsl_firefox(monkeypatch, profiles, database, sqlite3.SQLITE_IOERR_SHMOPEN)
332
333 with closing(sqlite3.connect(database)) as writer:
334 assert writer.execute("PRAGMA journal_mode=WAL").fetchone() == ("wal",)
335 writer.execute("PRAGMA wal_autocheckpoint=0")
336 writer.execute(
337 "INSERT INTO moz_cookies (name, value, host) VALUES (?, ?, ?)",
338 ("reddit_session", "dummy-committed", ".reddit.com"),
339 )
340 writer.commit()
341 assert database.with_name("cookies.sqlite-wal").stat().st_size > 0
342 writer.execute("UPDATE moz_cookies SET value = 'dummy-uncommitted'")
343
344 assert env.read_reddit_session_cookie({}, "firefox") == ("dummy-committed", "ok")
345 env_path = tmp_path / ".env"
346 result = setup_wizard.run_reddit_session_setup({}, env_path, consent=True)
347
348 assert result["status"] == "found" and result["browser"] == "firefox"
349 assert result["checked"] == [{"browser": "firefox", "result": "ok"}]
350 assert "dummy-committed" not in str(result)
351 assert "REDDIT_FROM_BROWSER=firefox" in env_path.read_text()
352 assert "dummy-committed" not in env_path.read_text()
353 assert list(scratch.iterdir()) == []
354
355
356 def test_reddit_setup_reports_unreadable_windows_firefox_database(
357 tmp_path, monkeypatch, mock_firefox_env,
358 ):
359 profiles = mock_firefox_env()
360 database = profiles / "abc123.default-release" / "cookies.sqlite"
361 simulate_wsl_firefox(monkeypatch, profiles, database, sqlite3.SQLITE_IOERR_SHMOPEN)
362
363 result = setup_wizard.run_reddit_session_setup({}, tmp_path / ".env", consent=True)
364
365 assert result["status"] == "not-found"
366 assert result["checked"] == [{"browser": "firefox", "result": "error"}]
367
368
369 def test_windows_firefox_wal_change_rejects_the_copied_pair(monkeypatch, mock_firefox_env):
370 profiles = mock_firefox_env()
371 database = profiles / "abc123.default-release" / "cookies.sqlite"
372 wal = database.with_name("cookies.sqlite-wal")
373 simulate_wsl_firefox(monkeypatch, profiles, database, sqlite3.SQLITE_IOERR_SHMOPEN)
374
375 with closing(sqlite3.connect(database)) as writer:
376 assert writer.execute("PRAGMA journal_mode=WAL").fetchone() == ("wal",)
377 writer.execute("INSERT INTO moz_cookies (name, value, host) VALUES "
378 "('reddit_session', 'dummy-old', '.reddit.com')")
379 writer.commit()
380 reads = 0
381 real_open = Path.open
382
383 def open_during_update(path, mode="r", *args, **kwargs):
384 nonlocal reads
385 if path == wal and mode == "rb":
386 reads += 1
387 if reads == 2:
388 writer.execute("UPDATE moz_cookies SET value = 'dummy-new' "
389 "WHERE name = 'reddit_session'")
390 writer.commit()
391 return real_open(path, mode, *args, **kwargs)
392
393 monkeypatch.setattr(Path, "open", open_during_update)
394 assert env.read_reddit_session_cookie({}, "firefox") == (None, "error")
395 assert reads == 2
396 assert writer.execute("SELECT value FROM moz_cookies WHERE name = 'reddit_session'").fetchone() == (
397 "dummy-new",
398 )
399
400
401 @pytest.mark.parametrize("condition, expected", [
402 ("zeroed-header", (None, "error")),
403 ("truncated-first-frame", (None, "error")),
404 ("truncated-trailing-frame", ("dummy-current", "ok")),
405 ])
406 def test_windows_firefox_wal_recovery_validates_initial_snapshot(
407 monkeypatch, mock_firefox_env, condition, expected,
408 ):
409 profiles = mock_firefox_env(profiles={
410 "abc123.default-release": [(".reddit.com", "reddit_session", "dummy-checkpointed")],
411 })
412 database = profiles / "abc123.default-release" / "cookies.sqlite"
413 wal = database.with_name("cookies.sqlite-wal")
414 simulate_wsl_firefox(monkeypatch, profiles, database, sqlite3.SQLITE_IOERR_SHMOPEN)
415
416 with closing(sqlite3.connect(database)) as writer:
417 assert writer.execute("PRAGMA journal_mode=WAL").fetchone() == ("wal",)
418 writer.execute("UPDATE moz_cookies SET value = 'dummy-current'")
419 writer.commit()
420 first_commit = wal.read_bytes()
421 page_size = int.from_bytes(first_commit[8:12], "big")
422 assert len(first_commit) == 32 + 24 + page_size
423 if condition == "truncated-trailing-frame":
424 writer.execute("UPDATE moz_cookies SET value = 'dummy-next'")
425 writer.commit()
426 original = wal.read_bytes()
427 if condition == "zeroed-header":
428 wal.write_bytes(bytes(32) + original[32:])
429 else:
430 wal.write_bytes(original[:-1])
431 try:
432 assert env.read_reddit_session_cookie({}, "firefox") == expected
433 finally:
434 wal.write_bytes(original)
435
436
437 def test_failed_windows_firefox_snapshot_does_not_hide_another_profile(
438 monkeypatch, mock_firefox_env,
439 ):
440 profiles = mock_firefox_env(profiles={
441 "abc123.default-release": [],
442 "xyz789.other": [
443 (".reddit.com", "reddit_session", "dummy-other"),
444 (".x.com", "auth_token", "dummy-auth"),
445 (".x.com", "ct0", "dummy-ct0"),
446 ],
447 })
448 blocked = profiles / "abc123.default-release" / "cookies.sqlite"
449 simulate_wsl_firefox(monkeypatch, profiles, blocked, sqlite3.SQLITE_IOERR_SHMOPEN)
450
451 assert env.read_reddit_session_cookie({}, "firefox") == ("dummy-other", "ok")
452 assert env.extract_browser_credentials({"FROM_BROWSER": "firefox", "BROWSER_CONSENT": "true"}) == {
453 "AUTH_TOKEN": "dummy-auth", "CT0": "dummy-ct0",
454 }
455
456
457 class TestExtractFirefoxCookies:
458 """Tests for extract_firefox_cookies."""
459
460 def test_partial_cookie_survives_later_profile_denial(self, mock_firefox_env, capsys):
461 profiles_dir = mock_firefox_env(
462 profiles={
463 "abc123.default-release": [(".x.com", "ct0", "dummy-ct0")],
464 "xyz789.other": [],
465 }
466 )
467 blocked = profiles_dir / "xyz789.other" / "cookies.sqlite"
468 real_copyfile = cookie_extract.copy_snapshot
469 requested = []
470
471 def guarded_copyfile(source, target):
472 if Path(source) == blocked:
473 raise PermissionError(1, "Operation not permitted", str(blocked))
474 return real_copyfile(source, target)
475
476 def extract_requested(_browser, domain, cookie_names):
477 if domain == ".x.com":
478 requested.append(cookie_names)
479 return cookie_extract._try_firefox_dir(profiles_dir, domain, cookie_names)
480
481 with patch("lib.cookie_extract.copy_snapshot", side_effect=guarded_copyfile), patch(
482 "lib.cookie_extract.extract_cookies",
483 side_effect=extract_requested,
484 ):
485 found = env.extract_browser_credentials({
486 "FROM_BROWSER": "firefox", "BROWSER_CONSENT": "true",
487 "AUTH_TOKEN": "dummy-auth",
488 })
489 assert found == {"CT0": "dummy-ct0"}
490 assert requested == [["auth_token", "ct0"], ["ct0"]]
491 assert "permission denied" in capsys.readouterr().err.lower()
492
493 def test_manual_token_keeps_complete_profile_preference_without_denial(self, mock_firefox_env):
494 profiles_dir = mock_firefox_env(
495 profiles={
496 "abc123.default-release": [(".x.com", "ct0", "stale-ct0")],
497 "xyz789.other": [
498 (".x.com", "auth_token", "dummy-auth"),
499 (".x.com", "ct0", "matching-ct0"),
500 ],
501 }
502 )
503 requested = []
504
505 def extract_requested(_browser, domain, cookie_names):
506 if domain == ".x.com":
507 requested.append(cookie_names)
508 return cookie_extract._try_firefox_dir(profiles_dir, domain, cookie_names)
509
510 with patch("lib.cookie_extract.extract_cookies", side_effect=extract_requested):
511 found = env.extract_browser_credentials({
512 "FROM_BROWSER": "firefox", "BROWSER_CONSENT": "true",
513 "AUTH_TOKEN": "dummy-auth",
514 })
515 assert found == {"CT0": "matching-ct0"}
516 assert requested == [["auth_token", "ct0"]]
517
518 def test_later_install_entry_outside_profiles_survives_first_denial(self, tmp_path):
519 profiles_dir = tmp_path / "Firefox"
520 profiles_dir.mkdir()
521 blocked = tmp_path / "blocked"
522 available = tmp_path / "external-profile"
523 available.mkdir()
524 (profiles_dir / "profiles.ini").write_text(
525 f"[InstallA]\nDefault={blocked}\n[InstallB]\nDefault={available}\n"
526 )
527 real_stat = Path.stat
528
529 def guarded_stat(path, *args, **kwargs):
530 if path == blocked:
531 raise PermissionError(1, "Operation not permitted", str(path))
532 return real_stat(path, *args, **kwargs)
533
534 with patch.object(Path, "stat", guarded_stat):
535 assert _find_default_profile(profiles_dir) == available
536
537 def test_denied_default_copy_uses_complete_pair_in_alternate_profile(self, mock_firefox_env):
538 profiles_dir = mock_firefox_env(
539 profiles={
540 "abc123.default-release": [],
541 "xyz789.other": [
542 (".x.com", "auth_token", "dummy-auth"),
543 (".x.com", "ct0", "dummy-ct0"),
544 ],
545 }
546 )
547 blocked = profiles_dir / "abc123.default-release" / "cookies.sqlite"
548 real_copyfile = cookie_extract.copy_snapshot
549
550 def guarded_copyfile(source, target):
551 if Path(source) == blocked:
552 raise PermissionError(1, "Operation not permitted", str(blocked))
553 return real_copyfile(source, target)
554
555 with patch("lib.cookie_extract.copy_snapshot", side_effect=guarded_copyfile):
556 found = cookie_extract._try_firefox_dir(
557 profiles_dir, ".x.com", ["auth_token", "ct0"]
558 )
559 assert found == {"auth_token": "dummy-auth", "ct0": "dummy-ct0"}
560
561 @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits are not reliable on Windows")
562 def test_temp_cookie_db_copy_is_owner_only(self, tmp_path):
563 """Copied cookie DB temp files are chmodded owner-only before read."""
564 db_path = tmp_path / "cookies.sqlite"
565 conn = sqlite3.connect(str(db_path))
566 conn.execute(
567 "CREATE TABLE moz_cookies (name TEXT NOT NULL, value TEXT NOT NULL, host TEXT NOT NULL)"
568 )
569 conn.execute(
570 "INSERT INTO moz_cookies (name, value, host) VALUES (?, ?, ?)",
571 ("auth_token", "tok_abc123", ".x.com"),
572 )
573 conn.commit()
574 conn.close()
575 os.chmod(db_path, 0o644)
576
577 real_connect = sqlite3.connect
578
579 def assert_temp_copy_locked(path, *args, **kwargs):
580 if kwargs.get("uri"):
581 assert path == db_path.resolve().as_uri() + "?mode=ro"
582 elif Path(str(path)) != db_path:
583 assert Path(str(path)).stat().st_mode & 0o777 == 0o600
584 return real_connect(path, *args, **kwargs)
585
586 with patch("lib.cookie_extract.sqlite3.connect", side_effect=assert_temp_copy_locked):
587 result = _query_cookies_db(db_path, ".x.com", ["auth_token"])
588
589 assert result == {"auth_token": "tok_abc123"}
590
591 @pytest.mark.skipif(os.name == "nt", reason="POSIX permission model does not apply on Windows; mkstemp is 0o666 there")
592 def test_temp_cookie_copy_never_world_readable(self, tmp_path):
593 """The temp copy must be private the instant it exists, not only after
594 the lock chmod. Regression for the TOCTOU window where copy2 widened the
595 0600 mkstemp file to the source's 0644 before _lock_temp_cookie_copy ran.
596 """
597 db_path = tmp_path / "cookies.sqlite"
598 conn = sqlite3.connect(str(db_path))
599 conn.execute(
600 "CREATE TABLE moz_cookies (name TEXT NOT NULL, value TEXT NOT NULL, host TEXT NOT NULL)"
601 )
602 conn.execute(
603 "INSERT INTO moz_cookies (name, value, host) VALUES (?, ?, ?)",
604 ("auth_token", "tok_abc123", ".x.com"),
605 )
606 conn.commit()
607 conn.close()
608 os.chmod(db_path, 0o644) # loose source perms, as Firefox ships them
609
610 observed = {}
611 real_lock = cookie_extract._lock_temp_cookie_copy
612
613 def spy(path):
614 # Mode of the copy as it exists right after copyfile, before chmod.
615 observed["mode_after_copy"] = os.stat(path).st_mode & 0o777
616 return real_lock(path)
617
618 with patch.object(cookie_extract, "_lock_temp_cookie_copy", side_effect=spy):
619 _query_cookies_db(db_path, ".x.com", ["auth_token"])
620
621 assert observed["mode_after_copy"] == 0o600
622
623 def test_valid_cookies_extracted(self, mock_firefox_env):
624 """Cookies for the target domain are returned correctly."""
625 profiles_dir = mock_firefox_env()
626
627 with patch(
628 "lib.cookie_extract._get_firefox_profiles_dir",
629 return_value=profiles_dir,
630 ):
631 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
632
633 assert result == {"auth_token": "tok_abc123", "ct0": "ct0_xyz789"}
634
635 def test_multiple_profiles_selects_default(self, mock_firefox_env):
636 """When multiple profiles exist, the one with Default=1 is used."""
637 profiles_dir = mock_firefox_env(
638 profiles={
639 "aaa111.other": [
640 (".x.com", "auth_token", "wrong_token"),
641 ],
642 "bbb222.default-release": [
643 (".x.com", "auth_token", "correct_token"),
644 (".x.com", "ct0", "correct_ct0"),
645 ],
646 },
647 profiles_ini=textwrap.dedent("""\
648 [General]
649 StartWithLastProfile=1
650
651 [Profile0]
652 Name=other
653 IsRelative=1
654 Path=aaa111.other
655
656 [Profile1]
657 Name=default-release
658 IsRelative=1
659 Path=bbb222.default-release
660 Default=1
661 """),
662 )
663
664 with patch(
665 "lib.cookie_extract._get_firefox_profiles_dir",
666 return_value=profiles_dir,
667 ):
668 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
669
670 assert result is not None
671 assert result["auth_token"] == "correct_token"
672 assert result["ct0"] == "correct_ct0"
673
674 def test_firefox_not_installed(self):
675 """Returns None when Firefox profiles directory doesn't exist."""
676 with patch(
677 "lib.cookie_extract._get_firefox_profiles_dir",
678 return_value=None,
679 ), patch(
680 "lib.cookie_extract._is_wsl",
681 return_value=False,
682 ):
683 result = extract_firefox_cookies(".x.com", ["auth_token"])
684
685 assert result is None
686
687 def test_default_partial_yields_to_complete_non_default(self, mock_firefox_env):
688 """Default profile holds a lone ct0 (logged-out); the logged-in
689 non-default profile's complete pair wins."""
690 profiles_dir = mock_firefox_env(
691 profiles={
692 "aaa111.default": [
693 (".x.com", "ct0", "partial_ct0"),
694 ],
695 "bbb222.release": [
696 (".x.com", "auth_token", "tok_complete"),
697 (".x.com", "ct0", "ct0_complete"),
698 ],
699 },
700 profiles_ini=textwrap.dedent("""\
701 [General]
702 StartWithLastProfile=1
703
704 [Profile0]
705 Name=default
706 IsRelative=1
707 Path=aaa111.default
708 Default=1
709
710 [Profile1]
711 Name=release
712 IsRelative=1
713 Path=bbb222.release
714 """),
715 )
716
717 with patch(
718 "lib.cookie_extract._get_firefox_profiles_dir",
719 return_value=profiles_dir,
720 ):
721 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
722
723 assert result is not None
724 assert result["auth_token"] == "tok_complete"
725 assert result["ct0"] == "ct0_complete"
726
727 def test_partial_fallback_when_no_complete_profile(self, mock_firefox_env):
728 """With no complete profile anywhere, the first partial is kept."""
729 profiles_dir = mock_firefox_env(
730 profiles={
731 "aaa111.default": [
732 (".x.com", "ct0", "partial_ct0"),
733 ],
734 },
735 profiles_ini=textwrap.dedent("""\
736 [General]
737 StartWithLastProfile=1
738
739 [Profile0]
740 Name=default
741 IsRelative=1
742 Path=aaa111.default
743 Default=1
744 """),
745 )
746
747 with patch(
748 "lib.cookie_extract._get_firefox_profiles_dir",
749 return_value=profiles_dir,
750 ):
751 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
752
753 assert result == {"ct0": "partial_ct0"}
754
755 def test_cookies_sqlite_empty(self, mock_firefox_env):
756 """Returns None when cookies.sqlite has no rows."""
757 profiles_dir = mock_firefox_env(
758 profiles={"abc123.default-release": []}, # no cookies
759 )
760
761 with patch(
762 "lib.cookie_extract._get_firefox_profiles_dir",
763 return_value=profiles_dir,
764 ), patch(
765 "lib.cookie_extract._is_wsl",
766 return_value=False,
767 ):
768 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
769
770 assert result is None
771
772 def test_domain_has_no_cookies(self, mock_firefox_env):
773 """Returns None when cookies exist but not for the target domain."""
774 profiles_dir = mock_firefox_env(
775 profiles={
776 "abc123.default-release": [
777 (".example.com", "auth_token", "foreign_auth_token"),
778 (".example.com", "ct0", "foreign_ct0"),
779 (".example.com", "session", "sess_123"),
780 ],
781 },
782 )
783
784 with patch(
785 "lib.cookie_extract._get_firefox_profiles_dir",
786 return_value=profiles_dir,
787 ), patch(
788 "lib.cookie_extract._is_wsl",
789 return_value=False,
790 ):
791 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
792
793 assert result is None
794
795 def test_malformed_profiles_ini_falls_back(self, mock_firefox_env):
796 """Falls back to first profile on disk when profiles.ini is garbage."""
797 profiles_dir = mock_firefox_env(
798 profiles={
799 "zzz999.fallback": [
800 (".x.com", "auth_token", "fallback_token"),
801 ],
802 },
803 profiles_ini="this is not valid ini content\n[[[broken",
804 )
805
806 with patch(
807 "lib.cookie_extract._get_firefox_profiles_dir",
808 return_value=profiles_dir,
809 ):
810 result = extract_firefox_cookies(".x.com", ["auth_token"])
811
812 assert result is not None
813 assert result["auth_token"] == "fallback_token"
814
815 def test_utf16_profiles_ini_uses_install_default(self, mock_firefox_env):
816 """Firefox on Windows writes UTF-16 LE profiles.ini (#1067)."""
817 default_profile = "en3ndvop.default-release"
818 decoy = "aaa111.decoy"
819 profiles_dir = mock_firefox_env(
820 default_profile=default_profile,
821 profiles={
822 decoy: [
823 (".x.com", "auth_token", "decoy_token"),
824 ],
825 default_profile: [
826 (".x.com", "auth_token", "utf16_token"),
827 (".x.com", "ct0", "utf16_ct0"),
828 ],
829 },
830 )
831 ini = textwrap.dedent(f"""\
832 [Install308046B0AF4A39CB]
833 Default={default_profile}
834 Locked=1
835 """)
836 (profiles_dir / "profiles.ini").write_bytes(ini.encode("utf-16"))
837
838 with patch(
839 "lib.cookie_extract._get_firefox_profiles_dir",
840 return_value=profiles_dir,
841 ):
842 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
843
844 assert result is not None
845 assert result["auth_token"] == "utf16_token"
846 assert result["ct0"] == "utf16_ct0"
847
848 def test_non_default_profile_with_cookies(self, mock_firefox_env):
849 """Falls back to non-default profile when default has no X cookies."""
850 profiles_dir = mock_firefox_env(
851 profiles={
852 "aaa111.default": [
853 (".example.com", "session", "sess_other"),
854 ],
855 "bbb222.release": [
856 (".x.com", "auth_token", "tok_nondefault"),
857 (".x.com", "ct0", "ct0_nondefault"),
858 ],
859 },
860 profiles_ini=textwrap.dedent("""\
861 [General]
862 StartWithLastProfile=1
863
864 [Profile0]
865 Name=default
866 IsRelative=1
867 Path=aaa111.default
868 Default=1
869
870 [Profile1]
871 Name=release
872 IsRelative=1
873 Path=bbb222.release
874 """),
875 )
876
877 with patch(
878 "lib.cookie_extract._get_firefox_profiles_dir",
879 return_value=profiles_dir,
880 ):
881 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
882
883 assert result is not None
884 assert result["auth_token"] == "tok_nondefault"
885 assert result["ct0"] == "ct0_nondefault"
886
887 def test_multiple_profiles_none_have_cookies(self, mock_firefox_env):
888 """Returns None when no profile has matching cookies."""
889 profiles_dir = mock_firefox_env(
890 profiles={
891 "aaa111.default": [
892 (".example.com", "session", "sess_a"),
893 ],
894 "bbb222.release": [
895 (".other.com", "other", "val_b"),
896 ],
897 },
898 profiles_ini=textwrap.dedent("""\
899 [General]
900 StartWithLastProfile=1
901
902 [Profile0]
903 Name=default
904 IsRelative=1
905 Path=aaa111.default
906 Default=1
907
908 [Profile1]
909 Name=release
910 IsRelative=1
911 Path=bbb222.release
912 """),
913 )
914
915 with patch(
916 "lib.cookie_extract._get_firefox_profiles_dir",
917 return_value=profiles_dir,
918 ), patch(
919 "lib.cookie_extract._is_wsl",
920 return_value=False,
921 ):
922 result = extract_firefox_cookies(".x.com", ["auth_token", "ct0"])
923
924 assert result is None
925
926
927 class TestExtractCookiesAuto:
928 """Tests for extract_cookies with browser='auto'."""
929
930 def test_auto_macos_tries_chrome_then_firefox(self, mock_firefox_env):
931 """On macOS, auto tries the Chromium family first, falls back to Firefox."""
932 profiles_dir = mock_firefox_env()
933
934 # Mock every Chromium-family extractor to None so the test is hermetic
935 # regardless of which browsers are actually installed/logged-in on the
936 # machine running it (auto tries these before Firefox).
937 with (
938 patch("lib.cookie_extract.platform.system", return_value="Darwin"),
939 patch("lib.cookie_extract.extract_chrome_cookies", return_value=None),
940 patch("lib.cookie_extract.extract_brave_cookies", return_value=None),
941 patch("lib.cookie_extract.extract_edge_cookies", return_value=None),
942 patch("lib.cookie_extract.extract_vivaldi_cookies", return_value=None),
943 patch("lib.cookie_extract.extract_opera_cookies", return_value=None),
944 patch("lib.cookie_extract.extract_arc_cookies", return_value=None),
945 patch("lib.cookie_extract.extract_dia_cookies", return_value=None),
946 patch("lib.cookie_extract.extract_chromium_cookies", return_value=None),
947 patch("lib.cookie_extract.extract_safari_cookies", return_value=None),
948 patch(
949 "lib.cookie_extract._get_firefox_profiles_dir",
950 return_value=profiles_dir,
951 ),
952 ):
953 result = extract_cookies("auto", ".x.com", ["auth_token", "ct0"])
954
955 # All Chromium browsers and Safari return None, Firefox succeeds
956 assert result is not None
957 assert result["auth_token"] == "tok_abc123"
958 assert result["ct0"] == "ct0_xyz789"
959
960 def test_auto_linux_tries_firefox_only(self, mock_firefox_env):
961 """On Linux, auto only tries Firefox."""
962 profiles_dir = mock_firefox_env()
963
964 with (
965 patch("lib.cookie_extract.platform.system", return_value="Linux"),
966 patch(
967 "lib.cookie_extract._get_firefox_profiles_dir",
968 return_value=profiles_dir,
969 ),
970 ):
971 result = extract_cookies("auto", ".x.com", ["auth_token", "ct0"])
972
973 assert result is not None
974 assert result["auth_token"] == "tok_abc123"
975
976 def test_explicit_firefox(self, mock_firefox_env):
977 """Explicit browser='firefox' goes directly to Firefox."""
978 profiles_dir = mock_firefox_env()
979
980 with patch(
981 "lib.cookie_extract._get_firefox_profiles_dir",
982 return_value=profiles_dir,
983 ):
984 result = extract_cookies("firefox", ".x.com", ["auth_token"])
985
986 assert result is not None
987 assert result["auth_token"] == "tok_abc123"
988
989 def test_unknown_browser_returns_none(self):
990 """Unknown browser name returns None."""
991 result = extract_cookies("netscape", ".x.com", ["auth_token"])
992 assert result is None
993
994 def test_chrome_delegates_to_chrome_module(self):
995 """Chrome extraction delegates to chrome_cookies module."""
996 with patch(
997 "lib.cookie_extract.extract_chrome_cookies",
998 return_value={"auth_token": "chrome_tok"},
999 ):
1000 result = extract_cookies("chrome", ".x.com", ["auth_token"])
1001 assert result == {"auth_token": "chrome_tok"}
1002
1003 def test_safari_delegates_to_safari_module(self):
1004 """Safari extraction delegates to safari_cookies module."""
1005 with patch(
1006 "lib.cookie_extract.extract_safari_cookies",
1007 return_value={"auth_token": "safari_tok"},
1008 ):
1009 result = extract_cookies("safari", ".x.com", ["auth_token"])
1010 assert result == {"auth_token": "safari_tok"}
1011
1012
1013 class TestHasCompletePair:
1014 """Tests for the shared has_complete_pair() helper."""
1015
1016 def test_none_is_incomplete(self):
1017 assert has_complete_pair(None, ["auth_token", "ct0"]) is False
1018
1019 def test_empty_is_incomplete(self):
1020 assert has_complete_pair({}, ["auth_token", "ct0"]) is False
1021
1022 def test_partial_pair_is_incomplete(self):
1023 assert has_complete_pair({"ct0": "x"}, ["auth_token", "ct0"]) is False
1024
1025 def test_empty_valued_pair_is_incomplete(self):
1026 assert has_complete_pair({"auth_token": "", "ct0": ""}, ["auth_token", "ct0"]) is False
1027 assert has_complete_pair({"auth_token": "a", "ct0": ""}, ["auth_token", "ct0"]) is False
1028
1029 def test_complete_pair(self):
1030 assert has_complete_pair(
1031 {"auth_token": "a", "ct0": "c"}, ["auth_token", "ct0"]
1032 ) is True
1033
1034 def test_single_cookie_service(self):
1035 assert has_complete_pair({"_session_id": "s"}, ["_session_id"]) is True
1036
1037 def test_extra_keys_still_complete(self):
1038 assert has_complete_pair(
1039 {"auth_token": "a", "ct0": "c", "other": "o"},
1040 ["auth_token", "ct0"],
1041 ) is True
1042
1042 lines PYTHON