Debian Codegraph @

tests/TestCookie.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (c) 2008-2026 Andrew Ziem.
3 #
4 # This work is licensed under the terms of the GNU GPL, version 3 or
5 # later. See the COPYING file in the top-level directory.
6
7 """
8 Test case for module Cookie
9 """
10
11 import hashlib
12 import json
13 import os
14 import sqlite3
15 import unittest
16 import shutil
17 from unittest import mock
18
19 import bleachbit
20 from bleachbit import Cookie
21 from bleachbit.Action import Cookie as CookieAction
22 from bleachbit.Cookie import COOKIE_KEEP_LIST_FILENAME, load_keep_list
23 from bleachbit.Options import options
24 from bleachbit.FileUtilities import execute_sqlite3
25 from tests import common
26
27
28 DEFAULT_COOKIE_FIXTURES = (
29 ('example.com', 'session_id'),
30 ('google.com', 'pref'),
31 ('github.com', 'auth'),
32 )
33
34 DOMAIN_MATCHING_CASES = (
35 ('example.com', 'example.com', True, 'Exact host match'),
36 ('example.com', '.example.com', True,
37 'Domain cookie canonicalizes to base host'),
38 ('example.com', 'shop.example.com', True,
39 'Subdomain should be preserved when base is keeplisted'),
40 ('example.com', '.shop.example.com', True,
41 'Firefox/Chromium store domain cookies with dots'),
42 ('example.com', 'thisisanexample.com', False,
43 'Substring matches must not count'),
44 ('example.com', 'example.com.attacker.net', False,
45 'Extra label to the right is a different domain'),
46 ('example.com', 'shop-example.com', False,
47 'Hyphenated host is unrelated'),
48 ('www.example.com', 'example.com', False,
49 'Host-only cookies should not match parent domain'),
50 ('.example.com', 'example.com', True,
51 'Leading dots in keep list should be ignored'),
52 ('.example.com', 'www.example.com', True,
53 'Leading dots in keep list should match subdomains'),
54 ('.example.com', 'fooexample.com', False,
55 'Canonical registrable domain mismatch'),
56 )
57
58
59 # Additional coverage:
60 # - Non-SQLite file with non-empty keep list should not be deleted (raises ValueError)
61 # - SQLite DB with unknown table and non-empty keep list should not be deleted (raises ValueError)
62 # - When no hosts match keep list, all rows are deleted and the database file is removed
63
64 class CookieTestCase(common.BleachbitTestCase):
65 """Test cases for Cookie module"""
66
67 def setUp(self):
68 """Set up test fixtures"""
69 super().setUp()
70 # tearDown reloads Options, so this doesn't leak between tests
71 options.set('shred', True)
72 # remove the shared cookie keep-list file after every test
73 keep_path = os.path.join(
74 bleachbit.options_dir, COOKIE_KEEP_LIST_FILENAME)
75 self.addCleanup(lambda: os.path.exists(
76 keep_path) and os.remove(keep_path))
77
78 def _get_file_hash(self, filepath):
79 """Calculate SHA-256 hash of a file"""
80 with open(filepath, 'rb') as f:
81 return hashlib.sha256(f.read()).digest()
82
83 def _sample_cookies(self, dotted=False):
84 """Return a reusable copy of the default cookie fixtures"""
85 cookies = DEFAULT_COOKIE_FIXTURES
86 if dotted:
87 return [
88 (host if host.startswith('.') else f'.{host}', name)
89 for host, name in cookies
90 ]
91 return [(host, name) for host, name in cookies]
92
93 def _create_chrome_cookies_db(self, cookies=None):
94 """Create a Chrome cookies database for testing
95
96 Args:
97 cookies: Iterable of (host_key, name) tuples. If None, uses
98 default test cookies.
99
100 Returns:
101 str: Path to the created cookies database
102 """
103 if cookies is None:
104 cookies = self._sample_cookies()
105
106 path = os.path.join(self.tempdir, 'chrome_cookies.db')
107 if os.path.exists(path):
108 os.unlink(path)
109 sql = '''
110 CREATE TABLE cookies (
111 host_key TEXT NOT NULL,
112 name TEXT NOT NULL
113 )
114 '''
115 execute_sqlite3(path, sql)
116
117 conn = sqlite3.connect(path)
118 try:
119 cursor = conn.cursor()
120 for host_key, name in cookies:
121 cursor.execute(
122 'INSERT INTO cookies (host_key, name) VALUES (?, ?)',
123 (host_key, name),
124 )
125 conn.commit()
126 finally:
127 conn.close()
128
129 return path
130
131 def _find_live_firefox_cookies_file(self):
132 """Return path to a real Firefox cookies.sqlite if one exists"""
133 search_roots = [
134 os.path.expanduser('~/snap/firefox/common/.mozilla/firefox'),
135 os.path.expanduser('~/.mozilla/firefox'),
136 ]
137 appdata = os.environ.get('APPDATA')
138 if appdata:
139 search_roots.append(os.path.join(
140 appdata, 'Mozilla', 'Firefox', 'Profiles'))
141
142 for root in search_roots:
143 if not root or not os.path.isdir(root):
144 continue
145 for dirpath, _dirnames, filenames in os.walk(root):
146 if 'cookies.sqlite' in filenames:
147 return os.path.join(dirpath, 'cookies.sqlite')
148 return None
149
150 def _create_firefox_cookies_db(self, cookies=None):
151 """Create a Firefox cookies database for testing
152
153 Args:
154 cookies: Iterable of cookie descriptors. Accepts:
155 * plain host strings
156 * (host, name) tuples
157 If None, uses default test cookies.
158
159 Returns:
160 str: Path to the created cookies database
161 """
162 if cookies is None:
163 cookies = self._sample_cookies(dotted=True)
164
165 path = os.path.join(self.tempdir, 'firefox_cookies.db')
166 if os.path.exists(path):
167 os.unlink(path)
168 sql = '''
169 CREATE TABLE moz_cookies (
170 id INTEGER PRIMARY KEY,
171 host TEXT NOT NULL,
172 name TEXT NOT NULL,
173 CONSTRAINT moz_uniqueid UNIQUE (host, name)
174 )
175 '''
176 execute_sqlite3(path, sql)
177
178 conn = sqlite3.connect(path)
179 try:
180 cursor = conn.cursor()
181 for cookie in cookies:
182 host = name = None
183 if isinstance(cookie, str):
184 host, name = cookie, ''
185 elif isinstance(cookie, (list, tuple)):
186 if len(cookie) >= 2:
187 host, name = cookie[:2]
188 elif len(cookie) == 1:
189 host, name = cookie[0], ''
190 if host is None:
191 raise ValueError(
192 'Unsupported cookie format for Firefox test fixture')
193 cursor.execute(
194 'INSERT INTO moz_cookies (host, name) VALUES (?, ?)', (host, name))
195 conn.commit()
196 finally:
197 conn.close()
198
199 return path
200
201 def test_delete_cookie_value_error(self):
202 """Empty keep list should raise ValueError (API requires non-empty set)"""
203 path = self._create_chrome_cookies_db()
204
205 # Get file hash before operation
206 original_hash = self._get_file_hash(path)
207
208 # Test scenarios that should raise ValueError
209 scenarios = [
210 # Scenario 1: Empty allowlist
211 (set(), "Empty keep list should raise ValueError"),
212 # Scenario 2: None allowlist
213 (None, "None keep list should raise ValueError"),
214 ]
215
216 for keep_list, description in scenarios:
217 with self.subTest(description=description):
218 with self.assertRaises(ValueError):
219 Cookie.delete_cookies(path, keep_list, really_delete=True)
220 self.assertExists(path)
221 new_hash = self._get_file_hash(path)
222 self.assertEqual(original_hash, new_hash,
223 'Database file was modified')
224
225 def test_delete_cookie_bad_file(self):
226 """Empty keep list should raise ValueError (API requires non-empty set)"""
227 path_missing = os.path.join(self.tempdir, 'nonexistent.db')
228 path_non_sqlite = self.write_file(
229 'experiment_626.dna', text='not sqlite3')
230 path_wrong_sqlite = os.path.join(self.tempdir, 'wrong_sqlite.db')
231
232 execute_sqlite3(
233 path_wrong_sqlite, "CREATE TABLE not_browser_related (id INTEGER PRIMARY KEY)")
234
235 scenarios = [
236 (path_missing, "Non-existent file", ValueError),
237 (path_non_sqlite, "Non-SQLite file", sqlite3.DatabaseError),
238 (path_wrong_sqlite, "SQLite file with wrong table", ValueError),
239 ]
240
241 for test_path, description, expected_exception in scenarios:
242 with self.subTest(description=description):
243 original_hash = None
244 if not test_path == path_missing:
245 original_hash = self._get_file_hash(test_path)
246 with self.assertRaises(expected_exception):
247 Cookie.delete_cookies(
248 test_path, {'example.com'}, really_delete=True)
249
250 if test_path == path_missing:
251 self.assertNotExists(test_path)
252 else:
253 self.assertExists(test_path)
254 new_hash = self._get_file_hash(test_path)
255 self.assertEqual(original_hash, new_hash,
256 'Database file was modified')
257
258 def test_delete_cookies_chrome_with_keeplist(self):
259 """Test selectively deleting Chrome cookies with keep list"""
260 path = self._create_chrome_cookies_db()
261
262 # Test deletion with keep list (keep google.com)
263 keep_list = ['google.com']
264 result = Cookie.delete_cookies(
265 path, set(keep_list), really_delete=True)
266
267 # example.com and github.com deleted
268 self.assertEqual(result['total_deleted'], 2)
269 self.assertEqual(result['total_kept'], 1) # google.com kept
270 self.assertFalse(result['skipped'])
271 self.assertFalse(result['whole_file_deleted'])
272 self.assertGreaterEqual(result['file_size_reduction'], 0)
273
274 def test_non_sqlite_file_with_keeplist_raises(self):
275 """Non-SQLite file should raise ValueError and not be deleted"""
276 # First create a valid cookies db to get the path format right
277 path = self._create_chrome_cookies_db()
278 # Now remove it and create a non-sqlite file
279 os.unlink(path)
280 path = os.path.join(self.tempdir, 'not_sqlite.txt')
281 with open(path, 'w', encoding='utf-8') as f:
282 f.write('not a database')
283
284 with self.assertRaises(sqlite3.DatabaseError):
285 Cookie.delete_cookies(path, {'example.com'}, really_delete=True)
286
287 self.assertTrue(os.path.exists(path))
288
289 def test_sqlite_unknown_table_with_keeplist_raises(self):
290 """SQLite DB without known cookies table should raise ValueError"""
291 path = os.path.join(self.tempdir, 'unknown_table.db')
292 conn = sqlite3.connect(path)
293 cur = conn.cursor()
294 cur.execute(
295 'CREATE TABLE something_else (id INTEGER PRIMARY KEY, host TEXT)')
296 conn.commit()
297 conn.close()
298
299 with self.assertRaises(ValueError):
300 Cookie.delete_cookies(path, {'example.com'}, really_delete=True)
301
302 self.assertTrue(os.path.exists(path))
303
304 def test_delete_cookies_when_no_hosts_match_kept(self):
305 """If no hosts match keep list, all rows are deleted and file is removed"""
306 path = self._create_chrome_cookies_db()
307
308 result = Cookie.delete_cookies(
309 path, {'no-such-host.example'}, really_delete=True)
310
311 self.assertEqual(result['total_kept'], 0)
312 self.assertEqual(result['total_deleted'], 3)
313 self.assertFalse(result['skipped'])
314 self.assertTrue(result['whole_file_deleted'])
315 self.assertGreaterEqual(result['file_size_reduction'], 0)
316
317 # Verify database file was removed
318 self.assertFalse(os.path.exists(path))
319
320 def test_delete_cookies_firefox_with_keeplist(self):
321 """Test selectively deleting Firefox cookies with keeplist"""
322 path = self._create_firefox_cookies_db()
323
324 # Test deletion with keep list
325 keep_list = ['google.com']
326 result = Cookie.delete_cookies(
327 path, set(keep_list), really_delete=True)
328
329 # example.com and github.com deleted
330 self.assertEqual(result['total_deleted'], 2)
331 self.assertEqual(result['total_kept'], 1) # google.com kept
332 self.assertFalse(result['skipped'])
333 self.assertFalse(result['whole_file_deleted'])
334 self.assertGreaterEqual(result['file_size_reduction'], 0)
335
336 # Verify the database still exists and has the right cookies
337 self.assertTrue(os.path.exists(path))
338
339 conn = sqlite3.connect(path)
340 cursor = conn.cursor()
341 remaining_cookies = cursor.execute(
342 'SELECT host FROM moz_cookies').fetchall()
343 conn.close()
344
345 self.assertEqual(len(remaining_cookies), 1)
346 # Firefox stores domain cookies with a leading dot (e.g., '.google.com').
347 self.assertEqual(remaining_cookies[0][0].lstrip('.'), 'google.com')
348
349 def test_delete_firefox_live(self):
350 """Test deleting Firefox cookies from a real database"""
351 live_path = self._find_live_firefox_cookies_file()
352 if not live_path:
353 self.skipTest(
354 'Skipping live Firefox test because cookies.sqlite was not found')
355
356 def run_test_scenario(random_count):
357 """Helper to test a cookie deletion scenario"""
358 self.assertGreaterEqual(random_count, 0)
359 temp_db = os.path.join(
360 self.tempdir, f'firefox_live_copy{random_count}.sqlite')
361 shutil.copy2(live_path, temp_db)
362
363 # Copy WAL/SHM files if present to keep the database consistent
364 for suffix in ('-wal', '-shm'):
365 aux_src = f"{live_path}{suffix}"
366 if os.path.exists(aux_src):
367 shutil.copy2(aux_src, f"{temp_db}{suffix}")
368
369 # Add a non-existent domain to keep list to test filtering
370 doesnotexist = 'doesnotexist1234567890.com'
371 if random_count:
372 conn = sqlite3.connect(temp_db)
373 cursor = conn.cursor()
374 random_hosts = cursor.execute(
375 f'SELECT DISTINCT host FROM moz_cookies ORDER BY RANDOM() LIMIT {random_count}').fetchall()
376 conn.close()
377 if not random_hosts:
378 self.skipTest('No hosts found in live Firefox database')
379 keep_list = {host[0].lstrip('.') for host in random_hosts}
380 else:
381 keep_list = {doesnotexist}
382
383 preview_result = Cookie.delete_cookies(
384 temp_db, keep_list, really_delete=False)
385 self.assertIn('total_deleted', preview_result)
386 self.assertFalse(preview_result['skipped'])
387 self.assertTrue(os.path.exists(temp_db))
388
389 delete_result = Cookie.delete_cookies(
390 temp_db, keep_list, really_delete=True)
391 self.assertIn('total_deleted', delete_result)
392 self.assertFalse(delete_result['skipped'])
393
394 # Check file size reduction accuracy
395 size_diff = abs(
396 preview_result['file_size_reduction'] - delete_result['file_size_reduction'])
397 # The estimate is accurate with shredding enabled, which is
398 # how this test is run.
399 self.assertLessEqual(
400 size_diff, 1024, f"Size difference {size_diff:,} exceeds tolerance")
401
402 if delete_result.get('whole_file_deleted'):
403 self.assertFalse(os.path.exists(temp_db))
404 else:
405 self.assertTrue(os.path.exists(temp_db))
406 os.unlink(temp_db)
407
408 # Test scenario 1: Delete all cookies (keep non-existent domain)
409 run_test_scenario(0)
410 # Test scenario 2: Delete several random cookies
411 run_test_scenario(10)
412 run_test_scenario(50)
413
414 def test_preview_cookies_deletion_chrome(self):
415 """Test previewing Chrome cookie deletion"""
416 path = self._create_chrome_cookies_db()
417
418 # Test preview with keep list
419 keep_list = ['google.com']
420 result = Cookie.delete_cookies(
421 path, set(keep_list), really_delete=False)
422
423 self.assertEqual(result['total_deleted'], 2)
424 self.assertEqual(result['total_kept'], 1)
425 self.assertFalse(result['skipped'])
426 self.assertFalse(result['whole_file_deleted'])
427 self.assertGreaterEqual(result['file_size_reduction'], 0)
428
429 # Verify original database is unchanged
430 conn = sqlite3.connect(path)
431 cursor = conn.cursor()
432 all_cookies = cursor.execute('SELECT host_key FROM cookies').fetchall()
433 conn.close()
434
435 self.assertEqual(len(all_cookies), 3) # All cookies still there
436
437 def test_keeplist_domain_matching_matrix(self):
438 """Table-driven coverage for keep list domain semantics"""
439 for selection, host_value, expect_keep, reason in DOMAIN_MATCHING_CASES:
440 with self.subTest(selection=selection, host=host_value, reason=reason):
441 cookies = [(host_value, 'token')]
442 path = self._create_chrome_cookies_db(cookies)
443 result = Cookie.delete_cookies(
444 path, {selection}, really_delete=False)
445
446 if expect_keep:
447 self.assertEqual(result['total_kept'], 1, reason)
448 self.assertEqual(result['total_deleted'], 0)
449 else:
450 self.assertEqual(result['total_kept'], 0, reason)
451 self.assertEqual(result['total_deleted'], 1)
452
453 def test_preview_cookies_deletion_no_keeplist(self):
454 """Test previewing cookie deletion with no keep list"""
455 # Create test cookies
456 cookies_data = [
457 ('example.com', 'session_id'),
458 ]
459
460 path = self._create_chrome_cookies_db(cookies_data)
461
462 # Test preview with no keep list (should preview whole file deletion)
463 with self.assertRaises(ValueError):
464 Cookie.delete_cookies(path, set(), really_delete=False)
465
466 def test_nonexistent_file(self):
467 """Test handling of nonexistent cookie files"""
468 path = os.path.join(self.tempdir, 'nonexistent.db')
469
470 # Both deletion and preview should raise ValueError for nonexistent files
471 with self.assertRaises(ValueError):
472 Cookie.delete_cookies(path, {'example.com'}, really_delete=True)
473 with self.assertRaises(ValueError):
474 Cookie.delete_cookies(path, {'example.com'}, really_delete=False)
475
476 def test_browser_detection(self):
477 """Test automatic browser detection"""
478 # Test Chrome detection
479 chrome_path = self._create_chrome_cookies_db()
480 self.assertEqual(Cookie.detect_browser(
481 chrome_path), ('cookies', 'host_key'))
482
483 # Test Firefox detection
484 firefox_path = self._create_firefox_cookies_db()
485 self.assertEqual(Cookie.detect_browser(
486 firefox_path), ('moz_cookies', 'host'))
487
488 def test_empty_database(self):
489 """Test handling of empty cookie databases"""
490 # Create empty Chrome database
491 path = self._create_chrome_cookies_db([])
492
493 # Test deletion with keep list
494 result = Cookie.delete_cookies(
495 path, {'example.com'}, really_delete=True)
496
497 self.assertEqual(result['total_deleted'], 0)
498 self.assertEqual(result['total_kept'], 0)
499 self.assertFalse(result['skipped'])
500 self.assertFalse(result['whole_file_deleted'])
501 self.assertGreaterEqual(result['file_size_reduction'], 0)
502
503 def _make_cookie_action(self):
504 """Create a Cookie action instance with a mock XML element."""
505 elem = mock.MagicMock()
506 elem.getAttribute.return_value = ''
507 elem.getAttribute.side_effect = lambda name: {
508 'command': 'cookie',
509 'search': 'file',
510 'path': os.path.join(self.tempdir, 'nonexistent'),
511 }.get(name, '')
512 return CookieAction(elem)
513
514 def test_load_keep_list_file_not_found(self):
515 """FileNotFoundError should return empty set (no keep list configured)"""
516 # Ensure the file doesn't exist
517 keep_path = os.path.join(
518 bleachbit.options_dir, COOKIE_KEEP_LIST_FILENAME)
519 if os.path.exists(keep_path):
520 os.remove(keep_path)
521 result = load_keep_list()
522 self.assertEqual(result, set())
523
524 def test_load_keep_list_valid_json(self):
525 """Valid JSON keep list should return the expected domains"""
526 keep_data = ["example.com", "example.org"]
527 keep_path = os.path.join(
528 bleachbit.options_dir, COOKIE_KEEP_LIST_FILENAME)
529 os.makedirs(bleachbit.options_dir, exist_ok=True)
530 with open(keep_path, 'w', encoding='utf-8') as f:
531 json.dump(keep_data, f)
532 result = load_keep_list()
533 self.assertEqual(result, {'example.com', 'example.org'})
534
535 def test_load_keep_list_json_decode_error(self):
536 """Corrupted JSON should raise JSONDecodeError, not return empty set"""
537 action = self._make_cookie_action()
538 keep_path = os.path.join(
539 bleachbit.options_dir, COOKIE_KEEP_LIST_FILENAME)
540 os.makedirs(bleachbit.options_dir, exist_ok=True)
541 self.write_file(keep_path, '{invalid json', mode='w')
542 with self.assertRaises(json.JSONDecodeError):
543 load_keep_list()
544 with self.assertRaises(json.JSONDecodeError):
545 list(action.get_commands())
546
547 def test_load_keep_list_unicode_decode_error(self):
548 """UnicodeDecodeError should propagate, not return empty set"""
549 action = self._make_cookie_action()
550 keep_path = os.path.join(
551 bleachbit.options_dir, COOKIE_KEEP_LIST_FILENAME)
552 os.makedirs(bleachbit.options_dir, exist_ok=True)
553 # Write invalid UTF-8 bytes
554 with open(keep_path, 'wb') as f:
555 f.write(b'\x80\x81\x82')
556 with self.assertRaises(UnicodeDecodeError):
557 load_keep_list()
558 with self.assertRaises(UnicodeDecodeError):
559 list(action.get_commands())
560
561 def test_load_keep_list_permission_error(self):
562 """PermissionError (a subtype of OSError) should propagate"""
563 action = self._make_cookie_action()
564 keep_path = os.path.join(
565 bleachbit.options_dir, COOKIE_KEEP_LIST_FILENAME)
566 os.makedirs(bleachbit.options_dir, exist_ok=True)
567 self.write_file(keep_path, json.dumps(["example.com"]), mode='w')
568 real_open = open
569
570 def _mock_open(*args, **kwargs):
571 if len(args) >= 1 and args[0] == keep_path:
572 raise PermissionError('mock permission denied')
573 return real_open(*args, **kwargs)
574 with mock.patch('builtins.open', _mock_open):
575 with self.assertRaises(PermissionError):
576 load_keep_list()
577 with self.assertRaises(PermissionError):
578 list(action.get_commands())
579
580 @common.skipIfWindows
581 def test_load_keep_list_chmod(self):
582 """Test that chmod affects file access"""
583 action = self._make_cookie_action()
584 keep_path = os.path.join(
585 bleachbit.options_dir, COOKIE_KEEP_LIST_FILENAME)
586 os.makedirs(bleachbit.options_dir, exist_ok=True)
587 self.write_file(keep_path, json.dumps(["example.com"]), mode='w')
588 # Remove read permission
589 os.chmod(keep_path, 0o200) # write-only
590 with self.assertRaises(PermissionError):
591 load_keep_list()
592 with self.assertRaises(PermissionError):
593 list(action.get_commands())
594 os.chmod(keep_path, 0o600) # restore read permission
595
596
597 if __name__ == '__main__':
598 unittest.main()