返回 last30days-skill
test_chrome_cookies.py
根目录 / tests / test_chrome_cookies.py
1 """Tests for Chrome cookie extraction on macOS."""
2
3 import hashlib
4 import os
5 import sqlite3
6 import shutil
7 import subprocess
8 import tempfile
9 from pathlib import Path
10 from unittest import mock
11
12 import pytest
13
14 OPENSSL_AVAILABLE = shutil.which("openssl") is not None
15
16 from lib import chrome_cookies
17 from lib.chrome_cookies import (
18 CHROME_COOKIES_DB,
19 CHROME_IV_HEX,
20 CHROME_KEY_LENGTH,
21 CHROME_PBKDF2_ITERATIONS,
22 CHROME_SALT,
23 _derive_aes_key,
24 _get_chrome_encryption_key,
25 _get_db_version,
26 _remove_pkcs7_padding,
27 _extract_chromium_cookies_macos,
28 _decrypt_v10_value,
29 _find_chromium_cookies_db,
30 extract_chrome_cookies_macos,
31 )
32
33
34 def test_cookie_copy_permission_denial_is_not_reported_as_missing(tmp_path):
35 db = tmp_path / "Cookies"
36 db.touch()
37 with mock.patch(
38 "lib.chrome_cookies.copy_snapshot",
39 side_effect=PermissionError(1, "Operation not permitted", str(db)),
40 ):
41 with pytest.raises(PermissionError):
42 _extract_chromium_cookies_macos(
43 db, "Microsoft Edge Safe Storage", ".x.com", ["auth_token", "ct0"]
44 )
45
46
47 def test_temporary_storage_denial_is_not_blamed_on_browser_access(tmp_path):
48 db = tmp_path / "Cookies"
49 db.touch()
50 denied_temp = tmp_path / "temporary.sqlite"
51 with mock.patch(
52 "lib.chrome_cookies.copy_snapshot",
53 side_effect=PermissionError(13, "Permission denied", str(denied_temp)),
54 ):
55 assert _extract_chromium_cookies_macos(
56 db, "Microsoft Edge Safe Storage", ".x.com", ["auth_token", "ct0"]
57 ) is None
58
59
60 def test_keychain_permission_denial_is_not_blamed_on_browser_database():
61 with mock.patch(
62 "lib.chrome_cookies.subprocess.run",
63 side_effect=PermissionError(1, "Operation not permitted", "security"),
64 ):
65 assert chrome_cookies._get_chromium_encryption_key("Microsoft Edge Safe Storage") is None
66
67
68 def test_profile_discovery_preserves_permission_denial_when_stat_fails(tmp_path):
69 blocked = tmp_path / "Default" / "Network" / "Cookies"
70 real_stat = Path.stat
71 real_exists = Path.exists
72
73 def guarded_stat(path, *args, **kwargs):
74 if path == blocked:
75 raise PermissionError(1, "Operation not permitted", str(path))
76 return real_stat(path, *args, **kwargs)
77
78 def simulated_py314_exists(path, *args, **kwargs):
79 if path == blocked:
80 return False
81 return real_exists(path, *args, **kwargs)
82
83 with mock.patch.object(Path, "stat", guarded_stat), mock.patch.object(
84 Path, "exists", simulated_py314_exists
85 ):
86 with pytest.raises(PermissionError):
87 chrome_cookies._profile_cookie_db(tmp_path / "Default")
88
89
90 def test_profile_directory_discovery_preserves_permission_denial(tmp_path):
91 blocked = tmp_path / "Profile 1"
92 blocked.mkdir()
93 real_stat = Path.stat
94 real_is_dir = Path.is_dir
95
96 def guarded_stat(path, *args, **kwargs):
97 if path == blocked:
98 raise PermissionError(1, "Operation not permitted", str(path))
99 return real_stat(path, *args, **kwargs)
100
101 def simulated_py314_is_dir(path, *args, **kwargs):
102 if path == blocked:
103 return False
104 return real_is_dir(path, *args, **kwargs)
105
106 with mock.patch.object(Path, "stat", guarded_stat), mock.patch.object(
107 Path, "is_dir", simulated_py314_is_dir
108 ):
109 with pytest.raises(PermissionError):
110 chrome_cookies._find_all_chromium_cookies_dbs(tmp_path)
111
112 # ---------------------------------------------------------------------------
113 # Helpers — create real encrypted cookie values using known key + system openssl
114 # ---------------------------------------------------------------------------
115
116 KNOWN_PASSPHRASE = b"test_passphrase_for_unit_tests"
117 KNOWN_AES_KEY = _derive_aes_key(KNOWN_PASSPHRASE)
118 # Independent v10 vectors: PBKDF2-HMAC-SHA1, saltysalt, 1003 iterations,
119 # 16-byte key; OpenSSL AES-128-CBC with a 16-space IV and PKCS7 padding.
120 V10_AES_KEY = bytes.fromhex("bae7b43668299f6b6839c58cff9e97db")
121 V10_AUTH_TOKEN = bytes.fromhex(
122 "76313040a19511ccca2ce72c5b842326adf2e97a36831c0c5943045f7d66f96cbf011e"
123 )
124 V10_CT0 = bytes.fromhex("763130189b696f39999dba1b0c8f9c005b8a24")
125
126
127 def _encrypt_value_v10(plaintext: str, aes_key: bytes) -> bytes:
128 """Encrypt a value the same way Chrome v10 does, using system openssl.
129
130 Returns b'v10' + AES-128-CBC ciphertext with PKCS7 padding.
131 """
132 hex_key = aes_key.hex()
133 result = subprocess.run(
134 [
135 "openssl", "enc", "-aes-128-cbc", "-e",
136 "-K", hex_key,
137 "-iv", CHROME_IV_HEX,
138 ],
139 input=plaintext.encode("utf-8"),
140 capture_output=True,
141 timeout=5,
142 )
143 assert result.returncode == 0, f"openssl encrypt failed: {result.stderr}"
144 return b"v10" + result.stdout
145
146
147 def _encrypt_value_v10_with_sha_prefix(plaintext: str, aes_key: bytes) -> bytes:
148 """Encrypt with a 32-byte SHA-256 prefix (Chrome 130+ style)."""
149 raw = b"\x00" * 32 + plaintext.encode("utf-8")
150 hex_key = aes_key.hex()
151 result = subprocess.run(
152 [
153 "openssl", "enc", "-aes-128-cbc", "-e",
154 "-K", hex_key,
155 "-iv", CHROME_IV_HEX,
156 ],
157 input=raw,
158 capture_output=True,
159 timeout=5,
160 )
161 assert result.returncode == 0, f"openssl encrypt failed: {result.stderr}"
162 return b"v10" + result.stdout
163
164
165 def _create_chrome_cookies_db(path: str, cookies: list[tuple], db_version: int = 20) -> None:
166 """Create a minimal Chrome Cookies SQLite database.
167
168 cookies: list of (host_key, name, value, encrypted_value) tuples
169 """
170 conn = sqlite3.connect(path)
171 c = conn.cursor()
172 c.execute("CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT)")
173 c.execute("INSERT OR REPLACE INTO meta (key, value) VALUES ('version', ?)", (str(db_version),))
174 c.execute(
175 "CREATE TABLE IF NOT EXISTS cookies ("
176 " host_key TEXT NOT NULL,"
177 " name TEXT NOT NULL,"
178 " value TEXT NOT NULL DEFAULT '',"
179 " encrypted_value BLOB NOT NULL DEFAULT x'',"
180 " path TEXT NOT NULL DEFAULT '/',"
181 " expires_utc INTEGER NOT NULL DEFAULT 0,"
182 " is_secure INTEGER NOT NULL DEFAULT 1,"
183 " is_httponly INTEGER NOT NULL DEFAULT 1,"
184 " creation_utc INTEGER NOT NULL DEFAULT 0,"
185 " last_access_utc INTEGER NOT NULL DEFAULT 0,"
186 " has_expires INTEGER NOT NULL DEFAULT 1,"
187 " is_persistent INTEGER NOT NULL DEFAULT 1,"
188 " priority INTEGER NOT NULL DEFAULT 1,"
189 " samesite INTEGER NOT NULL DEFAULT 0,"
190 " source_scheme INTEGER NOT NULL DEFAULT 2,"
191 " source_port INTEGER NOT NULL DEFAULT 443,"
192 " last_update_utc INTEGER NOT NULL DEFAULT 0"
193 ")"
194 )
195 for host_key, name, value, encrypted_value in cookies:
196 c.execute(
197 "INSERT INTO cookies (host_key, name, value, encrypted_value) VALUES (?, ?, ?, ?)",
198 (host_key, name, value, encrypted_value),
199 )
200 conn.commit()
201 conn.close()
202
203
204 @pytest.mark.parametrize("domain", [".x.com", "x.com", ".example.test", "example.test"])
205 def test_chromium_cookie_host_family_and_requested_names(tmp_path, domain):
206 host = domain.lstrip(".")
207 db = tmp_path / "Cookies"
208 _create_chrome_cookies_db(str(db), [
209 (host, "auth_token", "dummy-auth", b""),
210 ("." + host, "ct0", "dummy-ct0", b""),
211 ("sub." + host, "sub_cookie", "dummy-sub", b""),
212 ("not" + host, "near_cookie", "dummy-near", b""),
213 (host + ".example", "suffix_cookie", "dummy-suffix", b""),
214 (host, "unrequested", "dummy-other", b""),
215 ])
216 with mock.patch("lib.chrome_cookies._get_chromium_encryption_key") as key:
217 result = _extract_chromium_cookies_macos(
218 db, "Chrome Safe Storage", domain,
219 ["auth_token", "ct0", "sub_cookie", "near_cookie", "suffix_cookie"],
220 )
221 assert result == {"auth_token": "dummy-auth", "ct0": "dummy-ct0"}
222 key.assert_not_called()
223
224
225 def test_denied_modern_path_uses_accessible_legacy_cookie_database(tmp_path):
226 profile = tmp_path / "Default"
227 profile.mkdir()
228 legacy = profile / "Cookies"
229 legacy.touch()
230 blocked = profile / "Network" / "Cookies"
231 real_stat = Path.stat
232
233 def guarded_stat(path, *args, **kwargs):
234 if path == blocked:
235 raise PermissionError(1, "Operation not permitted", str(path))
236 return real_stat(path, *args, **kwargs)
237
238 with mock.patch.object(Path, "stat", guarded_stat):
239 assert chrome_cookies._profile_cookie_db(profile) == legacy
240
241
242 def test_denied_default_copy_uses_complete_pair_in_later_profile(tmp_path):
243 default = tmp_path / "Default" / "Network"
244 alternate = tmp_path / "Profile 1" / "Network"
245 default.mkdir(parents=True)
246 alternate.mkdir(parents=True)
247 blocked = default / "Cookies"
248 blocked.touch()
249 available = alternate / "Cookies"
250 _create_chrome_cookies_db(str(available), [
251 (".x.com", "auth_token", "dummy-auth", b""),
252 (".x.com", "ct0", "dummy-ct0", b""),
253 ])
254 real_copyfile = chrome_cookies.copy_snapshot
255
256 def guarded_copyfile(source, target):
257 if Path(source) == blocked:
258 raise PermissionError(1, "Operation not permitted", str(blocked))
259 return real_copyfile(source, target)
260
261 with mock.patch("lib.chrome_cookies.copy_snapshot", side_effect=guarded_copyfile):
262 found = chrome_cookies._extract_chromium_cookies_any_profile(
263 tmp_path, "Chrome Safe Storage", ".x.com", ["auth_token", "ct0"]
264 )
265 assert found == {"auth_token": "dummy-auth", "ct0": "dummy-ct0"}
266
267 # ---------------------------------------------------------------------------
268 # PKCS7 padding tests
269 # ---------------------------------------------------------------------------
270
271
272 class TestPkcs7Padding:
273 def test_valid_padding_1(self):
274 # 1 byte of padding
275 data = b"hello world!!!!!" + b"\x01"
276 assert _remove_pkcs7_padding(data) == b"hello world!!!!!"
277
278 def test_valid_padding_5(self):
279 data = b"hello world" + b"\x05\x05\x05\x05\x05"
280 assert _remove_pkcs7_padding(data) == b"hello world"
281
282 def test_valid_padding_16(self):
283 # Full block of padding
284 data = b"\x10" * 16
285 assert _remove_pkcs7_padding(data) == b""
286
287 def test_invalid_padding_zero(self):
288 data = b"hello\x00"
289 assert _remove_pkcs7_padding(data) is None
290
291 def test_invalid_padding_mismatch(self):
292 data = b"hello\x03\x03\x02"
293 assert _remove_pkcs7_padding(data) is None
294
295 def test_empty_data(self):
296 assert _remove_pkcs7_padding(b"") is None
297
298 # ---------------------------------------------------------------------------
299 # Key derivation test
300 # ---------------------------------------------------------------------------
301
302
303 class TestKeyDerivation:
304 def test_derive_aes_key_matches_v10_known_answer(self):
305 assert _derive_aes_key(KNOWN_PASSPHRASE) == V10_AES_KEY
306
307 def test_derive_aes_key_deterministic(self):
308 key1 = _derive_aes_key(b"my_passphrase")
309 key2 = _derive_aes_key(b"my_passphrase")
310 assert key1 == key2
311 assert len(key1) == 16
312
313 def test_derive_aes_key_different_passphrases(self):
314 key1 = _derive_aes_key(b"passphrase_a")
315 key2 = _derive_aes_key(b"passphrase_b")
316 assert key1 != key2
317
318 # ---------------------------------------------------------------------------
319 # Decryption test (real openssl, known key)
320 # ---------------------------------------------------------------------------
321
322
323 @pytest.mark.skipif(not OPENSSL_AVAILABLE, reason="openssl not installed")
324 class TestDecryption:
325 def test_decrypt_v10_roundtrip(self):
326 """Encrypt then decrypt — verifies the full pipeline works."""
327 original = "my_secret_cookie_value_12345"
328 encrypted = _encrypt_value_v10(original, KNOWN_AES_KEY)
329 assert encrypted[:3] == b"v10"
330
331 decrypted = _decrypt_v10_value(encrypted, KNOWN_AES_KEY, db_version=20)
332 assert decrypted == original
333
334 def test_decrypt_v10_chrome130_with_sha_prefix(self):
335 """Chrome 130+ (db_version >= 24) strips 32-byte SHA-256 prefix."""
336 original = "session_token_abc"
337 encrypted = _encrypt_value_v10_with_sha_prefix(original, KNOWN_AES_KEY)
338
339 decrypted = _decrypt_v10_value(encrypted, KNOWN_AES_KEY, db_version=24)
340 assert decrypted == original
341
342 def test_decrypt_wrong_key_returns_none_or_garbage(self):
343 """Wrong key should either fail decryption or produce garbage."""
344 original = "secret"
345 encrypted = _encrypt_value_v10(original, KNOWN_AES_KEY)
346 wrong_key = _derive_aes_key(b"wrong_passphrase")
347
348 result = _decrypt_v10_value(encrypted, wrong_key, db_version=20)
349 # Either None (padding check fails) or garbage (not the original)
350 assert result is None or result != original
351
352 def test_decrypt_empty_ciphertext(self):
353 """v10 prefix with no ciphertext should return None."""
354 assert _decrypt_v10_value(b"v10", KNOWN_AES_KEY, db_version=20) is None
355
356 # ---------------------------------------------------------------------------
357 # Chrome not installed → returns None
358 # ---------------------------------------------------------------------------
359
360
361 class TestChromeNotInstalled:
362 def test_db_not_found(self):
363 with mock.patch(
364 "lib.chrome_cookies._find_all_chromium_cookies_dbs",
365 return_value=[],
366 ):
367 result = extract_chrome_cookies_macos(".x.com", ["auth_token"])
368 assert result is None
369
370
371 class TestChromiumCookieDbFinder:
372 def test_legacy_single_db_finder_returns_first_all_profile_candidate(self, tmp_path):
373 first = tmp_path / "Default" / "Network" / "Cookies"
374 second = tmp_path / "Profile 1" / "Network" / "Cookies"
375
376 with mock.patch(
377 "lib.chrome_cookies._find_all_chromium_cookies_dbs",
378 return_value=[first, second],
379 ) as find_all:
380 result = _find_chromium_cookies_db(tmp_path)
381
382 assert result == first
383 find_all.assert_called_once_with(tmp_path)
384
385 # ---------------------------------------------------------------------------
386 # Keychain access denied → returns None
387 # ---------------------------------------------------------------------------
388
389
390 class TestKeychainDenied:
391 def test_security_command_fails(self):
392 with mock.patch("lib.chrome_cookies.subprocess.run") as mock_run:
393 mock_run.return_value = subprocess.CompletedProcess(
394 args=[], returncode=44, stdout="", stderr="security: SecKeychainSearchCopyNext: The specified item could not be found in the keychain."
395 )
396 result = _get_chrome_encryption_key()
397 assert result is None
398
399 def test_security_command_not_found(self):
400 with mock.patch("lib.chrome_cookies.subprocess.run", side_effect=FileNotFoundError):
401 result = _get_chrome_encryption_key()
402 assert result is None
403
404 # ---------------------------------------------------------------------------
405 # openssl not found → returns None
406 # ---------------------------------------------------------------------------
407
408
409 class TestInProcessDecryption:
410 def test_decrypts_without_openssl_subprocess(self):
411 with mock.patch("lib.chrome_cookies.subprocess.run", side_effect=AssertionError("no subprocess")):
412 result = _decrypt_v10_value(V10_AUTH_TOKEN, V10_AES_KEY, db_version=20)
413 assert result == "my_auth_token_123"
414
415 def test_decryptor_failure_returns_none(self):
416 with mock.patch("lib.chrome_cookies._decrypt_aes128_cbc", return_value=None):
417 assert _decrypt_v10_value(V10_AUTH_TOKEN, V10_AES_KEY, db_version=20) is None
418
419 # ---------------------------------------------------------------------------
420 # Unencrypted cookie values → returned as-is
421 # ---------------------------------------------------------------------------
422
423
424 class TestUnencryptedCookies:
425 @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits are not reliable on Windows")
426 def test_temp_cookie_db_copy_is_owner_only(self, tmp_path):
427 """Copied Chromium cookie DB temp files are chmodded owner-only before read."""
428 db_path = tmp_path / "Cookies"
429 _create_chrome_cookies_db(str(db_path), [
430 (".x.com", "auth_token", "plain_token_value", b""),
431 ])
432 os.chmod(db_path, 0o644)
433
434 real_connect = sqlite3.connect
435
436 def assert_temp_copy_locked(path, *args, **kwargs):
437 if kwargs.get("uri"):
438 assert path == db_path.resolve().as_uri() + "?mode=ro"
439 elif Path(str(path)) != db_path:
440 assert Path(str(path)).stat().st_mode & 0o777 == 0o600
441 return real_connect(path, *args, **kwargs)
442
443 with mock.patch("lib.chrome_cookies.sqlite3.connect", side_effect=assert_temp_copy_locked):
444 result = _extract_chromium_cookies_macos(
445 db_path,
446 "Chrome Safe Storage",
447 ".x.com",
448 ["auth_token"],
449 )
450
451 assert result == {"auth_token": "plain_token_value"}
452
453 @pytest.mark.skipif(os.name == "nt", reason="POSIX permission model does not apply on Windows")
454 def test_temp_cookie_copy_never_world_readable(self, tmp_path):
455 """The temp copy must stay private immediately after copying content."""
456 db_path = tmp_path / "Cookies"
457 _create_chrome_cookies_db(str(db_path), [
458 (".x.com", "auth_token", "plain_token_value", b""),
459 ])
460 os.chmod(db_path, 0o644)
461
462 observed = {}
463 real_lock = chrome_cookies._lock_temp_cookie_copy
464
465 def spy(path):
466 observed["mode_after_copy"] = os.stat(path).st_mode & 0o777
467 return real_lock(path)
468
469 with mock.patch.object(chrome_cookies, "_lock_temp_cookie_copy", side_effect=spy):
470 result = _extract_chromium_cookies_macos(
471 db_path,
472 "Chrome Safe Storage",
473 ".x.com",
474 ["auth_token"],
475 )
476
477 assert result == {"auth_token": "plain_token_value"}
478 assert observed["mode_after_copy"] == 0o600
479
480 def test_plain_value_returned(self, tmp_path):
481 """Unencrypted cookies (value column populated) returned without decryption."""
482 db_path = str(tmp_path / "Cookies")
483 _create_chrome_cookies_db(db_path, [
484 (".x.com", "auth_token", "plain_token_value", b""),
485 (".x.com", "ct0", "plain_ct0_value", b""),
486 ])
487
488 with mock.patch(
489 "lib.chrome_cookies._find_all_chromium_cookies_dbs",
490 return_value=[Path(db_path)],
491 ):
492 # No keychain needed for unencrypted values
493 with mock.patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=None):
494 result = extract_chrome_cookies_macos(".x.com", ["auth_token", "ct0"])
495
496 assert result == {"auth_token": "plain_token_value", "ct0": "plain_ct0_value"}
497
498 # ---------------------------------------------------------------------------
499 # Full integration: mock DB with real v10 encryption, mock Keychain
500 # ---------------------------------------------------------------------------
501
502
503 class TestFullExtraction:
504 @pytest.mark.skipif(not OPENSSL_AVAILABLE, reason="openssl not installed")
505 def test_encrypted_cookies_extracted(self, tmp_path):
506 """Extract fixed v10 vectors through SQLite, key derivation, and OpenSSL."""
507 auth_val = "my_auth_token_123"
508 ct0_val = "my_ct0_csrf_456"
509
510 db_path = str(tmp_path / "Cookies")
511 _create_chrome_cookies_db(db_path, [
512 (".x.com", "auth_token", "", V10_AUTH_TOKEN),
513 (".x.com", "ct0", "", V10_CT0),
514 (".other.com", "other", "", b""), # unrelated cookie
515 ])
516
517 with mock.patch(
518 "lib.chrome_cookies._find_all_chromium_cookies_dbs",
519 return_value=[Path(db_path)],
520 ):
521 with mock.patch(
522 "lib.chrome_cookies._get_chromium_encryption_key",
523 return_value=KNOWN_PASSPHRASE,
524 ):
525 result = extract_chrome_cookies_macos(".x.com", ["auth_token", "ct0"])
526
527 assert result == {"auth_token": auth_val, "ct0": ct0_val}
528
529 def test_no_matching_cookies_returns_none(self, tmp_path):
530 db_path = str(tmp_path / "Cookies")
531 _create_chrome_cookies_db(db_path, [
532 (".other.com", "session", "val", b""),
533 ])
534
535 with mock.patch(
536 "lib.chrome_cookies._find_all_chromium_cookies_dbs",
537 return_value=[Path(db_path)],
538 ):
539 with mock.patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=None):
540 result = extract_chrome_cookies_macos(".x.com", ["auth_token"])
541
542 assert result is None
543
544 @pytest.mark.skipif(not OPENSSL_AVAILABLE, reason="openssl not installed")
545 def test_chrome130_db_version_24(self, tmp_path):
546 """Chrome 130+ with db_version >= 24 strips SHA-256 prefix."""
547 auth_val = "token_for_chrome130"
548 encrypted_auth = _encrypt_value_v10_with_sha_prefix(auth_val, KNOWN_AES_KEY)
549
550 db_path = str(tmp_path / "Cookies")
551 _create_chrome_cookies_db(db_path, [
552 (".x.com", "auth_token", "", encrypted_auth),
553 ], db_version=24)
554
555 with mock.patch(
556 "lib.chrome_cookies._find_all_chromium_cookies_dbs",
557 return_value=[Path(db_path)],
558 ):
559 with mock.patch(
560 "lib.chrome_cookies._get_chromium_encryption_key",
561 return_value=KNOWN_PASSPHRASE,
562 ):
563 result = extract_chrome_cookies_macos(".x.com", ["auth_token"])
564
565 assert result is not None
566 assert result["auth_token"] == auth_val
567
568 @pytest.mark.skipif(not OPENSSL_AVAILABLE, reason="openssl not installed")
569 def test_multi_profile_extraction_reuses_keychain_key(self, tmp_path):
570 """Profiles for one browser share a Keychain service; fetch it once."""
571 first_db = tmp_path / "Default.sqlite"
572 second_db = tmp_path / "Profile1.sqlite"
573 auth_val = "profile_auth_token"
574 ct0_val = "profile_ct0_value"
575
576 _create_chrome_cookies_db(str(first_db), [
577 (".x.com", "auth_token", "", _encrypt_value_v10(auth_val, KNOWN_AES_KEY)),
578 ])
579 _create_chrome_cookies_db(str(second_db), [
580 (".x.com", "auth_token", "", _encrypt_value_v10(auth_val, KNOWN_AES_KEY)),
581 (".x.com", "ct0", "", _encrypt_value_v10(ct0_val, KNOWN_AES_KEY)),
582 ])
583
584 with mock.patch(
585 "lib.chrome_cookies._find_all_chromium_cookies_dbs",
586 return_value=[first_db, second_db],
587 ):
588 with mock.patch(
589 "lib.chrome_cookies._get_chromium_encryption_key",
590 return_value=KNOWN_PASSPHRASE,
591 ) as get_key:
592 result = extract_chrome_cookies_macos(".x.com", ["auth_token", "ct0"])
593
594 assert result is not None
595 assert result["ct0"] == ct0_val
596 get_key.assert_called_once_with("Chrome Safe Storage")
597
598 # ---------------------------------------------------------------------------
599 # DB version detection
600 # ---------------------------------------------------------------------------
601
602
603 class TestDbVersion:
604 def test_reads_version_from_meta(self, tmp_path):
605 db_path = str(tmp_path / "test.db")
606 conn = sqlite3.connect(db_path)
607 c = conn.cursor()
608 c.execute("CREATE TABLE meta (key TEXT, value TEXT)")
609 c.execute("INSERT INTO meta VALUES ('version', '24')")
610 conn.commit()
611 assert _get_db_version(c) == 24
612 conn.close()
613
614 def test_no_meta_table_returns_zero(self, tmp_path):
615 db_path = str(tmp_path / "test.db")
616 conn = sqlite3.connect(db_path)
617 c = conn.cursor()
618 c.execute("CREATE TABLE dummy (x TEXT)")
619 conn.commit()
620 assert _get_db_version(c) == 0
621 conn.close()
622
622 lines PYTHON