"""Private profile credentials must not leak into preferences or other profiles.""" from __future__ import annotations import os from pathlib import Path import pytest from voice_dictation.infrastructure.credentials import read_api_key, save_api_key def test_key_roundtrip_private_and_isolated(tmp_path: Path) -> None: beta = tmp_path / "beta" save_api_key(beta, "test-key-not-real") assert read_api_key(beta) == "test-key-not-real" assert read_api_key(tmp_path / "main") == "" if os.name == "posix": assert (beta / "credentials.json").stat().st_mode & 0o777 == 0o600 save_api_key(beta, "replacement-not-real") assert read_api_key(beta) == "replacement-not-real" assert not list(beta.glob(".credentials-*")) def test_invalid_key_preserves_previous(tmp_path: Path) -> None: save_api_key(tmp_path, "test-key-not-real") with pytest.raises(ValueError): save_api_key(tmp_path, "bad key") assert read_api_key(tmp_path) == "test-key-not-real" def test_invalid_file_does_not_crash(tmp_path: Path) -> None: (tmp_path / "credentials.json").write_text("[]") assert read_api_key(tmp_path) == "" @pytest.mark.parametrize( "value", [ " sk-test-not-real ", '"sk-test-not-real"', "OPENAI_API_KEY=sk-test-not-real", 'OPENAI_API_KEY = "sk-test-not-real"', "export OPENAI_API_KEY=sk-test-not-real", ], ) def test_paste_from_dotenv(tmp_path: Path, value: str) -> None: save_api_key(tmp_path, value) assert read_api_key(tmp_path) == "sk-test-not-real" def test_multiple_env_values_rejected(tmp_path: Path) -> None: with pytest.raises(ValueError): save_api_key(tmp_path, "OPENAI_API_KEY=sk-test\nOTHER_KEY=test") assert not (tmp_path / "credentials.json").exists() @pytest.mark.parametrize( "value", [ "OPENAI_API_KEY\t=sk-test-not-real", "export OPENAI_API_KEY = sk-test-not-real", "sk-test-\nnot-real", "“sk-test-not-real”", "sk-test-\u200bnot-real", ], ) def test_copy_formatting_is_normalized(tmp_path: Path, value: str) -> None: save_api_key(tmp_path, value) assert read_api_key(tmp_path) == "sk-test-not-real"