返回 last30days-skill
test_cr20_auth.py
根目录 / tests / test_cr20_auth.py
1 """Offline regressions for credential persistence and browser snapshots."""
2
3 from __future__ import annotations
4
5 import os
6 from pathlib import Path
7 import sqlite3
8 import subprocess
9 import sys
10 import time
11
12 import pytest
13
14 import last30days as cli
15 from lib import chrome_cookies, cookie_extract, env, setup_wizard, sqlite_snapshot
16
17
18 SCRIPTS = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts"
19
20
21 @pytest.fixture
22 def password_store(tmp_path, monkeypatch):
23 store = tmp_path / "dummy password store"
24 entry = store / "last30days" / "OPENAI_API_KEY.gpg"
25 entry.parent.mkdir(parents=True)
26 binary_dir = tmp_path / "bin"
27 binary_dir.mkdir()
28 calls = tmp_path / "pass-calls.txt"
29 binary = binary_dir / "pass"
30 binary.write_text(
31 f"#!{sys.executable}\n"
32 "import os, pathlib, sys\n"
33 "args = sys.argv[1:]\n"
34 "with open(os.environ['DUMMY_PASS_CALLS'], 'a') as f:\n"
35 " f.write(' '.join(args) + '\\n')\n"
36 "entry = pathlib.Path(os.environ['PASSWORD_STORE_DIR']) / (args[-1] + '.gpg')\n"
37 "if args[0] == 'show':\n"
38 " if os.environ.get('DUMMY_DECRYPT_FAILURE') == '1':\n"
39 " sys.exit(2)\n"
40 " sys.exit(0 if entry.exists() else 1)\n"
41 "if args[0] == 'insert':\n"
42 " # pass yesno() accepts non-TTY input even without --force.\n"
43 " entry.write_text(sys.stdin.read())\n"
44 " sys.exit(0)\n"
45 "sys.exit(3)\n",
46 encoding="utf-8",
47 )
48 binary.chmod(0o700)
49 monkeypatch.setenv("PATH", str(binary_dir) + os.pathsep + os.environ["PATH"])
50 monkeypatch.setenv("PASSWORD_STORE_DIR", str(store))
51 monkeypatch.setenv("DUMMY_PASS_CALLS", str(calls))
52 return entry, calls
53
54
55 def _run_setup_pass(*args):
56 return subprocess.run(
57 ["bash", str(SCRIPTS / "setup-pass.sh"), *args, "OPENAI_API_KEY"],
58 input="dummy-new-key\n", text=True, capture_output=True, timeout=10,
59 )
60
61
62 def test_pass_decryption_failure_cannot_overwrite_existing_entry(password_store, monkeypatch):
63 entry, calls = password_store
64 entry.write_text("dummy-original-encrypted-value\n")
65 monkeypatch.setenv("DUMMY_DECRYPT_FAILURE", "1")
66
67 result = _run_setup_pass()
68
69 assert entry.read_text() == "dummy-original-encrypted-value\n"
70 assert "insert" not in (calls.read_text() if calls.exists() else "")
71 assert "skipping" in result.stdout
72
73
74 def test_pass_missing_entry_is_inserted_without_force(password_store):
75 entry, calls = password_store
76 result = _run_setup_pass()
77 assert result.returncode == 0, result.stderr
78 assert entry.read_text() == "dummy-new-key\n"
79 assert "added=1 replaced=0" in result.stdout
80 assert " -f " not in calls.read_text()
81
82
83 def test_pass_existing_entry_is_skipped_without_replace(password_store):
84 entry, calls = password_store
85 entry.write_text("dummy-original-encrypted-value\n")
86 result = _run_setup_pass()
87 assert result.returncode == 0, result.stderr
88 assert entry.read_text() == "dummy-original-encrypted-value\n"
89 assert "insert" not in (calls.read_text() if calls.exists() else "")
90
91
92 def test_pass_explicit_replace_updates_existing_entry(password_store):
93 entry, calls = password_store
94 entry.write_text("dummy-original-encrypted-value\n")
95 result = _run_setup_pass("--replace")
96 assert result.returncode == 0, result.stderr
97 assert entry.read_text() == "dummy-new-key\n"
98 assert "added=0 replaced=1" in result.stdout
99 assert "insert -m -f -- last30days/OPENAI_API_KEY" in calls.read_text()
100
101
102 def test_pass_entry_created_while_prompting_is_not_overwritten(password_store):
103 entry, calls = password_store
104 process = subprocess.Popen(
105 ["bash", str(SCRIPTS / "setup-pass.sh"), "OPENAI_API_KEY"],
106 stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
107 text=True,
108 )
109 try:
110 assert process.stdout.read(31) == f" {'OPENAI_API_KEY':<28} "
111 entry.write_text("dummy-concurrently-created-key\n")
112 stdout, stderr = process.communicate("dummy-new-key\n", timeout=10)
113 assert process.returncode == 0, stderr
114 assert entry.read_text() == "dummy-concurrently-created-key\n"
115 assert "insert" not in (calls.read_text() if calls.exists() else "")
116 assert "skipping" in stdout
117 finally:
118 if process.poll() is None:
119 process.kill()
120 process.communicate()
121
122
123 @pytest.mark.parametrize("assignment", [
124 "SCRAPECREATORS_API_KEY=",
125 'SCRAPECREATORS_API_KEY=""',
126 "export SCRAPECREATORS_API_KEY='' # awaiting signup",
127 "SCRAPECREATORS_API_KEY= # awaiting signup",
128 ])
129 def test_signup_persists_usable_key_over_empty_assignment(tmp_path, monkeypatch, capsys, assignment):
130 env_path = tmp_path / ".env"
131 env_path.write_text(assignment + "\nSETUP_COMPLETE=true\n")
132 monkeypatch.setattr(env, "CONFIG_FILE", env_path)
133 monkeypatch.setattr(sys, "argv", ["last30days.py", "setup", "--github"])
134 monkeypatch.setattr(setup_wizard, "run_github_auth", lambda: {
135 "status": "success", "api_key": "dummy-signup-key-0123456789",
136 })
137
138 assert cli.main() == 0
139
140 output = capsys.readouterr()
141 assert env.load_env_file(env_path)["SCRAPECREATORS_API_KEY"] == "dummy-signup-key-0123456789"
142 assert '"persisted": true' in output.out
143 assert "dummy-signup-key-0123456789" not in output.out + output.err
144 assert env.load_env_file(env_path)["SETUP_COMPLETE"] == "true"
145 assert env_path.read_text().count("SCRAPECREATORS_API_KEY") == 1
146 if os.name != "nt":
147 assert env_path.stat().st_mode & 0o777 == 0o600
148
149
150 def test_signup_writer_preserves_nonempty_duplicate_assignment(tmp_path):
151 env_path = tmp_path / ".env"
152 original = 'SCRAPECREATORS_API_KEY=""\nSCRAPECREATORS_API_KEY=dummy-user-key\n'
153 env_path.write_text(original)
154 assert setup_wizard.write_api_key(env_path, "dummy-signup-key")
155 assert env_path.read_text() == original
156 assert env.load_env_file(env_path)["SCRAPECREATORS_API_KEY"] == "dummy-user-key"
157
158
159 @pytest.mark.parametrize("browser", ["firefox", "chrome"])
160 def test_browser_snapshot_reads_committed_wal_without_changing_database(tmp_path, browser):
161 database = tmp_path / "cookie database #1.sqlite"
162 table = "moz_cookies" if browser == "firefox" else "cookies"
163 host = "host" if browser == "firefox" else "host_key"
164 connection = sqlite3.connect(database)
165 try:
166 connection.execute("PRAGMA journal_mode=WAL")
167 connection.execute("PRAGMA wal_autocheckpoint=0")
168 connection.execute(
169 f"CREATE TABLE {table} (name TEXT, value TEXT, {host} TEXT, encrypted_value BLOB)"
170 )
171 connection.execute(
172 f"INSERT INTO {table} VALUES (?, ?, ?, ?)",
173 ("auth_token", "dummy-old-cookie", ".x.com", b""),
174 )
175 connection.commit()
176 connection.execute("PRAGMA wal_checkpoint(TRUNCATE)")
177 connection.execute(f"UPDATE {table} SET value = ?", ("dummy-new-cookie",))
178 connection.commit()
179 connection.execute(f"UPDATE {table} SET value = ?", ("dummy-uncommitted-cookie",))
180 wal = database.with_name(database.name + "-wal")
181 assert wal.stat().st_size > 0
182 before_database, before_wal = database.read_bytes(), wal.read_bytes()
183
184 if browser == "firefox":
185 result = cookie_extract._query_cookies_db(database, ".x.com", ["auth_token"])
186 else:
187 result = chrome_cookies._extract_chromium_cookies_macos(
188 database, "Dummy Safe Storage", ".x.com", ["auth_token"]
189 )
190
191 assert result == {"auth_token": "dummy-new-cookie"}
192 assert database.read_bytes() == before_database
193 assert wal.read_bytes() == before_wal
194 finally:
195 connection.close()
196
197
198 @pytest.mark.parametrize("browser", ["firefox", "chrome"])
199 def test_locked_browser_snapshot_times_out_and_removes_private_copy(tmp_path, monkeypatch, browser):
200 database = tmp_path / "locked.sqlite"
201 connection = sqlite3.connect(database)
202 connection.execute("CREATE TABLE locked (value TEXT)")
203 connection.commit()
204 connection.execute("BEGIN EXCLUSIVE")
205 copies = []
206
207 def bounded_snapshot(source, destination):
208 copies.append(Path(destination))
209 sqlite_snapshot.copy_snapshot(source, destination, timeout=0.05)
210
211 module = cookie_extract if browser == "firefox" else chrome_cookies
212 monkeypatch.setattr(module, "copy_snapshot", bounded_snapshot)
213 started = time.monotonic()
214 try:
215 if browser == "firefox":
216 result = cookie_extract._query_cookies_db(database, ".x.com", ["auth_token"])
217 else:
218 result = chrome_cookies._extract_chromium_cookies_macos(
219 database, "Dummy Safe Storage", ".x.com", ["auth_token"]
220 )
221 assert result is None
222 assert time.monotonic() - started < 1
223 assert len(copies) == 1
224 assert not copies[0].exists()
225 finally:
226 connection.close()
227
228
229 def _hold_exclusive_wal_database(database, rows):
230 connection = sqlite3.connect(database)
231 connection.execute("PRAGMA locking_mode=EXCLUSIVE")
232 connection.execute("PRAGMA journal_mode=WAL")
233 connection.execute("PRAGMA wal_autocheckpoint=0")
234 connection.execute("CREATE TABLE moz_cookies (name TEXT, value TEXT, host TEXT)")
235 connection.executemany("INSERT INTO moz_cookies VALUES (?, ?, ?)", rows)
236 connection.commit()
237 return connection
238
239
240 def test_firefox_snapshot_reads_committed_wal_while_the_browser_holds_its_exclusive_lock(tmp_path):
241 database = tmp_path / "cookies.sqlite"
242 connection = _hold_exclusive_wal_database(
243 database, [("auth_token", "dummy-auth", ".x.com"), ("ct0", "dummy-ct0", ".x.com")],
244 )
245 try:
246 assert database.with_name("cookies.sqlite-wal").stat().st_size > 0
247 with pytest.raises(sqlite3.OperationalError, match="locked"):
248 sqlite3.connect(database.as_uri() + "?mode=ro", uri=True, timeout=0).execute(
249 "SELECT 1 FROM moz_cookies"
250 ).fetchone()
251 assert cookie_extract._query_cookies_db(database, ".x.com", ["auth_token", "ct0"]) == {
252 "auth_token": "dummy-auth",
253 "ct0": "dummy-ct0",
254 }
255 finally:
256 connection.close()
257
258
259 def test_firefox_snapshot_reads_a_locked_database_whose_wal_is_empty(tmp_path):
260 database = tmp_path / "cookies.sqlite"
261 connection = _hold_exclusive_wal_database(
262 database, [("auth_token", "dummy-auth", ".x.com"), ("ct0", "dummy-ct0", ".x.com")],
263 )
264 try:
265 connection.execute("PRAGMA wal_checkpoint(TRUNCATE)")
266 assert database.with_name("cookies.sqlite-wal").stat().st_size == 0
267 with pytest.raises(sqlite3.OperationalError, match="locked"):
268 sqlite3.connect(database.as_uri() + "?mode=ro", uri=True, timeout=0).execute(
269 "SELECT 1 FROM moz_cookies"
270 ).fetchone()
271 assert cookie_extract._query_cookies_db(database, ".x.com", ["auth_token", "ct0"]) == {
272 "auth_token": "dummy-auth",
273 "ct0": "dummy-ct0",
274 }
275 finally:
276 connection.close()
277
278
279 def test_exclusive_wal_snapshot_rejects_a_database_that_changes_during_the_copy(tmp_path, monkeypatch):
280 database = tmp_path / "cookies.sqlite"
281 connection = _hold_exclusive_wal_database(database, [("auth_token", "dummy-auth", ".x.com")])
282 real_fingerprint = sqlite_snapshot._fingerprint
283 reads = []
284
285 def fingerprint_then_write(source, deadline, *, copy_to=None):
286 digest = real_fingerprint(source, deadline, copy_to=copy_to)
287 reads.append(source)
288 if len(reads) == 2:
289 connection.execute("INSERT INTO moz_cookies VALUES ('ct0', 'dummy-ct0', '.x.com')")
290 connection.commit()
291 return digest
292
293 monkeypatch.setattr(sqlite_snapshot, "_fingerprint", fingerprint_then_write)
294 try:
295 with pytest.raises(sqlite3.OperationalError, match="changed during snapshot"):
296 sqlite_snapshot.copy_snapshot(database, str(tmp_path / "copy.sqlite"))
297 finally:
298 connection.close()
299
300
301 def test_snapshot_preserves_source_permission_error(tmp_path, monkeypatch):
302 database = tmp_path / "denied.sqlite"
303 real_open = Path.open
304
305 def guarded_open(path, *args, **kwargs):
306 if path == database:
307 raise PermissionError(13, "Permission denied", str(path))
308 return real_open(path, *args, **kwargs)
309
310 monkeypatch.setattr(Path, "open", guarded_open)
311 with pytest.raises(PermissionError) as error:
312 sqlite_snapshot.copy_snapshot(database, str(tmp_path / "copy.sqlite"))
313 assert error.value.filename == str(database)
314
315
316 @pytest.mark.parametrize("failure", ["missing_table", "malformed_cookie"])
317 def test_chromium_snapshot_query_failure_removes_wal_sidecars(tmp_path, monkeypatch, failure):
318 database = tmp_path / "Cookies"
319 copies = tmp_path / "private-copies"
320 copies.mkdir()
321 real_mkstemp = chrome_cookies.tempfile.mkstemp
322 monkeypatch.setattr(
323 chrome_cookies.tempfile, "mkstemp",
324 lambda **kwargs: real_mkstemp(dir=copies, **kwargs),
325 )
326 connection = sqlite3.connect(database)
327 try:
328 connection.execute("PRAGMA journal_mode=WAL")
329 connection.execute("PRAGMA wal_autocheckpoint=0")
330 if failure == "missing_table":
331 connection.execute("CREATE TABLE other (value TEXT)")
332 else:
333 connection.execute(
334 "CREATE TABLE cookies (name TEXT, value TEXT, host_key TEXT, encrypted_value BLOB)"
335 )
336 connection.execute(
337 "INSERT INTO cookies VALUES (?, ?, ?, ?)", ("auth_token", "", ".x.com", 42)
338 )
339 connection.commit()
340
341 assert chrome_cookies._extract_chromium_cookies_macos(
342 database, "Dummy Safe Storage", ".x.com", ["auth_token"]
343 ) is None
344
345 assert list(copies.iterdir()) == []
346 finally:
347 connection.close()
348
348 lines PYTHON