| 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 Mac |
| 9 |
""" |
| 10 |
|
| 11 |
import errno |
| 12 |
import glob |
| 13 |
import os |
| 14 |
import struct |
| 15 |
import subprocess |
| 16 |
from unittest import mock |
| 17 |
|
| 18 |
from tests import common |
| 19 |
from bleachbit import IS_MAC |
| 20 |
if IS_MAC: |
| 21 |
from bleachbit.Mac import ( |
| 22 |
delete_safari_cookies, |
| 23 |
get_macos_locale, |
| 24 |
is_full_disk_access_enabled, |
| 25 |
is_safari_binarycookies, |
| 26 |
list_safari_cookies, |
| 27 |
notify_macos, |
| 28 |
_read_safari_cookie_records, |
| 29 |
_serialize_safari_cookie_records, |
| 30 |
_write_safari_cookie_records, |
| 31 |
) |
| 32 |
|
| 33 |
|
| 34 |
class MacTestCase(common.BleachbitTestCase): |
| 35 |
"""Test case for bleachbit.Mac""" |
| 36 |
|
| 37 |
@common.skipUnlessMac |
| 38 |
def test_notify_macos_calls_osascript(self): |
| 39 |
"""notify_macos() invokes osascript with a display notification script.""" |
| 40 |
with mock.patch('subprocess.run') as mock_run: |
| 41 |
notify_macos('hello world') |
| 42 |
|
| 43 |
self.assertEqual(mock_run.call_count, 1) |
| 44 |
args = mock_run.call_args[0][0] |
| 45 |
self.assertEqual(args[0], 'osascript') |
| 46 |
self.assertEqual(args[1], '-e') |
| 47 |
self.assertIn('display notification', args[2]) |
| 48 |
self.assertIn('hello world', args[2]) |
| 49 |
|
| 50 |
@common.skipUnlessMac |
| 51 |
def test_notify_macos_escapes_quotes_and_backslashes(self): |
| 52 |
"""Quotes and backslashes in the message cannot break out of the |
| 53 |
AppleScript string literal or inject additional script.""" |
| 54 |
malicious = 'x" with title "Hacked" -- do shell script "echo pwned' |
| 55 |
with mock.patch('subprocess.run') as mock_run: |
| 56 |
notify_macos(malicious) |
| 57 |
|
| 58 |
script = mock_run.call_args[0][0][2] |
| 59 |
self.assertIn('\\"', script) |
| 60 |
self.assertEqual(script.count('display notification'), 1) |
| 61 |
|
| 62 |
@common.skipUnlessMac |
| 63 |
def test_notify_macos_survives_missing_osascript(self): |
| 64 |
"""A missing/failing osascript must not raise out of notify_macos().""" |
| 65 |
with mock.patch('subprocess.run', side_effect=FileNotFoundError('no osascript')): |
| 66 |
notify_macos('should not raise') |
| 67 |
|
| 68 |
@common.skipUnlessMac |
| 69 |
def test_notify_macos_raises_on_non_mac(self): |
| 70 |
"""notify_macos() raises RuntimeError when not running on macOS.""" |
| 71 |
with mock.patch('bleachbit.Mac.IS_MAC', False): |
| 72 |
with self.assertRaises(RuntimeError): |
| 73 |
notify_macos('test') |
| 74 |
|
| 75 |
def test_is_full_disk_access_enabled_non_mac(self): |
| 76 |
"""is_full_disk_access_enabled() returns True on non-macOS.""" |
| 77 |
if IS_MAC: |
| 78 |
self.skipTest('This test is only for non-macOS') |
| 79 |
from bleachbit.Mac import is_full_disk_access_enabled |
| 80 |
self.assertTrue(is_full_disk_access_enabled()) |
| 81 |
|
| 82 |
@common.skipUnlessMac |
| 83 |
def test_is_full_disk_access_enabled_no_probe_exists(self): |
| 84 |
"""When no probe path exists, the function returns True (assume enabled).""" |
| 85 |
fake_probes = ('~/nonexistent_fda_probe_1/', '~/nonexistent_fda_probe_2/') |
| 86 |
with mock.patch('bleachbit.Mac._FDA_PROBE_PATHS', fake_probes): |
| 87 |
self.assertTrue(is_full_disk_access_enabled()) |
| 88 |
|
| 89 |
@common.skipUnlessMac |
| 90 |
def test_is_full_disk_access_enabled_eperm_detected(self): |
| 91 |
"""EPERM on an existing probe path is detected as FDA not enabled.""" |
| 92 |
|
| 93 |
fake_probes = ('~/Library/Safari/',) |
| 94 |
real_exists = os.path.exists |
| 95 |
|
| 96 |
def fake_scandir(path): |
| 97 |
# Simulate TCC blocking the directory with EPERM. |
| 98 |
raise OSError(errno.EPERM, 'Operation not permitted', path) |
| 99 |
|
| 100 |
with mock.patch('bleachbit.Mac._FDA_PROBE_PATHS', fake_probes), \ |
| 101 |
mock.patch('os.scandir', side_effect=fake_scandir), \ |
| 102 |
mock.patch('os.path.exists', side_effect=real_exists): |
| 103 |
self.assertFalse(is_full_disk_access_enabled()) |
| 104 |
|
| 105 |
@common.skipUnlessMac |
| 106 |
def test_is_full_disk_access_enabled_eacces_not_fda(self): |
| 107 |
"""EACCES (Unix mode) is not mistaken for a TCC/FDA denial.""" |
| 108 |
fake_probes = ('~/Library/Safari/',) |
| 109 |
real_exists = os.path.exists |
| 110 |
|
| 111 |
def fake_scandir(path): |
| 112 |
raise OSError(errno.EACCES, 'Permission denied', path) |
| 113 |
|
| 114 |
with mock.patch('bleachbit.Mac._FDA_PROBE_PATHS', fake_probes), \ |
| 115 |
mock.patch('os.scandir', side_effect=fake_scandir), \ |
| 116 |
mock.patch('os.path.exists', side_effect=real_exists): |
| 117 |
self.assertTrue(is_full_disk_access_enabled()) |
| 118 |
|
| 119 |
@common.skipUnlessMac |
| 120 |
def test_is_full_disk_access_enabled_accessible(self): |
| 121 |
"""When probe paths are accessible, FDA is reported as enabled.""" |
| 122 |
# Use a path that exists and is accessible (not TCC-protected). |
| 123 |
fake_probes = (self.tempdir + '/',) |
| 124 |
with mock.patch('bleachbit.Mac._FDA_PROBE_PATHS', fake_probes): |
| 125 |
self.assertTrue(is_full_disk_access_enabled()) |
| 126 |
|
| 127 |
@common.skipUnlessMac |
| 128 |
def test_get_macos_locale(self): |
| 129 |
"""get_macos_locale() returns system locale preference or None.""" |
| 130 |
ret = get_macos_locale() |
| 131 |
if ret is not None: |
| 132 |
self.assertIsInstance(ret, str) |
| 133 |
self.assertNotIn('@', ret) |
| 134 |
|
| 135 |
@common.skipUnlessMac |
| 136 |
def test_get_macos_locale_mocked(self): |
| 137 |
"""get_macos_locale() parses AppleLocale output and strips variants.""" |
| 138 |
proc_mock = mock.Mock() |
| 139 |
proc_mock.returncode = 0 |
| 140 |
proc_mock.stdout = 'es_ES@currency=EUR\n' |
| 141 |
with mock.patch('subprocess.run', return_value=proc_mock): |
| 142 |
self.assertEqual(get_macos_locale(), 'es_ES') |
| 143 |
|
| 144 |
proc_mock.stdout = '' |
| 145 |
with mock.patch('subprocess.run', return_value=proc_mock): |
| 146 |
self.assertIsNone(get_macos_locale()) |
| 147 |
|
| 148 |
with mock.patch('subprocess.run', side_effect=subprocess.SubprocessError): |
| 149 |
self.assertIsNone(get_macos_locale()) |
| 150 |
|
| 151 |
def test_macos_version_name(self): |
| 152 |
"""macos_version_name() returns correct marketing name for macOS versions.""" |
| 153 |
# Imported inline so this test runs on non-Mac platforms |
| 154 |
from bleachbit.Mac import macos_version_name # pylint: disable=import-outside-toplevel |
| 155 |
cases = { |
| 156 |
'26.6.2': 'Tahoe', |
| 157 |
'15.1.0': 'Sequoia', |
| 158 |
'14.0': 'Sonoma', |
| 159 |
'13.5': 'Ventura', |
| 160 |
'12.3': 'Monterey', |
| 161 |
'11.0': 'Big Sur', |
| 162 |
# A version newer than this dictionary must return None, not a |
| 163 |
# wrong name. |
| 164 |
'27.0': None, |
| 165 |
'9.0': None, |
| 166 |
'': None, |
| 167 |
} |
| 168 |
for version, expected in cases.items(): |
| 169 |
self.assertEqual(macos_version_name(version), expected, |
| 170 |
f"Version {version} should map to {expected}") |
| 171 |
|
| 172 |
@common.skipUnlessMac |
| 173 |
def test_macos_version_name_no_arg(self): |
| 174 |
"""macos_version_name() with no argument names the running macOS.""" |
| 175 |
from bleachbit.Mac import macos_version_name, MACOSX_DICT_LEGACY, MACOSX_DICT_MODERN |
| 176 |
name = macos_version_name() |
| 177 |
self.assertIn(name, {**MACOSX_DICT_LEGACY, **MACOSX_DICT_MODERN}.values()) |
| 178 |
|
| 179 |
def test_macos_version_name_empty_mac_ver(self): |
| 180 |
"""An empty platform.mac_ver() string yields None, not an exception.""" |
| 181 |
# Imported inline so this test runs on non-Mac platforms |
| 182 |
from bleachbit.Mac import macos_version_name # pylint: disable=import-outside-toplevel |
| 183 |
with mock.patch('platform.mac_ver', return_value=('', ('', '', ''), '')): |
| 184 |
self.assertIsNone(macos_version_name()) |
| 185 |
|
| 186 |
@staticmethod |
| 187 |
def _make_cookie_record(domain, name='cookie_name', path='/', value='cookie_val'): |
| 188 |
"""Build a raw binary Safari cookie record.""" |
| 189 |
header_size = 32 |
| 190 |
d_bytes = domain.encode('utf-8') + b'\x00' |
| 191 |
n_bytes = name.encode('utf-8') + b'\x00' |
| 192 |
p_bytes = path.encode('utf-8') + b'\x00' |
| 193 |
v_bytes = value.encode('utf-8') + b'\x00' |
| 194 |
d_off = header_size |
| 195 |
n_off = d_off + len(d_bytes) |
| 196 |
p_off = n_off + len(n_bytes) |
| 197 |
v_off = p_off + len(p_bytes) |
| 198 |
total_size = v_off + len(v_bytes) |
| 199 |
return ( |
| 200 |
struct.pack('<IIIIIIII', total_size, 0, 0, 0, d_off, n_off, p_off, v_off) |
| 201 |
+ d_bytes + n_bytes + p_bytes + v_bytes |
| 202 |
) |
| 203 |
|
| 204 |
def _create_binarycookies_file(self, domain_records): |
| 205 |
"""Create a temporary binarycookies file""" |
| 206 |
pages = [{'records': domain_records}] |
| 207 |
data = _serialize_safari_cookie_records(pages) |
| 208 |
temp_path = self.mkstemp(suffix='.binarycookies') |
| 209 |
with open(temp_path, 'wb') as f: |
| 210 |
f.write(data) |
| 211 |
return temp_path |
| 212 |
|
| 213 |
@common.skipUnlessMac |
| 214 |
def test_is_safari_binarycookies(self): |
| 215 |
"""is_safari_binarycookies correctly identifies binarycookies files.""" |
| 216 |
rec = self._make_cookie_record('webkit.org') |
| 217 |
path = self._create_binarycookies_file([('webkit.org', rec)]) |
| 218 |
self.assertTrue(is_safari_binarycookies(path)) |
| 219 |
|
| 220 |
# Non-binarycookies file |
| 221 |
not_cookie = self.mkstemp() |
| 222 |
with open(not_cookie, 'wb') as f: |
| 223 |
f.write(b'SQLite format 3\x00') |
| 224 |
self.assertFalse(is_safari_binarycookies(not_cookie)) |
| 225 |
|
| 226 |
# Nonexistent file |
| 227 |
self.assertFalse(is_safari_binarycookies('/nonexistent/path/cookies.binarycookies')) |
| 228 |
|
| 229 |
@common.skipUnlessMac |
| 230 |
def test_read_safari_cookies_rejects_bad_page_marker(self): |
| 231 |
"""Regression test: _read_safari_cookie_records() must reject a |
| 232 |
page whose marker doesn't match what real Safari (and this |
| 233 |
module's own writer) always emits, rather than trusting |
| 234 |
cookie_count blindly. Confirmed against a real, unmodified |
| 235 |
Safari Cookies.binarycookies file that this exact marker value |
| 236 |
(b'\\x00\\x00\\x01\\x00') is what real Safari writes. |
| 237 |
|
| 238 |
File layout for a single-page, single-record file: 'cook'(4) + |
| 239 |
page_count(4) + page_size_table(4x1) = 12 bytes of file header, |
| 240 |
then the page itself starts at file offset 12 (the page marker |
| 241 |
is its first 4 bytes). |
| 242 |
""" |
| 243 |
rec = self._make_cookie_record('webkit.org') |
| 244 |
temp_path = self._create_binarycookies_file([('webkit.org', rec)]) |
| 245 |
|
| 246 |
with open(temp_path, 'r+b') as f: |
| 247 |
f.seek(12) |
| 248 |
f.write(b'\xff') |
| 249 |
|
| 250 |
with self.assertRaises(ValueError): |
| 251 |
list(_read_safari_cookie_records(temp_path)) |
| 252 |
|
| 253 |
@common.skipUnlessMac |
| 254 |
def test_read_safari_cookies_rejects_bad_end_of_table_marker(self): |
| 255 |
"""Regression test: _read_safari_cookie_records() must reject a |
| 256 |
page whose end-of-table marker (right after the offset table) |
| 257 |
doesn't match what real Safari (and this module's own writer) |
| 258 |
always emits. |
| 259 |
|
| 260 |
For a single-record page, the offset table is 4 bytes (one |
| 261 |
entry), so the end-of-table marker sits at page offset |
| 262 |
8 + 1*4 = 12, i.e. file offset 12 (page start) + 12 = 24. |
| 263 |
""" |
| 264 |
rec = self._make_cookie_record('webkit.org') |
| 265 |
temp_path = self._create_binarycookies_file([('webkit.org', rec)]) |
| 266 |
|
| 267 |
with open(temp_path, 'r+b') as f: |
| 268 |
f.seek(24) |
| 269 |
f.write(b'\xff') |
| 270 |
|
| 271 |
with self.assertRaises(ValueError): |
| 272 |
list(_read_safari_cookie_records(temp_path)) |
| 273 |
|
| 274 |
@common.skipUnlessMac |
| 275 |
def test_safari_binarycookies_roundtrip(self): |
| 276 |
"""Roundtrip serialize, write, read, and list Safari binary cookies.""" |
| 277 |
rec1 = self._make_cookie_record('webkit.org') |
| 278 |
rec2 = self._make_cookie_record('.sub.domain.org') |
| 279 |
path = self._create_binarycookies_file([ |
| 280 |
('webkit.org', rec1), |
| 281 |
('sub.domain.org', rec2), |
| 282 |
]) |
| 283 |
|
| 284 |
domains = list_safari_cookies(path) |
| 285 |
self.assertEqual(domains, ['sub.domain.org', 'webkit.org']) |
| 286 |
|
| 287 |
pages = _read_safari_cookie_records(path) |
| 288 |
self.assertEqual(len(pages), 1) |
| 289 |
self.assertEqual(len(pages[0]['records']), 2) |
| 290 |
self.assertEqual(pages[0]['records'][0][0], 'webkit.org') |
| 291 |
self.assertEqual(pages[0]['records'][1][0], 'sub.domain.org') |
| 292 |
|
| 293 |
# Test writing via _write_safari_cookie_records |
| 294 |
write_path = os.path.join(self.tempdir, 'rewritten.binarycookies') |
| 295 |
_write_safari_cookie_records(write_path, pages) |
| 296 |
self.assertEqual(list_safari_cookies(write_path), ['sub.domain.org', 'webkit.org']) |
| 297 |
|
| 298 |
@common.skipUnlessMac |
| 299 |
def test_delete_safari_cookies_preview(self): |
| 300 |
"""Preview deletion of Safari cookies computes deletion stats without modifying file.""" |
| 301 |
rec1 = self._make_cookie_record('bugs.webkit.org') |
| 302 |
rec2 = self._make_cookie_record('github.com') |
| 303 |
path = self._create_binarycookies_file([ |
| 304 |
('bugs.webkit.org', rec1), |
| 305 |
('github.com', rec2), |
| 306 |
]) |
| 307 |
|
| 308 |
res = delete_safari_cookies(path, {'github.com'}, really_delete=False) |
| 309 |
self.assertEqual(res['total_deleted'], 1) |
| 310 |
self.assertEqual(res['total_kept'], 1) |
| 311 |
self.assertFalse(res['skipped']) |
| 312 |
self.assertFalse(res['whole_file_deleted']) |
| 313 |
self.assertEqual(res['file_size_estimation_method'], 'ratio') |
| 314 |
# File should remain unmodified |
| 315 |
self.assertEqual(list_safari_cookies(path), ['bugs.webkit.org', 'github.com']) |
| 316 |
|
| 317 |
@common.skipUnlessMac |
| 318 |
def test_delete_safari_cookies_selective(self): |
| 319 |
"""Selective deletion removes unkept domains and rewrites the file.""" |
| 320 |
rec1 = self._make_cookie_record('git.webkit.org') |
| 321 |
rec2 = self._make_cookie_record('github.com') |
| 322 |
path = self._create_binarycookies_file([ |
| 323 |
('git.webkit.org', rec1), |
| 324 |
('github.com', rec2), |
| 325 |
]) |
| 326 |
|
| 327 |
res = delete_safari_cookies(path, {'github.com'}, really_delete=True) |
| 328 |
self.assertEqual(res['total_deleted'], 1) |
| 329 |
self.assertEqual(res['total_kept'], 1) |
| 330 |
self.assertFalse(res['skipped']) |
| 331 |
self.assertFalse(res['whole_file_deleted']) |
| 332 |
self.assertEqual(list_safari_cookies(path), ['github.com']) |
| 333 |
|
| 334 |
@common.skipUnlessMac |
| 335 |
def test_delete_safari_cookies_delete_all(self): |
| 336 |
"""When no cookies match keep list, the whole file is removed.""" |
| 337 |
rec1 = self._make_cookie_record('build.webkit.org') |
| 338 |
path = self._create_binarycookies_file([('build.webkit.org', rec1)]) |
| 339 |
|
| 340 |
res = delete_safari_cookies(path, {'other.org'}, really_delete=True) |
| 341 |
self.assertEqual(res['total_deleted'], 1) |
| 342 |
self.assertEqual(res['total_kept'], 0) |
| 343 |
self.assertTrue(res['whole_file_deleted']) |
| 344 |
self.assertFalse(os.path.exists(path)) |
| 345 |
|
| 346 |
@common.skipUnlessMac |
| 347 |
def test_delete_safari_cookies_empty_keep_list_raises(self): |
| 348 |
"""Empty keep list raises ValueError.""" |
| 349 |
rec1 = self._make_cookie_record('lists.webkit.org') |
| 350 |
path = self._create_binarycookies_file([('lists.webkit.org', rec1)]) |
| 351 |
|
| 352 |
with self.assertRaises(ValueError): |
| 353 |
delete_safari_cookies(path, set(), really_delete=False) |
| 354 |
|
| 355 |
@common.skipUnlessMac |
| 356 |
def test_cookie_module_delegates_safari(self): |
| 357 |
"""bleachbit.Cookie delegator functions invoke Mac Safari implementations.""" |
| 358 |
from bleachbit import Cookie |
| 359 |
rec1 = self._make_cookie_record('webkit.org') |
| 360 |
rec2 = self._make_cookie_record('bleachbit.org') |
| 361 |
path = self._create_binarycookies_file([ |
| 362 |
('webkit.org', rec1), |
| 363 |
('bleachbit.org', rec2), |
| 364 |
]) |
| 365 |
|
| 366 |
# list_cookies |
| 367 |
cookie_list = Cookie.list_cookies(path) |
| 368 |
self.assertEqual(cookie_list, [('bleachbit.org',), ('webkit.org',)]) |
| 369 |
|
| 370 |
# delete_cookies preview |
| 371 |
preview = Cookie.delete_cookies(path, {'bleachbit.org'}, really_delete=False) |
| 372 |
self.assertEqual(preview['total_deleted'], 1) |
| 373 |
self.assertEqual(preview['total_kept'], 1) |
| 374 |
|
| 375 |
# delete_cookies execute |
| 376 |
result = Cookie.delete_cookies(path, {'bleachbit.org'}, really_delete=True) |
| 377 |
self.assertEqual(result['total_deleted'], 1) |
| 378 |
self.assertEqual(result['total_kept'], 1) |
| 379 |
self.assertEqual(Cookie.list_cookies(path), [('bleachbit.org',)]) |
| 380 |
|
| 381 |
@common.skipUnlessMac |
| 382 |
def test_real_safari_cookies_read_sanity(self): |
| 383 |
"""Reading real Safari cookie files must not crash or yield garbage.""" |
| 384 |
from bleachbit import Cookie |
| 385 |
|
| 386 |
patterns = ( |
| 387 |
'~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies', |
| 388 |
'~/Library/HTTPStorages/*.binarycookies', |
| 389 |
) |
| 390 |
paths = [ |
| 391 |
path |
| 392 |
for pattern in patterns |
| 393 |
for path in glob.glob(os.path.expanduser(pattern)) |
| 394 |
] |
| 395 |
if not paths: |
| 396 |
self.skipTest('no real Safari cookie files present on this system') |
| 397 |
|
| 398 |
if not is_full_disk_access_enabled(): |
| 399 |
self.skipTest('Full Disk Access is not enabled') |
| 400 |
|
| 401 |
for path in paths: |
| 402 |
self.assertTrue(is_safari_binarycookies(path)) |
| 403 |
|
| 404 |
domains = list_safari_cookies(path) |
| 405 |
self.assertIsInstance(domains, list) |
| 406 |
self.assertEqual(Cookie.list_cookies(path), [(d,) for d in domains]) |
| 407 |
|
| 408 |
for domain in domains: |
| 409 |
self.assertIsInstance(domain, str) |
| 410 |
self.assertTrue(domain) |
| 411 |
self.assertNotIn('\x00', domain) |