返回 last30days-skill
test_env_keychain.py
根目录 / tests / test_env_keychain.py
1 """Tests for macOS Keychain credential source in lib/env.py.
2
3 Covers:
4 - non-Darwin returns {}
5 - missing `security` binary returns {}
6 - successful lookups return parsed key/value pairs
7 - subprocess timeout / OSError are swallowed
8 - get_config merges keychain at lowest priority and labels _CONFIG_SOURCE
9 """
10
11 from __future__ import annotations
12
13 import os
14 import re
15 import shlex
16 import subprocess
17 from pathlib import Path
18 from unittest import mock
19
20 import pytest
21
22 from lib import env
23
24 SETUP_KEYCHAIN_SH = Path(__file__).resolve().parents[1] / "skills" / "last30days" / "scripts" / "setup-keychain.sh"
25
26
27 def _plaintext_presence_checks(script: str) -> list[str]:
28 # Join shell continuations before tokenizing so a split -w cannot hide.
29 logical = re.sub(r"\\\r?\n", " ", script)
30 offenders = []
31 for line in logical.splitlines():
32 code = " ".join(shlex.split(line, comments=True))
33 if re.search(r"find-generic-password\b.*\s-[wg](?=\s|[;>|&]|$)", code):
34 offenders.append(line)
35 return offenders
36
37
38 def test_setup_presence_checks_do_not_request_plaintext():
39 assert not _plaintext_presence_checks(SETUP_KEYCHAIN_SH.read_text(encoding="utf-8"))
40
41
42 def test_presence_guard_detects_multiline_password_flags():
43 script = (
44 "security find-generic-password \\\n"
45 ' -a "$USER" \\\n'
46 " -w >/dev/null"
47 )
48 assert _plaintext_presence_checks(script)
49 assert not _plaintext_presence_checks('# security find-generic-password -w\n')
50
51
52 @pytest.mark.parametrize("existed,replace,value,summary", [
53 (True, False, "", "added=0 replaced=0 skipped=1"),
54 (False, False, "DUMMY-VALUE\n", "added=1 replaced=0 skipped=0"),
55 (True, True, "DUMMY-VALUE\n", "added=0 replaced=1 skipped=0"),
56 ])
57 @pytest.mark.skipif(
58 os.name == "nt" or Path("/usr/bin/security").exists(),
59 reason="POSIX non-macOS shell fixture (macOS pins /usr/bin/security unconditionally)",
60 )
61 def test_setup_presence_and_counters_use_stub_security(tmp_path, existed, replace, value, summary):
62 stub = tmp_path / "security"
63 stub.write_text(
64 '#!/bin/sh\n'
65 'case "$1" in\n'
66 ' find-generic-password)\n'
67 ' printf "%s\\n" "$1" >> "$STUB_LOG"\n'
68 ' exit "$STUB_STATUS"\n'
69 ' ;;\n'
70 ' -i)\n'
71 ' IFS= read -r line || exit 98\n'
72 ' cmd="${line%% *}"\n'
73 ' printf "%s\\n" "$cmd" >> "$STUB_LOG"\n'
74 ' exit 0\n'
75 ' ;;\n'
76 ' *)\n'
77 ' printf "%s\\n" "$1" >> "$STUB_LOG"\n'
78 ' exit 99\n'
79 ' ;;\n'
80 'esac\n', encoding="utf-8",
81 )
82 stub.chmod(0o755)
83 log_path = tmp_path / "calls"
84 command = ["/bin/bash", str(SETUP_KEYCHAIN_SH)]
85 if replace:
86 command.append("--replace")
87 command.append("OPENAI_API_KEY")
88 result = subprocess.run(
89 command, input=value, text=True, capture_output=True, timeout=5,
90 env={"PATH": str(tmp_path), "LAST30DAYS_TEST_SECURITY_BIN": str(stub),
91 "USER": "fixture-user", "OSTYPE": "darwin",
92 "STUB_LOG": str(log_path), "STUB_STATUS": "0" if existed else "44"},
93 )
94 assert result.returncode == 0, result.stderr
95 assert summary in result.stdout
96 assert "DUMMY-VALUE" not in result.stdout + result.stderr
97 calls = log_path.read_text().splitlines()
98 assert calls == ["find-generic-password"] + ([] if existed and not replace else ["add-generic-password"])
99
100 # ---------------------------------------------------------------------------
101 # _load_keychain unit tests
102 # ---------------------------------------------------------------------------
103
104
105 def test_load_keychain_returns_empty_on_non_darwin():
106 with mock.patch("platform.system", return_value="Linux"):
107 assert env._load_keychain(["XAI_API_KEY"]) == {}
108
109
110 def test_load_keychain_returns_empty_when_security_missing():
111 with mock.patch("platform.system", return_value="Darwin"), \
112 mock.patch("shutil.which", return_value=None):
113 assert env._load_keychain(["XAI_API_KEY"]) == {}
114
115
116 def _run_result(returncode: int, stdout: str = "") -> subprocess.CompletedProcess:
117 return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr="")
118
119
120 def test_load_keychain_returns_empty_when_disable_switch_set(monkeypatch):
121 """The opt-out must win on Darwin with `security` present and a key stored.
122
123 Deliberately mocked past the platform/binary early-returns above: if the
124 switch were dropped, neither of those would cover this case and this goes red.
125 """
126 monkeypatch.setenv(env.KEYCHAIN_DISABLE_ENV, "1")
127 with mock.patch("platform.system", return_value="Darwin"), \
128 mock.patch("shutil.which", return_value="/usr/bin/security"), \
129 mock.patch("subprocess.run", return_value=_run_result(0, "should-not-be-read")) as run:
130 assert env._load_keychain(["XAI_API_KEY"]) == {}
131 # Proves the opt-out short-circuits BEFORE any lookup, not merely that the
132 # returned dict came back empty.
133 run.assert_not_called()
134
135
136 def test_load_keychain_reads_key_when_disable_switch_absent(monkeypatch):
137 """Counterexample for the test above: same mocks, switch off -> the key IS read.
138
139 Without this pair, `_load_keychain(...) == {}` could pass for the wrong
140 reason and nobody would notice.
141 """
142 monkeypatch.delenv(env.KEYCHAIN_DISABLE_ENV, raising=False)
143 with mock.patch("platform.system", return_value="Darwin"), \
144 mock.patch("shutil.which", return_value="/usr/bin/security"), \
145 mock.patch("subprocess.run", return_value=_run_result(0, "xai-secret")):
146 assert env._load_keychain(["XAI_API_KEY"]) == {"XAI_API_KEY": "xai-secret"}
147
148
149 def test_load_keychain_disable_switch_ignores_falsy_values(monkeypatch):
150 """`LAST30DAYS_SKIP_KEYCHAIN=0` / empty must NOT disable the source."""
151 for falsy in ("0", "", "false", "no"):
152 monkeypatch.setenv(env.KEYCHAIN_DISABLE_ENV, falsy)
153 with mock.patch("platform.system", return_value="Darwin"), \
154 mock.patch("shutil.which", return_value="/usr/bin/security"), \
155 mock.patch("subprocess.run", return_value=_run_result(0, "xai-secret")):
156 assert env._load_keychain(["XAI_API_KEY"]) == {"XAI_API_KEY": "xai-secret"}, falsy
157
158
159 def test_parse_keychain_aliases_accepts_string_and_object_forms():
160 raw = (
161 '{"XAI_API_KEY":"existing-xai-api-key",'
162 '"BRAVE_API_KEY":{"account":"keychain-user","service":"existing-brave-api-key"}}'
163 )
164 assert env._parse_keychain_aliases(raw) == {
165 "XAI_API_KEY": [{"service": "existing-xai-api-key", "account": ""}],
166 "BRAVE_API_KEY": [{"service": "existing-brave-api-key", "account": "keychain-user"}],
167 }
168
169
170 def test_parse_keychain_aliases_accepts_ordered_fallback_list():
171 raw = '{"XAI_API_KEY":[{"service":"primary-xai"},{"account":"keychain-user","service":"fallback-xai"}]}'
172 assert env._parse_keychain_aliases(raw) == {
173 "XAI_API_KEY": [
174 {"service": "primary-xai", "account": ""},
175 {"service": "fallback-xai", "account": "keychain-user"},
176 ],
177 }
178
179
180 def test_parse_keychain_aliases_warns_on_invalid_json_and_ignores_unknown_keys(capsys):
181 assert env._parse_keychain_aliases("not json") == {}
182 warning = capsys.readouterr().err
183 assert "LAST30DAYS_KEYCHAIN_ALIASES is not valid JSON" in warning
184 assert "canonical lookups enabled" in warning
185
186 assert env._parse_keychain_aliases('{"NOT_A_KEY":"secret-service"}') == {}
187 assert capsys.readouterr().err == ""
188
189
190 def test_load_keychain_loads_present_keys_skips_missing():
191 def fake_run(cmd, **kwargs):
192 service = cmd[cmd.index("-s") + 1]
193 if service == "last30days-XAI_API_KEY":
194 return _run_result(0, "xai-abc\n")
195 if service == "last30days-BRAVE_API_KEY":
196 return _run_result(0, "brv-xyz\n")
197 return _run_result(44) # security's "not found" exit code
198
199 with mock.patch("platform.system", return_value="Darwin"), \
200 mock.patch("shutil.which", return_value="/usr/bin/security"), \
201 mock.patch("subprocess.run", side_effect=fake_run):
202 result = env._load_keychain(["XAI_API_KEY", "BRAVE_API_KEY", "OPENAI_API_KEY"])
203
204 assert result == {"XAI_API_KEY": "xai-abc", "BRAVE_API_KEY": "brv-xyz"}
205
206
207 def test_load_keychain_uses_alias_when_canonical_missing():
208 calls = []
209
210 def fake_run(cmd, **kwargs):
211 account = cmd[cmd.index("-a") + 1]
212 service = cmd[cmd.index("-s") + 1]
213 calls.append((account, service))
214 if account == "keychain-user" and service == "existing-xai-api-key":
215 return _run_result(0, "xai-alias\n")
216 return _run_result(44)
217
218 aliases = {"XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}]}
219 with mock.patch("platform.system", return_value="Darwin"), \
220 mock.patch("shutil.which", return_value="/usr/bin/security"), \
221 mock.patch.dict("os.environ", {"USER": "mortimer"}, clear=False), \
222 mock.patch("subprocess.run", side_effect=fake_run):
223 result = env._load_keychain(["XAI_API_KEY"], aliases)
224
225 assert result == {"XAI_API_KEY": "xai-alias"}
226 assert calls == [
227 ("mortimer", "last30days-XAI_API_KEY"),
228 ("keychain-user", "existing-xai-api-key"),
229 ]
230
231
232 def test_load_keychain_canonical_wins_over_alias():
233 def fake_run(cmd, **kwargs):
234 service = cmd[cmd.index("-s") + 1]
235 if service == "last30days-XAI_API_KEY":
236 return _run_result(0, "xai-canonical\n")
237 if service == "existing-xai-api-key":
238 return _run_result(0, "xai-alias\n")
239 return _run_result(44)
240
241 aliases = {"XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}]}
242 with mock.patch("platform.system", return_value="Darwin"), \
243 mock.patch("shutil.which", return_value="/usr/bin/security"), \
244 mock.patch("subprocess.run", side_effect=fake_run):
245 result = env._load_keychain(["XAI_API_KEY"], aliases)
246
247 assert result == {"XAI_API_KEY": "xai-canonical"}
248
249
250 def test_load_keychain_strips_whitespace_and_newlines():
251 with mock.patch("platform.system", return_value="Darwin"), \
252 mock.patch("shutil.which", return_value="/usr/bin/security"), \
253 mock.patch("subprocess.run", return_value=_run_result(0, " hello-key \n")):
254 result = env._load_keychain(["FOO"])
255 assert result == {"FOO": "hello-key"}
256
257
258 def test_load_keychain_swallows_subprocess_errors():
259 def fake_run(cmd, **kwargs):
260 raise subprocess.TimeoutExpired(cmd=cmd, timeout=5)
261
262 with mock.patch("platform.system", return_value="Darwin"), \
263 mock.patch("shutil.which", return_value="/usr/bin/security"), \
264 mock.patch("subprocess.run", side_effect=fake_run):
265 assert env._load_keychain(["XAI_API_KEY"]) == {}
266
267
268 def test_load_keychain_swallows_oserror():
269 with mock.patch("platform.system", return_value="Darwin"), \
270 mock.patch("shutil.which", return_value="/usr/bin/security"), \
271 mock.patch("subprocess.run", side_effect=OSError("boom")):
272 assert env._load_keychain(["XAI_API_KEY"]) == {}
273
274
275 def test_load_keychain_skips_empty_stdout():
276 with mock.patch("platform.system", return_value="Darwin"), \
277 mock.patch("shutil.which", return_value="/usr/bin/security"), \
278 mock.patch("subprocess.run", return_value=_run_result(0, "")):
279 assert env._load_keychain(["XAI_API_KEY"]) == {}
280
281 # ---------------------------------------------------------------------------
282 # get_config integration tests
283 # ---------------------------------------------------------------------------
284
285 @pytest.fixture
286 def clean_env(monkeypatch, tmp_path):
287 """Hide every key get_config might touch and point CONFIG_FILE at a
288 non-existent path so no real user config bleeds in."""
289 for var in [
290 "OPENAI_API_KEY", "XAI_API_KEY", "BRAVE_API_KEY", "AUTH_TOKEN", "CT0",
291 "SCRAPECREATORS_API_KEY", "APIFY_API_TOKEN", "BSKY_HANDLE",
292 "BSKY_APP_PASSWORD", "TRUTHSOCIAL_TOKEN", "EXA_API_KEY",
293 "SERPER_API_KEY", "OPENROUTER_API_KEY", "PERPLEXITY_API_KEY", "PARALLEL_API_KEY",
294 "XQUIK_API_KEY", "DEEPLINE_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY",
295 "GOOGLE_GENAI_API_KEY", "INCLUDE_SOURCES", "FROM_BROWSER",
296 ]:
297 monkeypatch.delenv(var, raising=False)
298 monkeypatch.setattr(env, "CONFIG_FILE", tmp_path / "does-not-exist.env")
299 monkeypatch.chdir(tmp_path) # no project .env in this tree either
300 # Neutralize the pass(1) source so these tests don't pick up a real pass
301 # store on the host running them (tests that exercise pass override this).
302 monkeypatch.setattr(env, "_load_pass", lambda *a, **k: {})
303
304
305 def test_get_config_reports_keychain_source(clean_env):
306 with mock.patch.object(env, "_load_keychain", return_value={"XAI_API_KEY": "xai-from-kc"}):
307 cfg = env.get_config()
308 assert cfg["_CONFIG_SOURCE"] == "keychain"
309 assert cfg["XAI_API_KEY"] == "xai-from-kc"
310
311
312 def test_get_config_env_var_overrides_keychain(clean_env, monkeypatch):
313 monkeypatch.setenv("XAI_API_KEY", "xai-from-env")
314 with mock.patch.object(env, "_load_keychain", return_value={"XAI_API_KEY": "xai-from-kc"}):
315 cfg = env.get_config()
316 assert cfg["XAI_API_KEY"] == "xai-from-env"
317
318
319 def test_get_config_reports_env_only_when_keychain_empty(clean_env):
320 with mock.patch.object(env, "_load_keychain", return_value={}):
321 cfg = env.get_config()
322 assert cfg["_CONFIG_SOURCE"] == "env_only"
323
324
325 def test_get_config_global_file_outranks_keychain(clean_env, tmp_path, monkeypatch):
326 cfg_file = tmp_path / "global.env"
327 cfg_file.write_text("XAI_API_KEY=xai-from-file\n")
328 monkeypatch.setattr(env, "CONFIG_FILE", cfg_file)
329 with mock.patch.object(env, "_load_keychain", return_value={"XAI_API_KEY": "xai-from-kc"}):
330 cfg = env.get_config()
331 assert cfg["XAI_API_KEY"] == "xai-from-file"
332 assert cfg["_CONFIG_SOURCE"].startswith("global:")
333
334
335 def test_get_config_passes_aliases_from_global_file(clean_env, tmp_path, monkeypatch):
336 cfg_file = tmp_path / "global.env"
337 cfg_file.write_text(
338 'LAST30DAYS_KEYCHAIN_ALIASES={"XAI_API_KEY":{"account":"keychain-user","service":"existing-xai-api-key"}}\n'
339 )
340 monkeypatch.setattr(env, "CONFIG_FILE", cfg_file)
341
342 def fake_load_keychain(keys, aliases=None):
343 assert aliases == {
344 "XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}],
345 }
346 return {"XAI_API_KEY": "xai-from-alias"}
347
348 with mock.patch.object(env, "_load_keychain", side_effect=fake_load_keychain):
349 cfg = env.get_config()
350
351 assert cfg["XAI_API_KEY"] == "xai-from-alias"
352 assert cfg["LAST30DAYS_KEYCHAIN_ALIASES"].startswith('{"XAI_API_KEY"')
353
354
355 def test_get_config_passes_aliases_from_process_env(clean_env, monkeypatch):
356 monkeypatch.setenv(
357 "LAST30DAYS_KEYCHAIN_ALIASES",
358 '{"XAI_API_KEY":{"account":"keychain-user","service":"existing-xai-api-key"}}',
359 )
360
361 def fake_load_keychain(keys, aliases=None):
362 assert aliases == {
363 "XAI_API_KEY": [{"account": "keychain-user", "service": "existing-xai-api-key"}],
364 }
365 return {"XAI_API_KEY": "xai-from-env-alias"}
366
367 with mock.patch.object(env, "_load_keychain", side_effect=fake_load_keychain):
368 cfg = env.get_config()
369
370 assert cfg["XAI_API_KEY"] == "xai-from-env-alias"
371 assert cfg["LAST30DAYS_KEYCHAIN_ALIASES"].startswith('{"XAI_API_KEY"')
372
373
374 def test_get_config_openai_key_can_come_from_keychain(clean_env):
375 """OPENAI_API_KEY must be visible to get_openai_auth via the keychain
376 merge — wiring regression test."""
377 with mock.patch.object(env, "_load_keychain", return_value={"OPENAI_API_KEY": "sk-from-kc"}):
378 cfg = env.get_config()
379 assert cfg["OPENAI_API_KEY"] == "sk-from-kc"
380 assert cfg["OPENAI_AUTH_SOURCE"] == "api_key"
381
382 # ---------------------------------------------------------------------------
383 # Drift guard: lib/env.py KEYCHAIN_KEYS and setup-keychain.sh ALL_KEYS must
384 # stay in lockstep. A mismatch means users storing a key via the helper script
385 # wouldn't see it picked up by the loader, or vice versa.
386 # ---------------------------------------------------------------------------
387
388
389 def _parse_all_keys_from_shell(script: Path) -> list[str]:
390 text = script.read_text(encoding="utf-8")
391 match = re.search(r"ALL_KEYS=\(\s*(.*?)\s*\)", text, re.DOTALL)
392 if not match:
393 raise AssertionError(f"ALL_KEYS=( ... ) array not found in {script}")
394 body = match.group(1)
395 # Strip shell comments and split on whitespace
396 body = re.sub(r"#[^\n]*", "", body)
397 return [tok for tok in body.split() if tok]
398
399
400 def test_keychain_keys_match_setup_script():
401 shell_keys = _parse_all_keys_from_shell(SETUP_KEYCHAIN_SH)
402 python_keys = list(env.KEYCHAIN_KEYS)
403 assert shell_keys == python_keys, (
404 "lib/env.py::KEYCHAIN_KEYS and scripts/setup-keychain.sh::ALL_KEYS "
405 f"have drifted.\n python: {python_keys}\n shell: {shell_keys}"
406 )
407
408
409 def test_x_bearer_token_is_a_keychain_key():
410 """U6/R17: the X API bearer is loadable from the Keychain and listed by
411 the setup-keychain.sh helper (parity is enforced above)."""
412 assert "X_BEARER_TOKEN" in env.KEYCHAIN_KEYS
413 assert _parse_all_keys_from_shell(SETUP_KEYCHAIN_SH).count("X_BEARER_TOKEN") == 1
414
415
416 def test_get_config_deepline_key_can_come_from_keychain(clean_env):
417 with mock.patch.object(env, "_load_keychain", return_value={"DEEPLINE_API_KEY": "dl-from-kc"}):
418 cfg = env.get_config()
419 assert cfg["DEEPLINE_API_KEY"] == "dl-from-kc"
420
420 lines PYTHON