tests/test_audit.py
| 1 | """Tests for the wallet audit log.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import pytest |
| 6 | from quantumshield.core.keys import get_backend |
| 7 | |
| 8 | from pqc_agent_wallet import Wallet |
| 9 | from pqc_agent_wallet.errors import CredentialNotFoundError |
| 10 | |
| 11 | |
| 12 | def test_put_records_audit_entry(open_wallet: Wallet) -> None: |
| 13 | entries = open_wallet.audit.entries(operation="put") |
| 14 | names = [e.credential_name for e in entries] |
| 15 | assert "openai_api_key" in names |
| 16 | assert "postgres_password" in names |
| 17 | assert all(e.success for e in entries) |
| 18 | |
| 19 | |
| 20 | def test_get_records_audit_entry(open_wallet: Wallet) -> None: |
| 21 | open_wallet.get("openai_api_key") |
| 22 | get_entries = open_wallet.audit.entries(operation="get") |
| 23 | assert any( |
| 24 | e.credential_name == "openai_api_key" and e.success for e in get_entries |
| 25 | ) |
| 26 | |
| 27 | |
| 28 | def test_failed_get_records_failure(open_wallet: Wallet) -> None: |
| 29 | with pytest.raises(CredentialNotFoundError): |
| 30 | open_wallet.get("nonexistent") |
| 31 | failures = [e for e in open_wallet.audit.entries(operation="get") if not e.success] |
| 32 | assert any(e.credential_name == "nonexistent" for e in failures) |
| 33 | |
| 34 | |
| 35 | def test_audit_entries_signed_and_verifiable(open_wallet: Wallet) -> None: |
| 36 | if get_backend() == "stub": |
| 37 | pytest.skip("requires real signature backend") |
| 38 | |
| 39 | pk_hex = open_wallet.owner.signing_keypair.public_key.hex() |
| 40 | entries = open_wallet.audit.entries(limit=100) |
| 41 | assert entries, "expected at least one audit entry" |
| 42 | for entry in entries: |
| 43 | assert entry.signature |
| 44 | assert entry.algorithm |
| 45 | assert entry.verify_signature(pk_hex) is True |
| 46 | |
| 47 | |
| 48 | def test_audit_filter_by_operation(open_wallet: Wallet) -> None: |
| 49 | open_wallet.get("openai_api_key") |
| 50 | puts = open_wallet.audit.entries(operation="put") |
| 51 | gets = open_wallet.audit.entries(operation="get") |
| 52 | assert all(e.operation == "put" for e in puts) |
| 53 | assert all(e.operation == "get" for e in gets) |
| 54 | |
| 55 | |
| 56 | def test_audit_filter_by_credential_name(open_wallet: Wallet) -> None: |
| 57 | open_wallet.get("postgres_password") |
| 58 | filtered = open_wallet.audit.entries(credential_name="postgres_password") |
| 59 | assert filtered |
| 60 | assert all(e.credential_name == "postgres_password" for e in filtered) |
| 61 | |
| 62 | |
| 63 | def test_audit_export_json_roundtrip(open_wallet: Wallet) -> None: |
| 64 | data = open_wallet.audit.export_json() |
| 65 | assert "timestamp" in data |
| 66 | assert "put" in data |
| 67 | |
| 68 | |
| 69 | def test_audit_log_len(open_wallet: Wallet) -> None: |
| 70 | # open_wallet fixture: 2 puts produce 2 entries |
| 71 | assert len(open_wallet.audit) >= 2 |
| 72 | |