matrix-compute-node 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,226 @@
1
+ """
2
+ Abstract base class and exception hierarchy for pluggable hardware attestation.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from abc import ABC, abstractmethod
8
+ import logging
9
+ from typing import Any, Callable, Dict, Optional, Type
10
+
11
+ from matrix_contracts.schemas.attestation import AttestationEvidence
12
+
13
+ logger = logging.getLogger("matrix_compute_node.attestation")
14
+
15
+
16
+ class AttestationError(Exception):
17
+ """Base exception for all attestation provider errors."""
18
+
19
+
20
+ class HardwareAttestationUnavailableError(AttestationError):
21
+ """Raised when the requested hardware attestation provider is unavailable."""
22
+
23
+
24
+ class AttestationGenerationError(AttestationError):
25
+ """Raised when evidence generation or signing fails."""
26
+
27
+
28
+ class AttestationValidationError(AttestationError):
29
+ """Raised when inputs (nonce, public key) are invalid."""
30
+
31
+
32
+ class BaseAttestationProvider(ABC):
33
+ """
34
+ Abstract Base Class for hardware and simulated TEE attestation providers.
35
+ Defines the standard interface for generating cryptographically signed
36
+ hardware attestation evidence bound to challenger nonces and ephemeral public keys.
37
+ """
38
+
39
+ @property
40
+ @abstractmethod
41
+ def provider_name(self) -> str:
42
+ """
43
+ Canonical provider identifier (e.g. 'nvidia-cca', 'simulated-cca', 'amd-sev-snp', 'intel-tdx').
44
+ Matches `tee_type` in matrix_contracts.
45
+ """
46
+ ...
47
+
48
+ @abstractmethod
49
+ def is_available(self) -> bool:
50
+ """
51
+ Probes the platform and driver to determine if this provider is operational.
52
+ Returns True if available, False otherwise. Must not raise unhandled exceptions.
53
+ """
54
+ ...
55
+
56
+ @abstractmethod
57
+ def generate_evidence(
58
+ self,
59
+ nonce: bytes,
60
+ public_key: bytes,
61
+ ) -> AttestationEvidence:
62
+ """
63
+ Generates cryptographically signed attestation evidence proving hardware authenticity,
64
+ measurement integrity (PCRs/Golden RIM), and cryptographic binding to the challenger nonce
65
+ and ephemeral public key.
66
+
67
+ Args:
68
+ nonce: 32-byte challenger freshness nonce.
69
+ public_key: 32-byte ephemeral public key (e.g. X25519) to bind to the attestation.
70
+
71
+ Returns:
72
+ AttestationEvidence: Validated Pydantic container with certificate chain,
73
+ token claims, signature, Golden RIM, and optional evidence blob.
74
+
75
+ Raises:
76
+ AttestationValidationError: If nonce or public_key are invalid (not 32 bytes).
77
+ HardwareAttestationUnavailableError: If underlying hardware is unavailable.
78
+ AttestationGenerationError: If evidence generation fails.
79
+ """
80
+ ...
81
+
82
+ def get_measurements(self) -> Dict[str, str]:
83
+ """Returns a dictionary of current hardware/enclave measurements or PCR digests."""
84
+ return {}
85
+
86
+
87
+ # Provider Registry
88
+ _PROVIDER_REGISTRY: Dict[str, Type[BaseAttestationProvider]] = {}
89
+
90
+
91
+ def register_attestation_provider(
92
+ name: str,
93
+ ) -> Callable[[Type[BaseAttestationProvider]], Type[BaseAttestationProvider]]:
94
+ """Decorator to register an attestation provider class."""
95
+
96
+ def decorator(cls: Type[BaseAttestationProvider]) -> Type[BaseAttestationProvider]:
97
+ _PROVIDER_REGISTRY[name.lower().strip()] = cls
98
+ return cls
99
+
100
+ return decorator
101
+
102
+
103
+ def get_attestation_provider(
104
+ provider_type: Optional[str] = "auto",
105
+ device_index: int = 0,
106
+ fallback_to_simulated: bool = True,
107
+ **kwargs: Any,
108
+ ) -> BaseAttestationProvider:
109
+ """
110
+ Factory function resolving and instantiating the requested attestation provider.
111
+
112
+ Args:
113
+ provider_type: 'auto', 'nvidia-cca', 'simulated-cca', or registered provider name.
114
+ device_index: Target GPU index for hardware providers.
115
+ fallback_to_simulated: If True, falls back to SimulatedAttestationProvider when
116
+ hardware provider is unavailable.
117
+ **kwargs: Provider-specific configuration options.
118
+
119
+ Returns:
120
+ BaseAttestationProvider instance.
121
+ """
122
+ norm_type = (provider_type or "auto").strip().lower()
123
+
124
+ if norm_type == "auto":
125
+ from src.attestation.nvml_attest import NvidiaCcaProvider
126
+
127
+ cca_provider = NvidiaCcaProvider(device_index=device_index, **kwargs)
128
+ if cca_provider.is_available():
129
+ logger.info(
130
+ "Using hardware attestation provider: nvidia-cca (device %d)", device_index
131
+ )
132
+ return cca_provider
133
+
134
+ try:
135
+ from src.attestation.sev_snp_attest import AmdSevSnpProvider
136
+
137
+ snp_provider = AmdSevSnpProvider(device_index=device_index, **kwargs)
138
+ if snp_provider.is_available():
139
+ logger.info("Using hardware attestation provider: amd-sev-snp")
140
+ return snp_provider
141
+ except Exception as exc:
142
+ logger.debug("Auto probe for amd-sev-snp failed: %s", exc)
143
+
144
+ try:
145
+ from src.attestation.tdx_attest import IntelTdxProvider
146
+
147
+ tdx_provider = IntelTdxProvider(device_index=device_index, **kwargs)
148
+ if tdx_provider.is_available():
149
+ logger.info("Using hardware attestation provider: intel-tdx")
150
+ return tdx_provider
151
+ except Exception as exc:
152
+ logger.debug("Auto probe for intel-tdx failed: %s", exc)
153
+
154
+ if not fallback_to_simulated:
155
+ raise HardwareAttestationUnavailableError(
156
+ "No hardware TEE provider is operational (hardware attestation unavailable and fallback_to_simulated=False)."
157
+ )
158
+
159
+ logger.info("Hardware TEE unavailable; falling back to simulated-cca provider.")
160
+ from src.attestation.simulated import SimulatedAttestationProvider
161
+
162
+ return SimulatedAttestationProvider(**kwargs)
163
+
164
+ if norm_type in ("nvidia-cca", "nvidia"):
165
+ from src.attestation.nvml_attest import NvidiaCcaProvider
166
+
167
+ cca_provider = NvidiaCcaProvider(device_index=device_index, **kwargs)
168
+ if cca_provider.is_available():
169
+ logger.info(
170
+ "Using hardware attestation provider: nvidia-cca (device %d)", device_index
171
+ )
172
+ return cca_provider
173
+
174
+ if not fallback_to_simulated:
175
+ raise HardwareAttestationUnavailableError(
176
+ f"NVIDIA CCA requested on device {device_index}, but hardware or CC mode is unavailable."
177
+ )
178
+
179
+ logger.info("Hardware CCA unavailable; falling back to simulated-cca provider.")
180
+ from src.attestation.simulated import SimulatedAttestationProvider
181
+
182
+ return SimulatedAttestationProvider(**kwargs)
183
+
184
+ if norm_type in ("amd-sev-snp", "amd", "sev-snp"):
185
+ from src.attestation.sev_snp_attest import AmdSevSnpProvider
186
+
187
+ snp_provider = AmdSevSnpProvider(device_index=device_index, **kwargs)
188
+ if snp_provider.is_available():
189
+ logger.info("Using hardware attestation provider: amd-sev-snp")
190
+ return snp_provider
191
+
192
+ if not fallback_to_simulated:
193
+ raise HardwareAttestationUnavailableError(
194
+ "AMD SEV-SNP requested, but /dev/sev-guest hardware is unavailable."
195
+ )
196
+
197
+ logger.info("Hardware AMD SEV-SNP unavailable; falling back to simulated SEV-SNP provider.")
198
+ return AmdSevSnpProvider(device_index=device_index, simulate=True, **kwargs)
199
+
200
+ if norm_type in ("intel-tdx", "tdx", "intel"):
201
+ from src.attestation.tdx_attest import IntelTdxProvider
202
+
203
+ tdx_provider = IntelTdxProvider(device_index=device_index, **kwargs)
204
+ if tdx_provider.is_available():
205
+ logger.info("Using hardware attestation provider: intel-tdx")
206
+ return tdx_provider
207
+
208
+ if not fallback_to_simulated:
209
+ raise HardwareAttestationUnavailableError(
210
+ "Intel TDX requested, but /dev/tdx_guest hardware is unavailable."
211
+ )
212
+
213
+ logger.info("Hardware Intel TDX unavailable; falling back to simulated TDX provider.")
214
+ return IntelTdxProvider(device_index=device_index, simulate=True, **kwargs)
215
+
216
+ if norm_type in ("simulated-cca", "simulated", "mock"):
217
+ from src.attestation.simulated import SimulatedAttestationProvider
218
+
219
+ return SimulatedAttestationProvider(**kwargs)
220
+
221
+ if norm_type in _PROVIDER_REGISTRY:
222
+ cls = _PROVIDER_REGISTRY[norm_type]
223
+ return cls(device_index=device_index, **kwargs)
224
+
225
+ raise ValueError(f"Unknown attestation provider type: '{provider_type}'")
226
+