import sys import pytest from app.vault import DpapiCipher, Vault, VaultError from tests.conftest import FakeCipher def test_vault_roundtrip_with_fake_cipher(tmp_path): vault = Vault(tmp_path / "vault.bin", cipher=FakeCipher()) assert vault.get("token:x") is None vault.set("token:x", {"accessToken": "segredo-123", "refreshToken": "r1"}) vault.update("token:x", refreshToken="r2") assert vault.get("token:x") == {"accessToken": "segredo-123", "refreshToken": "r2"} assert b"segredo-123" not in (tmp_path / "vault.bin").read_bytes() reopened = Vault(tmp_path / "vault.bin", cipher=FakeCipher()) assert reopened.get("token:x")["refreshToken"] == "r2" reopened.delete("token:x") assert reopened.keys() == [] def test_vault_refuses_garbage(tmp_path): (tmp_path / "vault.bin").write_bytes(b"FAKE{nao-e-json") with pytest.raises(VaultError): Vault(tmp_path / "vault.bin", cipher=FakeCipher()).get("x") @pytest.mark.skipif(sys.platform != "win32", reason="DPAPI só existe no Windows") def test_real_dpapi_roundtrip(tmp_path): cipher = DpapiCipher() blob = cipher.protect(b"token-de-verdade") assert b"token-de-verdade" not in blob assert cipher.unprotect(blob) == b"token-de-verdade" vault = Vault(tmp_path / "vault.bin") # cifrador real (padrão) vault.set("app:youtube", {"clientSecret": "abc"}) assert Vault(tmp_path / "vault.bin").get("app:youtube") == {"clientSecret": "abc"} with pytest.raises(VaultError): cipher.unprotect(b"\x01\x02\x03 nao e dpapi")