返回 last30days-skill
test_pr03_cookies_cdp_consent_security.py
根目录 / tests / test_pr03_cookies_cdp_consent_security.py
1 """Security regression tests for PR 3: browser cookies, CDP, and consent-gate hardening.
2
3 Covers:
4 - HIGH-077: In-process macOS Chromium AES-128-CBC decryption (CommonCrypto + pure-Python
5 fallback), zero openssl subprocess argv exposure, and pinned /usr/bin/security.
6 - HIGH-079: Firefox (and Chromium) temp SQLite fd closure before unlink + WAL/SHM/journal
7 cleanup (Windows %TEMP% leak regression) + Firefox cookie scoping hardening.
8 - HIGH-081: Chromium exact host matching, PRAGMA schema inspection, expires_utc filtering,
9 and single-scope grouping by (host_key, path, top_frame_site_key) without cross-scope mixing.
10 - HIGH-082: Strict CDP URL validation (loopback-only http/ws, no userinfo/fragments/control
11 chars, valid port 1..65535), no-proxy/no-redirect HTTP opener, cross-host/port
12 webSocketDebuggerUrl rejection, WebSocket request-line injection rejection, and safe socket
13 cleanup without raising.
14 - HIGH-083: Per-user owner-only (0o700) Chrome login profile directory in box_chrome_login.py,
15 lstat/symlink/UID/mode enforcement, non-zero abort on error, and `mkdir -m 700 -p`.
16 - HIGH-084: Symmetric env/config refusal resolution in agentcookie.is_disabled() and
17 respecting explicit FROM_BROWSER pins unless AGENTCOOKIE=on.
18 """
19
20 from __future__ import annotations
21
22 import ctypes
23 import http.server
24 import json
25 import os
26 import socket
27 import sqlite3
28 import stat
29 import subprocess
30 import sys
31 import tempfile
32 import threading
33 import time
34 import urllib.request
35 from pathlib import Path
36 from unittest import mock
37
38 import pytest
39
40 import box_chrome_login as bcl
41 from lib import agentcookie, chrome_cdp, chrome_cookies, cookie_extract
42
43 # Independent v10 vectors (PBKDF2-HMAC-SHA1, saltysalt, 1003 iterations, 16-byte key).
44 _V10_AES_KEY = bytes.fromhex("bae7b43668299f6b6839c58cff9e97db")
45 _V10_AUTH_TOKEN = bytes.fromhex(
46 "76313040a19511ccca2ce72c5b842326adf2e97a36831c0c5943045f7d66f96cbf011e"
47 )
48 _V10_CT0 = bytes.fromhex("763130189b696f39999dba1b0c8f9c005b8a24")
49
50 # NIST FIPS-197 Appendix C.1 (AES-128) test vector.
51 _FIPS197_KEY = bytes.fromhex("000102030405060708090a0b0c0d0e0f")
52 _FIPS197_PLAINTEXT = bytes.fromhex("00112233445566778899aabbccddeeff")
53 _FIPS197_CIPHERTEXT = bytes.fromhex("69c4e0d86a7b0430d8cdb78070b4c55a")
54
55
56 # ===========================================================================
57 # HIGH-077: In-process AES-128-CBC decryption & pinned /usr/bin/security
58 # ===========================================================================
59
60
61 class TestHigh077ChromeCryptoAndSecurityPin:
62 def test_keychain_lookup_pins_usr_bin_security(self):
63 proc = subprocess.CompletedProcess(args=[], returncode=0, stdout="dummy-pass\n", stderr="")
64 with mock.patch("lib.chrome_cookies.subprocess.run", return_value=proc) as run:
65 got = chrome_cookies._get_chromium_encryption_key("Chrome Safe Storage")
66 assert got == b"dummy-pass"
67 argv = run.call_args.args[0]
68 assert argv[0] == "/usr/bin/security"
69 assert argv[1:] == ["find-generic-password", "-w", "-s", "Chrome Safe Storage"]
70
71 def test_decrypt_v10_spawns_zero_subprocesses_and_never_uses_openssl(self):
72 with (
73 mock.patch(
74 "lib.chrome_cookies.subprocess.run",
75 side_effect=AssertionError("must never spawn openssl or any subprocess"),
76 ),
77 mock.patch(
78 "subprocess.Popen",
79 side_effect=AssertionError("must never spawn subprocesses"),
80 ),
81 ):
82 assert chrome_cookies._decrypt_v10_value(_V10_AUTH_TOKEN, _V10_AES_KEY, 20) == (
83 "my_auth_token_123"
84 )
85 assert chrome_cookies._decrypt_v10_value(_V10_CT0, _V10_AES_KEY, 20) == (
86 "my_ct0_csrf_456"
87 )
88
89 def test_pure_aes128_block_matches_fips197_appendix_c1(self):
90 round_keys = chrome_cookies._aes128_expand_key(_FIPS197_KEY)
91 decrypted = chrome_cookies._aes128_decrypt_block(_FIPS197_CIPHERTEXT, round_keys)
92 assert decrypted == _FIPS197_PLAINTEXT
93
94 def test_decrypt_v10_rejects_bad_prefix_length_and_non_bytes(self):
95 assert chrome_cookies._decrypt_v10_value(b"v11" + b"\x00" * 16, _V10_AES_KEY, 20) is None
96 assert chrome_cookies._decrypt_v10_value(b"v10short", _V10_AES_KEY, 20) is None
97 assert chrome_cookies._decrypt_v10_value(b"v10" + b"\x00" * 16, b"short-key", 20) is None
98 assert chrome_cookies._decrypt_v10_value(42, _V10_AES_KEY, 20) is None # type: ignore[arg-type]
99
100 def test_commoncrypto_path_uses_libcommoncrypto_cccrypt_on_darwin(self, monkeypatch):
101 seen_calls = []
102
103 def fake_cccrypt(
104 op, alg, options, key, key_len, iv, data_in, data_in_len, data_out, data_out_avail, out_moved
105 ):
106 seen_calls.append((op, alg, options, key, key_len, iv, data_in, data_in_len, data_out_avail))
107 plaintext = b"cc-decrypted-cookie"
108 ctypes.memmove(data_out, plaintext, len(plaintext))
109 out_moved._obj.value = len(plaintext)
110 return 0 # kCCSuccess
111
112 fake_lib = mock.MagicMock()
113 fake_lib.CCCrypt = fake_cccrypt
114
115 monkeypatch.setattr(chrome_cookies, "_COMMONCRYPTO_LOADED", False)
116 monkeypatch.setattr(chrome_cookies, "_COMMONCRYPTO_FUNC", None)
117 monkeypatch.setattr(chrome_cookies.sys, "platform", "darwin")
118 with mock.patch("lib.chrome_cookies.ctypes.CDLL", return_value=fake_lib) as cdll:
119 got = chrome_cookies._decrypt_v10_value(_V10_AUTH_TOKEN, _V10_AES_KEY, db_version=20)
120
121 cdll.assert_called_once_with("/usr/lib/system/libcommonCrypto.dylib")
122 assert got == "cc-decrypted-cookie"
123 assert len(seen_calls) == 1
124 op, alg, options, key, key_len, iv, data_in, data_in_len, data_out_avail = seen_calls[0]
125 assert (op, alg, options) == (1, 0, 1) # kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding
126 assert key == _V10_AES_KEY and key_len == 16
127 assert iv == b" " * 16
128 assert data_in == _V10_AUTH_TOKEN[3:] and data_in_len == len(_V10_AUTH_TOKEN[3:])
129 assert data_out_avail >= data_in_len + 16
130
131 def test_commoncrypto_decode_error_returns_none_without_fallback(self, monkeypatch):
132 def failing_cccrypt(*_args):
133 return -4304 # kCCDecodeError
134
135 monkeypatch.setattr(chrome_cookies, "_COMMONCRYPTO_LOADED", True)
136 monkeypatch.setattr(chrome_cookies, "_COMMONCRYPTO_FUNC", failing_cccrypt)
137 with mock.patch(
138 "lib.chrome_cookies._decrypt_aes128_cbc_pure",
139 side_effect=AssertionError("must not fall back when CommonCrypto reports decode error"),
140 ):
141 assert chrome_cookies._decrypt_v10_value(_V10_AUTH_TOKEN, _V10_AES_KEY, 20) is None
142
143 def test_chrome130_empty_cookie_does_not_leak_32_byte_digest(self, tmp_path):
144 fake_digest_only = b"\x41" * 32
145 with mock.patch("lib.chrome_cookies._decrypt_aes128_cbc", return_value=fake_digest_only):
146 assert chrome_cookies._decrypt_v10_value(b"v10" + b"\x00" * 48, _V10_AES_KEY, 24) == ""
147
148 db = tmp_path / "Cookies"
149 _make_chromium_db(
150 db,
151 [(".x.com", "auth_token", "", b"v10" + b"\x00" * 48, "/", _chrome_utc(3600), 1, 1, "")],
152 db_version=24,
153 )
154 with (
155 mock.patch("lib.chrome_cookies._get_chromium_encryption_key", return_value=b"pass"),
156 mock.patch("lib.chrome_cookies._decrypt_aes128_cbc", return_value=fake_digest_only),
157 ):
158 assert (
159 chrome_cookies._extract_chromium_cookies_macos(
160 db, "Chrome Safe Storage", ".x.com", ["auth_token"]
161 )
162 is None
163 )
164
165
166 # ===========================================================================
167 # HIGH-079: Firefox temp fd close before unlink, sidecars, and scoping
168 # ===========================================================================
169
170
171 def _make_firefox_db(
172 path: Path,
173 rows: list[tuple[str, str, str, str, int, int, int, str]],
174 *,
175 wal_mode: bool = False,
176 user_version: int = 0,
177 ) -> None:
178 conn = sqlite3.connect(str(path))
179 try:
180 if wal_mode:
181 conn.execute("PRAGMA journal_mode=WAL")
182 if user_version:
183 conn.execute(f"PRAGMA user_version = {int(user_version)}")
184 conn.execute(
185 "CREATE TABLE moz_cookies ("
186 " id INTEGER PRIMARY KEY,"
187 " host TEXT NOT NULL,"
188 " name TEXT NOT NULL,"
189 " value TEXT NOT NULL,"
190 " path TEXT NOT NULL DEFAULT '/',"
191 " expiry INTEGER NOT NULL DEFAULT 0,"
192 " isSecure INTEGER NOT NULL DEFAULT 1,"
193 " isHttpOnly INTEGER NOT NULL DEFAULT 1,"
194 " originAttributes TEXT NOT NULL DEFAULT ''"
195 ")"
196 )
197 conn.executemany(
198 "INSERT INTO moz_cookies "
199 "(host, name, value, path, expiry, isSecure, isHttpOnly, originAttributes) "
200 "VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
201 rows,
202 )
203 conn.commit()
204 finally:
205 conn.close()
206
207
208 class TestHigh079FirefoxTempCleanupAndScoping:
209 def test_windows_style_unlink_sees_zero_open_fds_and_cleans_sidecars(self, tmp_path, monkeypatch):
210 db = tmp_path / "cookies.sqlite"
211 _make_firefox_db(
212 db,
213 [(".x.com", "auth_token", "dummy-auth", "/", 0, 1, 1, "")],
214 wal_mode=True,
215 )
216 scratch = tmp_path / "temp_root"
217 scratch.mkdir()
218 monkeypatch.setattr(tempfile, "tempdir", str(scratch))
219
220 open_fds: dict[str, set[int]] = {}
221 real_open = os.open
222 real_close = os.close
223 real_unlink = Path.unlink
224 real_copy = cookie_extract.copy_snapshot
225
226 def tracked_open(path, flags, mode=0o777, *args, **kwargs):
227 fd = real_open(path, flags, mode, *args, **kwargs)
228 p = str(path)
229 if p.startswith(str(scratch)):
230 open_fds.setdefault(p, set()).add(fd)
231 return fd
232
233 def tracked_close(fd):
234 for fds in open_fds.values():
235 fds.discard(fd)
236 return real_close(fd)
237
238 def windows_strict_unlink(self, *args, **kwargs):
239 p = str(self)
240 if open_fds.get(p):
241 raise PermissionError(13, "WinError 32: file in use by open fd", p)
242 return real_unlink(self, *args, **kwargs)
243
244 def copy_with_sidecars(src, dst, **kwargs):
245 real_copy(src, dst, **kwargs)
246 # Simulate WAL/SHM/journal sidecar creation beside temp copy.
247 for suffix in ("-wal", "-shm", "-journal"):
248 Path(str(dst) + suffix).write_bytes(b"sidecar")
249
250 monkeypatch.setattr(os, "open", tracked_open)
251 monkeypatch.setattr(os, "close", tracked_close)
252 monkeypatch.setattr(Path, "unlink", windows_strict_unlink)
253 monkeypatch.setattr(cookie_extract, "copy_snapshot", copy_with_sidecars)
254
255 got = cookie_extract._query_cookies_db(db, ".x.com", ["auth_token"])
256 assert got == {"auth_token": "dummy-auth"}
257 assert list(scratch.iterdir()) == []
258 assert all(not fds for fds in open_fds.values())
259
260 def test_firefox_temp_dir_cleaned_on_query_error(self, tmp_path, monkeypatch):
261 db = tmp_path / "broken.sqlite"
262 conn = sqlite3.connect(str(db))
263 conn.execute("CREATE TABLE other (x TEXT)")
264 conn.commit()
265 conn.close()
266
267 scratch = tmp_path / "temp_err"
268 scratch.mkdir()
269 monkeypatch.setattr(tempfile, "tempdir", str(scratch))
270
271 assert cookie_extract._query_cookies_db(db, ".x.com", ["auth_token"]) is None
272 assert list(scratch.iterdir()) == []
273
274 def test_firefox_scoping_rejects_suffix_subdomains_expired_and_cross_scope_mix(self, tmp_path):
275 db = tmp_path / "cookies.sqlite"
276 future = int(time.time()) + 3600
277 past = int(time.time()) - 3600
278 _make_firefox_db(
279 db,
280 [
281 # Suffix/subdomain lookalikes must never match.
282 ("evilx.com", "auth_token", "evil-auth", "/", future, 1, 1, ""),
283 ("sub.x.com", "auth_token", "sub-auth", "/", future, 1, 1, ""),
284 # Expired root cookie must be filtered out.
285 (".x.com", "auth_token", "expired-auth", "/", past, 1, 1, ""),
286 # Containerized/partitioned and subpath cookies must lose to unpartitioned root.
287 (".x.com", "auth_token", "part-auth", "/", future, 1, 1, "^userContextId=2"),
288 (".x.com", "ct0", "part-ct0", "/", future, 1, 1, "^userContextId=2"),
289 (".x.com", "auth_token", "subpath-auth", "/i", future, 1, 1, ""),
290 (".x.com", "ct0", "subpath-ct0", "/i", future, 1, 1, ""),
291 # Insecure cookie on same scope loses to secure cookie.
292 (".x.com", "auth_token", "insecure-auth", "/", future, 0, 1, ""),
293 # Valid unpartitioned root pair.
294 (".X.COM", "auth_token", "good-auth", "/", future, 1, 1, ""),
295 (".x.com", "ct0", "good-ct0", "/", 0, 1, 1, ""),
296 ],
297 )
298 got = cookie_extract._query_cookies_db(db, "x.com", ["auth_token", "ct0"])
299 assert got == {"auth_token": "good-auth", "ct0": "good-ct0"}
300
301 def test_firefox_never_mixes_pairs_across_path_partition_or_subdomain(self, tmp_path):
302 db = tmp_path / "cookies.sqlite"
303 future = int(time.time()) + 3600
304 _make_firefox_db(
305 db,
306 [
307 (".x.com", "auth_token", "root-auth", "/", future, 1, 1, ""),
308 (".x.com", "ct0", "subpath-ct0", "/i", future, 1, 1, ""),
309 (".x.com", "ct0", "part-ct0", "/", future, 1, 1, "^userContextId=2"),
310 ("sub.x.com", "ct0", "subdomain-ct0", "/", future, 1, 1, ""),
311 ],
312 )
313 got = cookie_extract._query_cookies_db(db, ".x.com", ["auth_token", "ct0"])
314 assert got is not None
315 assert set(got) != {"auth_token", "ct0"}
316
317 def test_firefox_pairs_host_only_and_domain_cookies_in_same_scope(self, tmp_path):
318 db = tmp_path / "cookies.sqlite"
319 future = int(time.time()) + 3600
320 _make_firefox_db(
321 db,
322 [
323 ("x.com", "auth_token", "host-auth", "/", future, 1, 1, ""),
324 (".x.com", "ct0", "domain-ct0", "/", future, 1, 1, ""),
325 ],
326 )
327 assert cookie_extract._query_cookies_db(db, ".x.com", ["auth_token", "ct0"]) == {
328 "auth_token": "host-auth",
329 "ct0": "domain-ct0",
330 }
331
332 # When both x.com and .x.com define the same cookie, preferred_host wins.
333 db_both = tmp_path / "both.sqlite"
334 _make_firefox_db(
335 db_both,
336 [
337 ("x.com", "auth_token", "host-auth", "/", future, 1, 1, ""),
338 (".x.com", "auth_token", "domain-auth", "/", future, 1, 1, ""),
339 ],
340 )
341 assert cookie_extract._query_cookies_db(db_both, ".x.com", ["auth_token"]) == {
342 "auth_token": "domain-auth"
343 }
344 assert cookie_extract._query_cookies_db(db_both, "x.com", ["auth_token"]) == {
345 "auth_token": "host-auth"
346 }
347
348 def test_firefox_142_millisecond_expiry_drops_expired_and_keeps_future(self, tmp_path):
349 db = tmp_path / "cookies_v16.sqlite"
350 now_ms = int(time.time()) * 1000
351 past_ms = now_ms - 60_000
352 future_ms = now_ms + 3_600_000
353 _make_firefox_db(
354 db,
355 [
356 (".x.com", "auth_token", "expired-ms-auth", "/", past_ms, 1, 1, ""),
357 (".x.com", "ct0", "tiny-expired-ms-ct0", "/", 500, 1, 1, ""),
358 (".x.com", "auth_token", "valid-ms-auth", "/", future_ms, 1, 1, ""),
359 (".x.com", "ct0", "valid-ms-ct0", "/", future_ms, 1, 1, ""),
360 ],
361 user_version=16,
362 )
363 assert cookie_extract._query_cookies_db(db, ".x.com", ["auth_token", "ct0"]) == {
364 "auth_token": "valid-ms-auth",
365 "ct0": "valid-ms-ct0",
366 }
367
368 # Only expired millisecond rows under user_version=16 -> None.
369 db_exp = tmp_path / "cookies_v16_expired.sqlite"
370 _make_firefox_db(
371 db_exp,
372 [
373 (".x.com", "auth_token", "expired-ms-auth", "/", past_ms, 1, 1, ""),
374 (".x.com", "ct0", "tiny-expired-ms-ct0", "/", 500, 1, 1, ""),
375 ],
376 user_version=16,
377 )
378 assert cookie_extract._query_cookies_db(db_exp, ".x.com", ["auth_token", "ct0"]) is None
379
380
381 # ===========================================================================
382 # HIGH-081: Chromium exact host, expiry, schema, and single-scope pairing
383 # ===========================================================================
384
385
386 def _make_chromium_db(
387 path: Path,
388 rows: list[tuple[str, str, str, bytes, str, int, int, int, str]],
389 *,
390 include_chips: bool = True,
391 db_version: int = 24,
392 ) -> None:
393 conn = sqlite3.connect(str(path))
394 try:
395 conn.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
396 conn.execute("INSERT INTO meta VALUES ('version', ?)", (str(db_version),))
397 chips_col = ", top_frame_site_key TEXT NOT NULL DEFAULT ''" if include_chips else ""
398 conn.execute(
399 "CREATE TABLE cookies ("
400 " host_key TEXT NOT NULL,"
401 " name TEXT NOT NULL,"
402 " value TEXT NOT NULL DEFAULT '',"
403 " encrypted_value BLOB NOT NULL DEFAULT x'',"
404 " path TEXT NOT NULL DEFAULT '/',"
405 " expires_utc INTEGER NOT NULL DEFAULT 0,"
406 " is_secure INTEGER NOT NULL DEFAULT 1,"
407 " is_httponly INTEGER NOT NULL DEFAULT 1"
408 f"{chips_col}"
409 ")"
410 )
411 for host_key, name, value, enc, cpath, exp, sec, httponly, chips in rows:
412 if include_chips:
413 conn.execute(
414 "INSERT INTO cookies "
415 "(host_key, name, value, encrypted_value, path, expires_utc, "
416 "is_secure, is_httponly, top_frame_site_key) "
417 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
418 (host_key, name, value, enc, cpath, exp, sec, httponly, chips),
419 )
420 else:
421 conn.execute(
422 "INSERT INTO cookies "
423 "(host_key, name, value, encrypted_value, path, expires_utc, "
424 "is_secure, is_httponly) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
425 (host_key, name, value, enc, cpath, exp, sec, httponly),
426 )
427 conn.commit()
428 finally:
429 conn.close()
430
431
432 def _chrome_utc(offset_seconds: int) -> int:
433 return (int(time.time()) + offset_seconds + 11644473600) * 1_000_000
434
435
436 class TestHigh081ChromiumCookieScoping:
437 def test_rejects_suffix_confusion_subdomains_and_like_wildcards(self, tmp_path):
438 db = tmp_path / "Cookies"
439 future = _chrome_utc(3600)
440 _make_chromium_db(
441 db,
442 [
443 ("evilx.com", "auth_token", "evil-auth", b"", "/", future, 1, 1, ""),
444 ("notx.com", "ct0", "notx-ct0", b"", "/", future, 1, 1, ""),
445 ("sub.x.com", "auth_token", "sub-auth", b"", "/", future, 1, 1, ""),
446 ("x_com", "auth_token", "wildcard-auth", b"", "/", future, 1, 1, ""),
447 ("x.com.evil.com", "auth_token", "suffix-auth", b"", "/", future, 1, 1, ""),
448 ],
449 )
450 with mock.patch("lib.chrome_cookies._get_chromium_encryption_key") as get_key:
451 assert (
452 chrome_cookies._extract_chromium_cookies_macos(
453 db, "Chrome Safe Storage", "x.com", ["auth_token", "ct0"]
454 )
455 is None
456 )
457 get_key.assert_not_called()
458
459 def test_filters_expired_cookies_before_keychain_lookup(self, tmp_path):
460 db = tmp_path / "Cookies"
461 past = _chrome_utc(-60)
462 _make_chromium_db(
463 db,
464 [
465 (".x.com", "auth_token", "", _V10_AUTH_TOKEN, "/", past, 1, 1, ""),
466 (".x.com", "ct0", "expired-plain", b"", "/", past, 1, 1, ""),
467 ],
468 )
469 with mock.patch("lib.chrome_cookies._get_chromium_encryption_key") as get_key:
470 assert (
471 chrome_cookies._extract_chromium_cookies_macos(
472 db, "Chrome Safe Storage", ".x.com", ["auth_token", "ct0"]
473 )
474 is None
475 )
476 # Expired encrypted rows must never trigger a macOS Keychain prompt.
477 get_key.assert_not_called()
478
479 def test_prefers_unpartitioned_root_secure_scope_over_chips_subpath_and_insecure(self, tmp_path):
480 db = tmp_path / "Cookies"
481 future = _chrome_utc(3600)
482 _make_chromium_db(
483 db,
484 [
485 # Partitioned (CHIPS) complete pair appears first in DB.
486 (".x.com", "auth_token", "chips-auth", b"", "/", future, 1, 1, "https://embed.example"),
487 (".x.com", "ct0", "chips-ct0", b"", "/", future, 1, 1, "https://embed.example"),
488 # Subpath complete pair.
489 (".x.com", "auth_token", "subpath-auth", b"", "/i/flow", future, 1, 1, ""),
490 (".x.com", "ct0", "subpath-ct0", b"", "/i/flow", future, 1, 1, ""),
491 # Insecure cookie in the root scope must lose to secure cookie.
492 (".x.com", "auth_token", "insecure-auth", b"", "/", future, 0, 1, ""),
493 # Legitimate unpartitioned root secure pair (case-insensitive host_key).
494 (".X.COM", "auth_token", "good-auth", b"", "/", future, 1, 1, ""),
495 (".x.com", "ct0", "good-ct0", b"", "/", 0, 1, 1, ""),
496 ],
497 include_chips=True,
498 )
499 got = chrome_cookies._extract_chromium_cookies_macos(
500 db, "Chrome Safe Storage", "x.com", ["auth_token", "ct0"]
501 )
502 assert got == {"auth_token": "good-auth", "ct0": "good-ct0"}
503
504 def test_never_mixes_cookies_across_path_chips_or_subdomain_scopes(self, tmp_path):
505 db = tmp_path / "Cookies"
506 future = _chrome_utc(3600)
507 _make_chromium_db(
508 db,
509 [
510 (".x.com", "auth_token", "root-auth", b"", "/", future, 1, 1, ""),
511 (".x.com", "ct0", "subpath-ct0", b"", "/i", future, 1, 1, ""),
512 (".x.com", "ct0", "chips-ct0", b"", "/", future, 1, 1, "https://other.example"),
513 ("sub.x.com", "ct0", "subdomain-ct0", b"", "/", future, 1, 1, ""),
514 ],
515 include_chips=True,
516 )
517 got = chrome_cookies._extract_chromium_cookies_macos(
518 db, "Chrome Safe Storage", ".x.com", ["auth_token", "ct0"]
519 )
520 assert got is not None
521 assert set(got) != {"auth_token", "ct0"}
522
523 def test_pairs_host_only_and_domain_cookies_in_same_scope(self, tmp_path):
524 db = tmp_path / "Cookies"
525 future = _chrome_utc(3600)
526 _make_chromium_db(
527 db,
528 [
529 ("x.com", "auth_token", "host-auth", b"", "/", future, 1, 1, ""),
530 (".x.com", "ct0", "domain-ct0", b"", "/", future, 1, 1, ""),
531 ],
532 include_chips=True,
533 )
534 assert chrome_cookies._extract_chromium_cookies_macos(
535 db, "Chrome Safe Storage", ".x.com", ["auth_token", "ct0"]
536 ) == {"auth_token": "host-auth", "ct0": "domain-ct0"}
537
538 # When both x.com and .x.com define the same cookie, preferred_host wins.
539 db_both = tmp_path / "Cookies_both"
540 _make_chromium_db(
541 db_both,
542 [
543 ("x.com", "auth_token", "host-auth", b"", "/", future, 1, 1, ""),
544 (".x.com", "auth_token", "domain-auth", b"", "/", future, 1, 1, ""),
545 ],
546 include_chips=True,
547 )
548 assert chrome_cookies._extract_chromium_cookies_macos(
549 db_both, "Chrome Safe Storage", ".x.com", ["auth_token"]
550 ) == {"auth_token": "domain-auth"}
551 assert chrome_cookies._extract_chromium_cookies_macos(
552 db_both, "Chrome Safe Storage", "x.com", ["auth_token"]
553 ) == {"auth_token": "host-auth"}
554
555 def test_never_mixes_cookies_across_has_cross_site_ancestor_partition(self, tmp_path):
556 db = tmp_path / "Cookies_chips_bit"
557 future = _chrome_utc(3600)
558 conn = sqlite3.connect(str(db))
559 try:
560 conn.execute("CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)")
561 conn.execute("INSERT INTO meta VALUES ('version', '24')")
562 conn.execute(
563 "CREATE TABLE cookies ("
564 " host_key TEXT NOT NULL,"
565 " name TEXT NOT NULL,"
566 " value TEXT NOT NULL DEFAULT '',"
567 " encrypted_value BLOB NOT NULL DEFAULT x'',"
568 " path TEXT NOT NULL DEFAULT '/',"
569 " expires_utc INTEGER NOT NULL DEFAULT 0,"
570 " is_secure INTEGER NOT NULL DEFAULT 1,"
571 " is_httponly INTEGER NOT NULL DEFAULT 1,"
572 " top_frame_site_key TEXT NOT NULL DEFAULT '',"
573 " has_cross_site_ancestor INTEGER NOT NULL DEFAULT 0"
574 ")"
575 )
576 # Same host_key, path, and top_frame_site_key — differ ONLY in has_cross_site_ancestor.
577 conn.executemany(
578 "INSERT INTO cookies "
579 "(host_key, name, value, encrypted_value, path, expires_utc, "
580 "is_secure, is_httponly, top_frame_site_key, has_cross_site_ancestor) "
581 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
582 [
583 (".x.com", "auth_token", "same-site-auth", b"", "/", future, 1, 1, "https://x.com", 0),
584 (".x.com", "ct0", "cross-site-ct0", b"", "/", future, 1, 1, "https://x.com", 1),
585 ],
586 )
587 conn.commit()
588 finally:
589 conn.close()
590
591 got = chrome_cookies._extract_chromium_cookies_macos(
592 db, "Chrome Safe Storage", ".x.com", ["auth_token", "ct0"]
593 )
594 assert got is not None
595 assert set(got) != {"auth_token", "ct0"}
596 # Same-site ancestor (0) ranks ahead of cross-site ancestor (1).
597 assert got == {"auth_token": "same-site-auth"}
598
599 def test_works_on_legacy_schema_without_top_frame_site_key(self, tmp_path):
600 db = tmp_path / "Cookies"
601 future = _chrome_utc(3600)
602 _make_chromium_db(
603 db,
604 [
605 ("x.com", "auth_token", "host-auth", b"", "/", future, 1, 1, ""),
606 ("x.com", "ct0", "host-ct0", b"", "/", future, 1, 1, ""),
607 ],
608 include_chips=False,
609 )
610 got = chrome_cookies._extract_chromium_cookies_macos(
611 db, "Chrome Safe Storage", ".x.com", ["auth_token", "ct0"]
612 )
613 assert got == {"auth_token": "host-auth", "ct0": "host-ct0"}
614
615
616 # ===========================================================================
617 # HIGH-082: Strict CDP URL validation, no proxy/redirect, WS hardening
618 # ===========================================================================
619
620
621 class TestHigh082ChromeCdpHardening:
622 @pytest.mark.parametrize(
623 "bad_url",
624 [
625 "http://169.254.169.254:80",
626 "http://evil.example:9222",
627 "http://10.0.0.1:18800",
628 "http://0.0.0.0:18800",
629 "http://localhost.evil.com:18800",
630 "ws://evil.example:18800/devtools/page/1",
631 "https://127.0.0.1:18800",
632 "wss://127.0.0.1:18800/devtools/page/1",
633 "file:///etc/passwd",
634 "ftp://127.0.0.1:21",
635 "data:application/json,{}",
636 "http://user:pass@127.0.0.1:18800",
637 "http://127.0.0.1:18800#frag",
638 "http://127.0.0.1:0",
639 "http://127.0.0.1:65536",
640 "http://127.0.0.1:99999",
641 "http://127.0.0.1",
642 "http://127.0.0.1:18800/extra/path",
643 "ws://127.0.0.1:18800/devtools/page/1 HTTP/1.1\r\nX-Test: 1",
644 "ws://127.0.0.1:18800/devtools/page/1\n",
645 "ws://127.0.0.1:18800/devtools/page/1\r",
646 "ws://127.0.0.1:18800/devtools/page/\u00e9",
647 "ws://127.0.0.1:18800",
648 ],
649 )
650 def test_rejects_unsafe_browser_cdp_urls_without_network_io(self, bad_url):
651 with (
652 mock.patch("socket.create_connection", side_effect=AssertionError("no socket")),
653 mock.patch.object(chrome_cdp._CDP_OPENER, "open", side_effect=AssertionError("no opener")),
654 mock.patch("urllib.request.urlopen", side_effect=AssertionError("no urlopen")),
655 ):
656 assert chrome_cdp.candidate_endpoints({"BROWSER_CDP_URL": bad_url}) == []
657 assert (
658 chrome_cdp.read_x_cookies(
659 {"BROWSER_CDP_URL": bad_url, "BROWSER_CONSENT": "true"}
660 )
661 is None
662 )
663
664 @pytest.mark.parametrize(
665 "raw,expected",
666 [
667 ("127.0.0.1:18800", "http://127.0.0.1:18800"),
668 ("http://localhost:9222/", "http://localhost:9222"),
669 ("http://[::1]:18800", "http://[::1]:18800"),
670 ("[::1]:18800", "http://[::1]:18800"),
671 ("ws://127.0.0.1:18800/devtools/page/ABC", "ws://127.0.0.1:18800/devtools/page/ABC"),
672 ("ws://[::1]:18800/devtools/page/ABC", "ws://[::1]:18800/devtools/page/ABC"),
673 ],
674 )
675 def test_accepts_valid_loopback_http_and_ws_urls(self, raw, expected):
676 assert chrome_cdp._normalize_base(raw) == expected
677
678 def test_http_get_json_refuses_302_redirects(self):
679 target_hits = []
680
681 class TargetHandler(http.server.BaseHTTPRequestHandler):
682 def do_GET(self):
683 target_hits.append(self.path)
684 payload = json.dumps({"Browser": "Chrome/120"}).encode()
685 self.send_response(200)
686 self.send_header("Content-Type", "application/json")
687 self.send_header("Content-Length", str(len(payload)))
688 self.end_headers()
689 self.wfile.write(payload)
690
691 def log_message(self, *_args):
692 pass
693
694 target_srv = http.server.HTTPServer(("127.0.0.1", 0), TargetHandler)
695 target_port = target_srv.server_address[1]
696
697 class RedirectHandler(http.server.BaseHTTPRequestHandler):
698 def do_GET(self):
699 self.send_response(302)
700 self.send_header("Location", f"http://127.0.0.1:{target_port}/json/version")
701 self.end_headers()
702
703 def log_message(self, *_args):
704 pass
705
706 redir_srv = http.server.HTTPServer(("127.0.0.1", 0), RedirectHandler)
707 redir_port = redir_srv.server_address[1]
708
709 t1 = threading.Thread(target=target_srv.serve_forever, daemon=True)
710 t2 = threading.Thread(target=redir_srv.serve_forever, daemon=True)
711 t1.start()
712 t2.start()
713 try:
714 assert chrome_cdp._http_get_json(f"http://127.0.0.1:{redir_port}/json/version") is None
715 assert target_hits == []
716 finally:
717 redir_srv.shutdown()
718 target_srv.shutdown()
719 redir_srv.server_close()
720 target_srv.server_close()
721
722 def test_http_get_json_bypasses_http_proxy_env(self, monkeypatch):
723 proxy_hits = []
724
725 class TrapProxy(http.server.BaseHTTPRequestHandler):
726 def do_GET(self):
727 proxy_hits.append(self.path)
728 self.send_response(200)
729 self.end_headers()
730 self.wfile.write(b'{"Browser": "FakeProxyChrome"}')
731
732 def log_message(self, *_args):
733 pass
734
735 class DirectServer(http.server.BaseHTTPRequestHandler):
736 def do_GET(self):
737 payload = json.dumps({"Browser": "Chrome/Direct"}).encode()
738 self.send_response(200)
739 self.send_header("Content-Type", "application/json")
740 self.send_header("Content-Length", str(len(payload)))
741 self.end_headers()
742 self.wfile.write(payload)
743
744 def log_message(self, *_args):
745 pass
746
747 proxy_srv = http.server.HTTPServer(("127.0.0.1", 0), TrapProxy)
748 direct_srv = http.server.HTTPServer(("127.0.0.1", 0), DirectServer)
749 proxy_port = proxy_srv.server_address[1]
750 direct_port = direct_srv.server_address[1]
751
752 monkeypatch.setenv("HTTP_PROXY", f"http://127.0.0.1:{proxy_port}")
753 monkeypatch.setenv("http_proxy", f"http://127.0.0.1:{proxy_port}")
754 monkeypatch.delenv("NO_PROXY", raising=False)
755 monkeypatch.delenv("no_proxy", raising=False)
756
757 t1 = threading.Thread(target=proxy_srv.serve_forever, daemon=True)
758 t2 = threading.Thread(target=direct_srv.serve_forever, daemon=True)
759 t1.start()
760 t2.start()
761 try:
762 got = chrome_cdp._http_get_json(f"http://127.0.0.1:{direct_port}/json/version")
763 assert got == {"Browser": "Chrome/Direct"}
764 assert proxy_hits == []
765 finally:
766 proxy_srv.shutdown()
767 direct_srv.shutdown()
768 proxy_srv.server_close()
769 direct_srv.server_close()
770
771 def test_cdp_opener_omits_file_ftp_data_and_https_handlers(self):
772 opener = chrome_cdp._CDP_OPENER
773 handler_types = tuple(type(h) for h in opener.handlers)
774 for forbidden in (
775 urllib.request.FileHandler,
776 urllib.request.FTPHandler,
777 urllib.request.DataHandler,
778 urllib.request.HTTPSHandler,
779 ):
780 assert forbidden not in handler_types
781
782 def test_http_get_json_always_uses_cdp_opener_even_when_urlopen_is_wrapped(self):
783 class DirectHandler(http.server.BaseHTTPRequestHandler):
784 def do_GET(self):
785 payload = json.dumps({"Browser": "Chrome/OpenerOnly"}).encode()
786 self.send_response(200)
787 self.send_header("Content-Type", "application/json")
788 self.send_header("Content-Length", str(len(payload)))
789 self.end_headers()
790 self.wfile.write(payload)
791
792 def log_message(self, *_args):
793 pass
794
795 srv = http.server.HTTPServer(("127.0.0.1", 0), DirectHandler)
796 port = srv.server_address[1]
797 thread = threading.Thread(target=srv.serve_forever, daemon=True)
798 thread.start()
799 try:
800 with mock.patch(
801 "urllib.request.urlopen",
802 side_effect=AssertionError("CDP must never fall back to wrapped urlopen"),
803 ):
804 got = chrome_cdp._http_get_json(f"http://127.0.0.1:{port}/json/version")
805 assert got == {"Browser": "Chrome/OpenerOnly"}
806 finally:
807 srv.shutdown()
808 srv.server_close()
809
810 @pytest.mark.parametrize(
811 "spoofed_ws",
812 [
813 "ws://169.254.169.254:80/devtools/page/1",
814 "ws://127.0.0.1:6379/devtools/page/1",
815 "ws://localhost:18800/devtools/page/1", # host mismatch against 127.0.0.1
816 "ws://127.0.0.1:18800/devtools/page/1 HTTP/1.1\r\nHost: evil",
817 "ws://127.0.0.1:18800/devtools/page/1\n",
818 "wss://127.0.0.1:18800/devtools/page/1",
819 ],
820 )
821 def test_page_ws_url_rejects_cross_endpoint_or_injected_targets(self, spoofed_ws):
822 targets = [{"type": "page", "webSocketDebuggerUrl": spoofed_ws}]
823 with mock.patch("lib.chrome_cdp._http_get_json", return_value=targets):
824 assert chrome_cdp._page_ws_url("http://127.0.0.1:18800") is None
825
826 @pytest.mark.parametrize(
827 "malicious_ws",
828 [
829 "ws://127.0.0.1:18800/a HTTP/1.1\r\nX-Smuggled: 1",
830 "ws://127.0.0.1:18800/a\rb",
831 "ws://127.0.0.1:18800/a\n",
832 "ws://127.0.0.1:99999/devtools/page/1",
833 "ws://127.0.0.1:18800/devtools/page/\u00e9",
834 "ws://evil.example:18800/devtools/page/1",
835 "ws://user@127.0.0.1:18800/devtools/page/1",
836 "ws://127.0.0.1:18800/devtools/page/1#frag",
837 ],
838 )
839 def test_wsconn_connect_rejects_injection_overflow_and_non_ascii_without_raising(self, malicious_ws):
840 with mock.patch("socket.create_connection", side_effect=AssertionError("must not connect")):
841 assert chrome_cdp._WSConn.connect(malicious_ws, 1.0) is None
842
843 def test_wsconn_connect_closes_socket_on_send_error(self):
844 fake_sock = mock.MagicMock(spec=socket.socket)
845 fake_sock.sendall.side_effect = UnicodeEncodeError("ascii", "x", 0, 1, "boom")
846 with mock.patch("socket.create_connection", return_value=fake_sock):
847 assert (
848 chrome_cdp._WSConn.connect("ws://127.0.0.1:18800/devtools/page/ABC", 1.0) is None
849 )
850 fake_sock.close.assert_called_once()
851
852 @pytest.mark.parametrize(
853 "env_refusal",
854 [
855 {"FROM_BROWSER": "off"},
856 {"BROWSER_CONSENT": "false"},
857 {"BROWSER_CONSENT": "unknown"},
858 ],
859 )
860 def test_cookie_access_allowed_honors_env_refusal(self, monkeypatch, env_refusal):
861 for k, v in env_refusal.items():
862 monkeypatch.setenv(k, v)
863 assert chrome_cdp.cookie_access_allowed({"BROWSER_CONSENT": "true"}) is False
864 assert chrome_cdp.cookie_access_allowed({"FROM_BROWSER": "chrome"}) is False
865
866
867 # ===========================================================================
868 # HIGH-083: Owner-only Chrome login profile directory in box_chrome_login.py
869 # ===========================================================================
870
871
872 class TestHigh083BoxChromeLoginProfileDir:
873 def test_default_profile_dir_is_never_fixed_tmp_path(self, tmp_path, monkeypatch):
874 assert bcl.DEFAULT_PROFILE_DIR != "/tmp/last30days-x-chrome"
875 assert Path(bcl.DEFAULT_PROFILE_DIR).parent != Path("/tmp")
876
877 runtime = tmp_path / "run"
878 runtime.mkdir(mode=0o700)
879 os.chmod(runtime, 0o700)
880 monkeypatch.setenv("XDG_RUNTIME_DIR", str(runtime))
881 assert bcl._default_profile_dir() == str(runtime / "last30days-x-chrome")
882
883 # World-writable XDG_RUNTIME_DIR (e.g. /tmp) is rejected -> uses safe 0700 XDG_CACHE_HOME.
884 monkeypatch.setenv("XDG_RUNTIME_DIR", "/tmp")
885 cache = tmp_path / "cache"
886 cache.mkdir(mode=0o700)
887 os.chmod(cache, 0o700)
888 monkeypatch.setenv("XDG_CACHE_HOME", str(cache))
889 assert bcl._default_profile_dir() == str(cache / "last30days" / "x-chrome")
890
891 # Unsafe XDG_CACHE_HOME (e.g. /tmp or loose mode) falls back to ~/.cache.
892 monkeypatch.setenv("XDG_CACHE_HOME", "/tmp")
893 assert bcl._default_profile_dir() == str(Path.home() / ".cache" / "last30days" / "x-chrome")
894
895 def test_render_recipe_and_setup_guide_launch_via_exec(self, tmp_path):
896 profile = tmp_path / "custom profile"
897 with (
898 mock.patch("lib.env.x_extras_enabled", return_value=True),
899 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
900 ):
901 recipe = bcl.build_recipe({}, profile_dir=str(profile))
902 rendered = bcl.render_recipe(recipe)
903 assert "box_chrome_login.py" in rendered
904 assert "--exec" in rendered
905 assert f"--profile-dir '{profile}'" in rendered
906 assert "mkdir " not in rendered
907 assert "/tmp/last30days-x-chrome" not in rendered
908
909 setup_doc = (
910 Path(__file__).resolve().parents[1]
911 / "skills"
912 / "last30days"
913 / "references"
914 / "setup-wizard.md"
915 ).read_text(encoding="utf-8")
916 assert "/tmp/last30days-x-chrome" not in setup_doc
917 assert 'box_chrome_login.py" --exec' in setup_doc
918 assert "--profile-dir" in setup_doc
919
920 @pytest.mark.skipif(os.name == "nt", reason="POSIX canonical path checks")
921 def test_exec_passes_verified_canonical_profile_dir_to_chrome(self, tmp_path, monkeypatch):
922 monkeypatch.chdir(tmp_path)
923 popen = mock.MagicMock()
924 with (
925 mock.patch("lib.env.x_extras_enabled", return_value=True),
926 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
927 mock.patch.object(bcl.env, "get_config", return_value={}),
928 mock.patch("subprocess.Popen", popen),
929 ):
930 assert bcl.main(["--exec", "--profile-dir", "rel-profile"]) == 0
931 expected = str((tmp_path / "rel-profile").resolve(strict=True))
932 assert popen.call_args.kwargs["env"]["CHROME_USER_DATA_DIR"] == expected
933 assert stat.S_IMODE(os.lstat(expected).st_mode) == 0o700
934
935 @pytest.mark.skipif(os.name == "nt", reason="POSIX fallback cache checks")
936 @pytest.mark.parametrize("bad_mode", [0o777, 0o775])
937 def test_exec_rejects_writable_fallback_home_cache_dir(self, tmp_path, monkeypatch, bad_mode):
938 fake_home = tmp_path / "home"
939 fake_home.mkdir(mode=0o700)
940 os.chmod(fake_home, 0o700)
941 cache_dir = fake_home / ".cache"
942 cache_dir.mkdir()
943 os.chmod(cache_dir, bad_mode)
944 monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False)
945 monkeypatch.delenv("XDG_CACHE_HOME", raising=False)
946 monkeypatch.setenv("HOME", str(fake_home))
947 try:
948 with (
949 mock.patch("lib.env.x_extras_enabled", return_value=True),
950 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
951 mock.patch.object(bcl.env, "get_config", return_value={}),
952 mock.patch(
953 "subprocess.Popen",
954 side_effect=AssertionError("must not spawn with writable ~/.cache"),
955 ),
956 ):
957 assert bcl.main(["--exec"]) == 1
958 finally:
959 os.chmod(cache_dir, 0o700)
960
961 @pytest.mark.skipif(os.name == "nt", reason="POSIX symlink fallback checks")
962 def test_exec_rejects_symlink_fallback_home_cache_dir(self, tmp_path, monkeypatch):
963 fake_home = tmp_path / "home"
964 fake_home.mkdir(mode=0o700)
965 os.chmod(fake_home, 0o700)
966 real_cache = tmp_path / "real-cache"
967 real_cache.mkdir(mode=0o700)
968 os.chmod(real_cache, 0o700)
969 (fake_home / ".cache").symlink_to(real_cache)
970 monkeypatch.delenv("XDG_RUNTIME_DIR", raising=False)
971 monkeypatch.delenv("XDG_CACHE_HOME", raising=False)
972 monkeypatch.setenv("HOME", str(fake_home))
973 with (
974 mock.patch("lib.env.x_extras_enabled", return_value=True),
975 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
976 mock.patch.object(bcl.env, "get_config", return_value={}),
977 mock.patch(
978 "subprocess.Popen",
979 side_effect=AssertionError("must not spawn when ~/.cache is a symlink"),
980 ),
981 ):
982 assert bcl.main(["--exec"]) == 1
983
984 @pytest.mark.skipif(os.name == "nt", reason="POSIX resolved ancestor checks")
985 def test_exec_verifies_resolved_ancestor_chain_behind_root_symlink(self, tmp_path):
986 # Simulate a root-owned ancestor symlink (like macOS /var -> /private/var)
987 # pointing to a 0o700 target whose own parent in the resolved path is 0o777.
988 unsafe_parent = tmp_path / "unsafe-resolved-parent"
989 unsafe_parent.mkdir()
990 os.chmod(unsafe_parent, 0o777)
991 safe_target = unsafe_parent / "safe-target"
992 safe_target.mkdir(mode=0o700)
993 os.chmod(safe_target, 0o700)
994 parent_in_target = safe_target / "owned-parent"
995 parent_in_target.mkdir(mode=0o700)
996 os.chmod(parent_in_target, 0o700)
997 profile_in_target = parent_in_target / "x-chrome"
998 profile_in_target.mkdir(mode=0o700)
999 os.chmod(profile_in_target, 0o700)
1000
1001 root_link = tmp_path / "sys-link"
1002 root_link.symlink_to(safe_target)
1003 via_link = root_link / "owned-parent" / "x-chrome"
1004
1005 real_lstat = os.lstat
1006
1007 def root_owned_symlink_lstat(path, *args, **kwargs):
1008 st = real_lstat(path, *args, **kwargs)
1009 if Path(path) == root_link:
1010 fake = mock.MagicMock()
1011 fake.st_mode = st.st_mode
1012 fake.st_uid = 0
1013 fake.st_dev = st.st_dev
1014 fake.st_ino = st.st_ino
1015 return fake
1016 return st
1017
1018 try:
1019 with (
1020 mock.patch("os.lstat", side_effect=root_owned_symlink_lstat),
1021 mock.patch("lib.env.x_extras_enabled", return_value=True),
1022 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1023 mock.patch.object(bcl.env, "get_config", return_value={}),
1024 mock.patch(
1025 "subprocess.Popen",
1026 side_effect=AssertionError("must reject unsafe resolved ancestor chain"),
1027 ),
1028 ):
1029 assert bcl.main(["--exec", "--profile-dir", str(via_link)]) == 1
1030 finally:
1031 os.chmod(unsafe_parent, 0o700)
1032
1033 # Once the resolved ancestor is safe (0o700), --exec succeeds and passes the canonical path.
1034 popen = mock.MagicMock()
1035 with (
1036 mock.patch("os.lstat", side_effect=root_owned_symlink_lstat),
1037 mock.patch("lib.env.x_extras_enabled", return_value=True),
1038 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1039 mock.patch.object(bcl.env, "get_config", return_value={}),
1040 mock.patch("subprocess.Popen", popen),
1041 ):
1042 assert bcl.main(["--exec", "--profile-dir", str(via_link)]) == 0
1043 assert popen.call_args.kwargs["env"]["CHROME_USER_DATA_DIR"] == str(
1044 profile_in_target.resolve(strict=True)
1045 )
1046
1047 @pytest.mark.skipif(os.name == "nt", reason="POSIX pre-mutation resolved ancestor checks")
1048 def test_exec_fails_before_creating_dirs_or_chmodding_behind_unsafe_root_symlink(self, tmp_path):
1049 # Case 1: missing subdirectories behind a root-owned symlink into an unsafe
1050 # resolved ancestor must NOT be created before rejection.
1051 unsafe_parent = tmp_path / "unsafe-precheck-parent"
1052 unsafe_parent.mkdir()
1053 os.chmod(unsafe_parent, 0o777)
1054 safe_target = unsafe_parent / "safe-target"
1055 safe_target.mkdir(mode=0o700)
1056 os.chmod(safe_target, 0o700)
1057
1058 root_link = tmp_path / "sys-precheck-link"
1059 root_link.symlink_to(safe_target)
1060 missing_parent = root_link / "should-not-be-created"
1061 missing_profile = missing_parent / "x-chrome"
1062
1063 # Case 2: existing profile with loose mode (0o755) behind the unsafe resolved
1064 # ancestor must NOT have its mode modified before rejection.
1065 existing_parent = safe_target / "existing-parent"
1066 existing_parent.mkdir(mode=0o700)
1067 os.chmod(existing_parent, 0o700)
1068 existing_profile = existing_parent / "x-chrome"
1069 existing_profile.mkdir()
1070 os.chmod(existing_profile, 0o755)
1071 via_existing = root_link / "existing-parent" / "x-chrome"
1072
1073 real_lstat = os.lstat
1074
1075 def root_owned_symlink_lstat(path, *args, **kwargs):
1076 st = real_lstat(path, *args, **kwargs)
1077 if Path(path) == root_link:
1078 fake = mock.MagicMock()
1079 fake.st_mode = st.st_mode
1080 fake.st_uid = 0
1081 fake.st_dev = st.st_dev
1082 fake.st_ino = st.st_ino
1083 return fake
1084 return st
1085
1086 try:
1087 with mock.patch("os.lstat", side_effect=root_owned_symlink_lstat):
1088 with pytest.raises(PermissionError):
1089 bcl._ensure_private_profile_dir(str(missing_profile))
1090 assert not (safe_target / "should-not-be-created").exists()
1091
1092 with pytest.raises(PermissionError):
1093 bcl._ensure_private_profile_dir(str(via_existing))
1094 assert stat.S_IMODE(real_lstat(existing_profile).st_mode) == 0o755
1095 finally:
1096 os.chmod(unsafe_parent, 0o700)
1097 os.chmod(existing_profile, 0o700)
1098
1099 def test_configuration_md_documents_profile_dir_flag_and_trust_requirement(self):
1100 cfg_doc = (
1101 Path(__file__).resolve().parents[1] / "CONFIGURATION.md"
1102 ).read_text(encoding="utf-8")
1103 assert "box_chrome_login.py --exec" in cfg_doc
1104 assert "--profile-dir" in cfg_doc
1105 assert "trusted non-symlink" in cfg_doc
1106
1107 @pytest.mark.skipif(os.name == "nt", reason="POSIX mode/uid checks")
1108 def test_exec_creates_0700_dir_and_tightens_loose_owner_dir(self, tmp_path):
1109 profile = tmp_path / "new-profile"
1110 popen = mock.MagicMock()
1111 with (
1112 mock.patch("lib.env.x_extras_enabled", return_value=True),
1113 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1114 mock.patch.object(bcl.env, "get_config", return_value={}),
1115 mock.patch("subprocess.Popen", popen),
1116 ):
1117 assert bcl.main(["--exec", "--profile-dir", str(profile)]) == 0
1118 assert stat.S_IMODE(os.lstat(profile).st_mode) == 0o700
1119
1120 # Existing owner-owned directory with 0755 gets tightened to 0700.
1121 os.chmod(profile, 0o755)
1122 with (
1123 mock.patch("lib.env.x_extras_enabled", return_value=True),
1124 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1125 mock.patch.object(bcl.env, "get_config", return_value={}),
1126 mock.patch("subprocess.Popen", popen),
1127 ):
1128 assert bcl.main(["--exec", "--profile-dir", str(profile)]) == 0
1129 assert stat.S_IMODE(os.lstat(profile).st_mode) == 0o700
1130
1131 @pytest.mark.skipif(os.name == "nt", reason="POSIX symlink/uid checks")
1132 def test_exec_aborts_nonzero_on_symlink_profile_dir(self, tmp_path):
1133 real_dir = tmp_path / "attacker"
1134 real_dir.mkdir(mode=0o777)
1135 link = tmp_path / "symlink-profile"
1136 link.symlink_to(real_dir)
1137 with (
1138 mock.patch("lib.env.x_extras_enabled", return_value=True),
1139 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1140 mock.patch.object(bcl.env, "get_config", return_value={}),
1141 mock.patch.object(bcl, "_default_profile_dir", return_value=str(link)),
1142 mock.patch("subprocess.Popen", side_effect=AssertionError("must not spawn on symlink")),
1143 ):
1144 assert bcl.main(["--exec"]) == 1
1145
1146 @pytest.mark.skipif(os.name == "nt", reason="POSIX parent trust checks")
1147 @pytest.mark.parametrize("parent_mode", [0o777, 0o775, 0o720])
1148 def test_exec_aborts_nonzero_on_group_or_world_writable_parent_dir(self, tmp_path, parent_mode):
1149 parent = tmp_path / "writable-parent"
1150 parent.mkdir()
1151 os.chmod(parent, parent_mode)
1152 profile = parent / "x-chrome"
1153 profile.mkdir(mode=0o700)
1154 os.chmod(profile, 0o700)
1155 try:
1156 with (
1157 mock.patch("lib.env.x_extras_enabled", return_value=True),
1158 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1159 mock.patch.object(bcl.env, "get_config", return_value={}),
1160 mock.patch("subprocess.Popen", side_effect=AssertionError("must not spawn under writable parent")),
1161 ):
1162 assert bcl.main(["--exec", "--profile-dir", str(profile)]) == 1
1163 finally:
1164 os.chmod(parent, 0o700)
1165
1166 @pytest.mark.skipif(os.name == "nt", reason="POSIX ancestor trust checks")
1167 def test_exec_aborts_nonzero_on_writable_non_sticky_cache_ancestor(self, tmp_path):
1168 unsafe_cache = tmp_path / "unsafe-cache"
1169 unsafe_cache.mkdir()
1170 os.chmod(unsafe_cache, 0o777)
1171 parent = unsafe_cache / "last30days"
1172 parent.mkdir(mode=0o700)
1173 os.chmod(parent, 0o700)
1174 profile = parent / "x-chrome"
1175 profile.mkdir(mode=0o700)
1176 os.chmod(profile, 0o700)
1177 try:
1178 with (
1179 mock.patch("lib.env.x_extras_enabled", return_value=True),
1180 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1181 mock.patch.object(bcl.env, "get_config", return_value={}),
1182 mock.patch("subprocess.Popen", side_effect=AssertionError("must not spawn under writable ancestor")),
1183 ):
1184 assert bcl.main(["--exec", "--profile-dir", str(profile)]) == 1
1185 finally:
1186 os.chmod(unsafe_cache, 0o700)
1187
1188 @pytest.mark.skipif(os.name == "nt", reason="POSIX immediate parent checks")
1189 def test_exec_aborts_nonzero_on_shared_tmp_immediate_parent(self):
1190 with (
1191 mock.patch("lib.env.x_extras_enabled", return_value=True),
1192 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1193 mock.patch.object(bcl.env, "get_config", return_value={}),
1194 mock.patch("subprocess.Popen", side_effect=AssertionError("must not spawn directly in /tmp")),
1195 ):
1196 assert bcl.main(["--exec", "--profile-dir", "/tmp/last30days-x-chrome-test"]) == 1
1197
1198 @pytest.mark.skipif(os.name == "nt", reason="POSIX symlink parent checks")
1199 def test_exec_aborts_nonzero_on_symlink_parent_dir(self, tmp_path):
1200 real_parent = tmp_path / "real-parent"
1201 real_parent.mkdir(mode=0o700)
1202 os.chmod(real_parent, 0o700)
1203 link_parent = tmp_path / "link-parent"
1204 link_parent.symlink_to(real_parent)
1205 profile = link_parent / "x-chrome"
1206 with (
1207 mock.patch("lib.env.x_extras_enabled", return_value=True),
1208 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1209 mock.patch.object(bcl.env, "get_config", return_value={}),
1210 mock.patch("subprocess.Popen", side_effect=AssertionError("must not spawn under symlink parent")),
1211 ):
1212 assert bcl.main(["--exec", "--profile-dir", str(profile)]) == 1
1213
1214 @pytest.mark.skipif(os.name == "nt", reason="POSIX uid checks")
1215 def test_exec_aborts_nonzero_on_foreign_owner_profile_dir(self, tmp_path):
1216 profile = tmp_path / "foreign-profile"
1217 profile.mkdir(mode=0o700)
1218 real_lstat = os.lstat
1219 fake_stat = mock.MagicMock()
1220 fake_stat.st_mode = stat.S_IFDIR | 0o700
1221 fake_stat.st_uid = os.getuid() + 1
1222
1223 def selective_lstat(path, *args, **kwargs):
1224 if Path(path) == profile:
1225 return fake_stat
1226 return real_lstat(path, *args, **kwargs)
1227
1228 with (
1229 mock.patch("lib.env.x_extras_enabled", return_value=True),
1230 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1231 mock.patch.object(bcl.env, "get_config", return_value={}),
1232 mock.patch.object(bcl, "_default_profile_dir", return_value=str(profile)),
1233 mock.patch("os.lstat", side_effect=selective_lstat),
1234 mock.patch("subprocess.Popen", side_effect=AssertionError("must not spawn on foreign uid")),
1235 ):
1236 assert bcl.main(["--exec"]) == 1
1237
1238 def test_exec_aborts_nonzero_when_makedirs_fails(self, tmp_path):
1239 profile = tmp_path / "uncreatable"
1240 with (
1241 mock.patch("lib.env.x_extras_enabled", return_value=True),
1242 mock.patch("shutil.which", return_value="/usr/local/bin/box-chrome"),
1243 mock.patch.object(bcl.env, "get_config", return_value={}),
1244 mock.patch.object(bcl, "_default_profile_dir", return_value=str(profile)),
1245 mock.patch("os.makedirs", side_effect=PermissionError("read-only")),
1246 mock.patch("subprocess.Popen", side_effect=AssertionError("must not spawn on OSError")),
1247 ):
1248 assert bcl.main(["--exec"]) == 1
1249
1250
1251 # ===========================================================================
1252 # HIGH-084: Symmetric consent resolution & FROM_BROWSER pin in agentcookie
1253 # ===========================================================================
1254
1255
1256 class TestHigh084AgentcookieConsentGate:
1257 @pytest.mark.parametrize(
1258 "env_vars,cfg",
1259 [
1260 ({"FROM_BROWSER": "off", "AGENTCOOKIE": "on"}, {}),
1261 ({"BROWSER_CONSENT": "false", "AGENTCOOKIE": "on"}, {}),
1262 ({"BROWSER_CONSENT": "unknown", "AGENTCOOKIE": "on"}, {}),
1263 ({"FROM_BROWSER": "off"}, {"AGENTCOOKIE": "on"}),
1264 ({"BROWSER_CONSENT": "false"}, {"AGENTCOOKIE": "on"}),
1265 ({"BROWSER_CONSENT": "false"}, {"BROWSER_CONSENT": "true"}),
1266 ({"AGENTCOOKIE": "off"}, {"AGENTCOOKIE": "on", "BROWSER_CONSENT": "true"}),
1267 ({"AGENTCOOKIE": "on"}, {"FROM_BROWSER": "off"}),
1268 ({"AGENTCOOKIE": "on"}, {"BROWSER_CONSENT": "false"}),
1269 ],
1270 )
1271 def test_refusal_in_either_env_or_config_always_vetoes(self, monkeypatch, env_vars, cfg):
1272 for k, v in env_vars.items():
1273 monkeypatch.setenv(k, v)
1274 with (
1275 mock.patch("shutil.which", return_value="/mock/agentcookie"),
1276 mock.patch("subprocess.run", side_effect=AssertionError("refused sidecar must not run")),
1277 ):
1278 assert agentcookie.is_disabled(cfg) is True
1279 assert agentcookie.is_available(cfg) is False
1280 assert agentcookie.read_x_cookies(cfg) is None
1281
1282 @pytest.mark.parametrize(
1283 "cfg",
1284 [
1285 {"FROM_BROWSER": "firefox", "BROWSER_CONSENT": "true"},
1286 {"FROM_BROWSER": "chrome", "BROWSER_CONSENT": "true"},
1287 {"FROM_BROWSER": "firefox,safari", "BROWSER_CONSENT": "true"},
1288 ],
1289 )
1290 @pytest.mark.parametrize("via_env", [False, True])
1291 def test_explicit_browser_pin_does_not_auto_enable_sidecar(self, monkeypatch, cfg, via_env):
1292 if via_env:
1293 for k, v in cfg.items():
1294 monkeypatch.setenv(k, v)
1295 passed = None
1296 else:
1297 passed = cfg
1298 with (
1299 mock.patch("shutil.which", return_value="/mock/agentcookie"),
1300 mock.patch("subprocess.run", side_effect=AssertionError("pinned browser must not invoke sidecar")),
1301 ):
1302 assert agentcookie.is_disabled(passed) is True
1303 assert agentcookie.is_available(passed) is False
1304 assert agentcookie.read_x_cookies(passed) is None
1305
1306 def test_env_browser_pin_blocks_sidecar_even_with_partial_config(self, monkeypatch):
1307 monkeypatch.setenv("FROM_BROWSER", "firefox")
1308 assert agentcookie.is_disabled({"BROWSER_CONSENT": "true"}) is True
1309
1310 def test_explicit_agentcookie_on_overrides_browser_pin_without_refusal(self):
1311 cfg = {"FROM_BROWSER": "firefox", "BROWSER_CONSENT": "true", "AGENTCOOKIE": "on"}
1312 assert agentcookie.is_disabled(cfg) is False
1313
1314 def test_auto_or_unset_from_browser_with_consent_still_allows_sidecar(self):
1315 assert agentcookie.is_disabled({"BROWSER_CONSENT": "true"}) is False
1316 assert agentcookie.is_disabled({"FROM_BROWSER": "auto", "BROWSER_CONSENT": "true"}) is False
1317
1317 lines PYTHON