tests/test_claim.py
| 1 | """Tests for AttestationClaim and AttestationReport.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import time |
| 6 | |
| 7 | from pqc_hypervisor_attestation import ( |
| 8 | AttestationClaim, |
| 9 | AttestationReport, |
| 10 | MemoryRegion, |
| 11 | RegionSnapshot, |
| 12 | ) |
| 13 | |
| 14 | |
| 15 | def _region() -> MemoryRegion: |
| 16 | return MemoryRegion( |
| 17 | region_id="w0", |
| 18 | description="weights", |
| 19 | address=0x1000, |
| 20 | size=4, |
| 21 | protection="RO", |
| 22 | ) |
| 23 | |
| 24 | |
| 25 | def _snapshot() -> RegionSnapshot: |
| 26 | return RegionSnapshot.create("w0", b"\x00\x01\x02\x03") |
| 27 | |
| 28 | |
| 29 | def test_create_populates_ids() -> None: |
| 30 | claim = AttestationClaim.create(region=_region(), snapshot=_snapshot()) |
| 31 | assert claim.claim_id.startswith("urn:pqc-att:") |
| 32 | report = AttestationReport.create(claims=[claim]) |
| 33 | assert report.report_id.startswith("urn:pqc-attreport:") |
| 34 | assert report.issued_at |
| 35 | assert report.expires_at |
| 36 | |
| 37 | |
| 38 | def test_to_dict_from_dict_roundtrip() -> None: |
| 39 | claim = AttestationClaim.create( |
| 40 | region=_region(), |
| 41 | snapshot=_snapshot(), |
| 42 | expected_hash="abc", |
| 43 | workload_id="w", |
| 44 | platform="in-memory", |
| 45 | nonce="n", |
| 46 | ) |
| 47 | report = AttestationReport.create( |
| 48 | claims=[claim], |
| 49 | attester_id="did:example:1", |
| 50 | platform="in-memory", |
| 51 | ) |
| 52 | restored = AttestationReport.from_dict(report.to_dict()) |
| 53 | assert restored.report_id == report.report_id |
| 54 | assert len(restored.claims) == 1 |
| 55 | assert restored.claims[0].claim_id == claim.claim_id |
| 56 | assert restored.claims[0].region == claim.region |
| 57 | assert restored.claims[0].snapshot == claim.snapshot |
| 58 | assert restored.attester_id == "did:example:1" |
| 59 | |
| 60 | |
| 61 | def test_is_expired_respects_ttl() -> None: |
| 62 | claim = AttestationClaim.create(region=_region(), snapshot=_snapshot()) |
| 63 | fresh = AttestationReport.create(claims=[claim], ttl_seconds=60) |
| 64 | assert fresh.is_expired() is False |
| 65 | |
| 66 | stale = AttestationReport.create(claims=[claim], ttl_seconds=0) |
| 67 | time.sleep(0.05) |
| 68 | assert stale.is_expired() is True |
| 69 | |
| 70 | |
| 71 | def test_canonical_bytes_deterministic() -> None: |
| 72 | claim = AttestationClaim.create( |
| 73 | region=_region(), |
| 74 | snapshot=_snapshot(), |
| 75 | expected_hash="abc", |
| 76 | workload_id="w", |
| 77 | platform="in-memory", |
| 78 | nonce="n", |
| 79 | ) |
| 80 | report = AttestationReport.create(claims=[claim]) |
| 81 | a = report.canonical_bytes() |
| 82 | b = report.canonical_bytes() |
| 83 | assert a == b |
| 84 | # Ordering of keys must be stable regardless of dict insertion order |
| 85 | assert a.startswith(b'{"attester_id":') |
| 86 | |