Skip to main content

phytrace_sdk/core/
attestation.rs

1//! Device attestation for provenance (issue #453, Rust side of #393).
2//!
3//! Each signed event's provenance block carries a `device_attestation`
4//! entry from an [`AttestationProvider`]:
5//!
6//! * With a TPM signer, [`Attestor`] (feature `http`) keeps a current TPM2
7//!   quote registered with PhyCloud: it fetches a nonce
8//!   (`POST /api/v1/attestation/nonce`), has the TPM quote its PCRs over it
9//!   with the attestation key, submits the quote
10//!   (`POST /api/v1/attestation/quotes`), and events reference the result:
11//!   `{"mode": "tpm", "quote_id": "...", "quote_status": "verified"}`.
12//!   Quotes are refreshed once per interval, not per event.
13//! * Without a TPM, [`SoftwareAttestation`] marks the block
14//!   `{"mode": "software", "warning": "no hardware root of trust"}`, so a
15//!   software agent is never mistaken for an attested one.
16//!
17//! The blocks are identical to the Python SDK's.
18
19use serde_json::{json, Value};
20
21/// Supplies the `device_attestation` block for the next event.
22pub trait AttestationProvider: Send + Sync {
23    /// The block to put in the next event's `provenance.device_attestation`.
24    fn current(&self) -> Value;
25}
26
27/// The attestation block of an agent without a TPM.
28pub fn software_attestation() -> Value {
29    json!({"mode": "software", "warning": "no hardware root of trust"})
30}
31
32/// [`AttestationProvider`] for agents without a TPM.
33#[derive(Debug, Clone, Copy, Default)]
34pub struct SoftwareAttestation;
35
36impl AttestationProvider for SoftwareAttestation {
37    fn current(&self) -> Value {
38        software_attestation()
39    }
40}
41
42/// `<endpoint>/api/v1`, accepting an endpoint that already ends in
43/// `/api/v1`.
44#[cfg(any(feature = "http", test))]
45pub(crate) fn api_base(endpoint: &str) -> String {
46    let base = endpoint.trim_end_matches('/');
47    let base = base.strip_suffix("/api/v1").unwrap_or(base);
48    format!("{base}/api/v1")
49}
50
51#[cfg(feature = "http")]
52pub use http::Attestor;
53
54#[cfg(feature = "http")]
55mod http {
56    use std::sync::{Arc, RwLock};
57    use std::time::{Duration, Instant};
58
59    use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
60    use serde_json::{json, Value};
61
62    use super::{api_base, AttestationProvider};
63    use crate::core::signer::Signer;
64    use crate::error::{PhyTraceError, PhyTraceResult};
65
66    /// Keeps a current TPM quote registered with PhyCloud.
67    pub struct Attestor {
68        signer: Arc<dyn Signer>,
69        client: reqwest::Client,
70        base_url: String,
71        api_key: Option<String>,
72        source_id: String,
73        interval: Duration,
74        pcrs: String,
75        current: RwLock<Value>,
76        last_attempt: RwLock<Option<Instant>>,
77    }
78
79    impl std::fmt::Debug for Attestor {
80        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81            f.debug_struct("Attestor")
82                .field("source_id", &self.source_id)
83                .field("interval", &self.interval)
84                .finish_non_exhaustive()
85        }
86    }
87
88    impl Attestor {
89        /// `signer` must be able to quote (a TPM signer); `api_key` is the
90        /// device's key with `events:write`.
91        pub fn new(
92            signer: Arc<dyn Signer>,
93            endpoint: &str,
94            api_key: Option<String>,
95            source_id: impl Into<String>,
96            interval: Duration,
97            pcrs: impl Into<String>,
98        ) -> Self {
99            Self {
100                signer,
101                client: reqwest::Client::new(),
102                base_url: api_base(endpoint),
103                api_key,
104                source_id: source_id.into(),
105                interval,
106                pcrs: pcrs.into(),
107                current: RwLock::new(json!({
108                    "mode": "tpm",
109                    "quote_id": null,
110                    "error": "no quote yet",
111                })),
112                last_attempt: RwLock::new(None),
113            }
114        }
115
116        /// Quote now and register the quote.  A failure is recorded in the
117        /// block (keeping the previous `quote_id`) rather than returned, so
118        /// telemetry keeps flowing.
119        pub async fn refresh(&self) -> Value {
120            if let Ok(mut last) = self.last_attempt.write() {
121                *last = Some(Instant::now());
122            }
123            let block = match self.try_refresh().await {
124                Ok(block) => block,
125                Err(e) => {
126                    tracing::warn!("TPM attestation failed: {e}");
127                    let previous = self.current().get("quote_id").cloned();
128                    json!({"mode": "tpm", "quote_id": previous, "error": e.to_string()})
129                }
130            };
131            if let Ok(mut current) = self.current.write() {
132                *current = block.clone();
133            }
134            block
135        }
136
137        async fn try_refresh(&self) -> PhyTraceResult<Value> {
138            let nonce_reply = self
139                .post("attestation/nonce", json!({"source_id": self.source_id}))
140                .await?;
141            let nonce = nonce_reply
142                .get("nonce")
143                .and_then(Value::as_str)
144                .ok_or_else(|| PhyTraceError::Provenance("nonce missing".to_string()))?
145                .to_string();
146            let nonce_bytes = hex_decode(&nonce)
147                .ok_or_else(|| PhyTraceError::Provenance("nonce is not hex".to_string()))?;
148            let quote = self
149                .signer
150                .quote(&nonce_bytes, &self.pcrs)
151                .ok_or_else(|| PhyTraceError::Provenance("signer cannot quote".to_string()))??;
152            let stored = self
153                .post(
154                    "attestation/quotes",
155                    json!({
156                        "source_id": self.source_id,
157                        "nonce": nonce,
158                        "attest": BASE64.encode(&quote.attest),
159                        "signature": quote.signature,
160                        "pcr_selection": quote.pcr_selection,
161                    }),
162                )
163                .await?;
164            Ok(json!({
165                "mode": "tpm",
166                "quote_id": stored.get("quote_id").cloned().unwrap_or(Value::Null),
167                "quote_status": stored.get("status").cloned().unwrap_or(Value::Null),
168            }))
169        }
170
171        async fn post(&self, path: &str, body: Value) -> PhyTraceResult<Value> {
172            let mut request = self
173                .client
174                .post(format!("{}/{path}", self.base_url))
175                .json(&body);
176            if let Some(key) = &self.api_key {
177                request = request.bearer_auth(key);
178            }
179            let response = request
180                .send()
181                .await
182                .map_err(|e| PhyTraceError::Transport(format!("{path}: {e}")))?;
183            let status = response.status();
184            let value: Value = response
185                .json()
186                .await
187                .map_err(|e| PhyTraceError::Transport(format!("{path}: {e}")))?;
188            if !status.is_success() {
189                let message = value
190                    .get("message")
191                    .and_then(Value::as_str)
192                    .unwrap_or("request failed");
193                return Err(PhyTraceError::Transport(format!(
194                    "{path}: HTTP {status}: {message}"
195                )));
196            }
197            Ok(value)
198        }
199
200        /// Whether a refresh is due.
201        pub fn due(&self) -> bool {
202            self.last_attempt
203                .read()
204                .map(|last| last.map_or(true, |t| t.elapsed() >= self.interval))
205                .unwrap_or(true)
206        }
207
208        /// The refresh interval.
209        pub fn interval(&self) -> Duration {
210            self.interval
211        }
212    }
213
214    impl AttestationProvider for Attestor {
215        fn current(&self) -> Value {
216            self.current
217                .read()
218                .map(|v| v.clone())
219                .unwrap_or_else(|_| json!({"mode": "tpm", "quote_id": null}))
220        }
221    }
222
223    pub(crate) fn hex_decode(s: &str) -> Option<Vec<u8>> {
224        if s.len() % 2 != 0 {
225            return None;
226        }
227        s.as_bytes()
228            .chunks(2)
229            .map(|pair| {
230                let hi = char::from(*pair.first()?).to_digit(16)?;
231                let lo = char::from(*pair.get(1)?).to_digit(16)?;
232                u8::try_from(hi * 16 + lo).ok()
233            })
234            .collect()
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241
242    #[test]
243    fn software_block_is_marked() {
244        assert_eq!(SoftwareAttestation.current()["mode"], "software");
245        assert_eq!(
246            software_attestation()["warning"],
247            "no hardware root of trust"
248        );
249    }
250
251    #[test]
252    fn api_base_accepts_bare_or_versioned_endpoints() {
253        assert_eq!(api_base("http://h:8000"), "http://h:8000/api/v1");
254        assert_eq!(api_base("http://h:8000/"), "http://h:8000/api/v1");
255        assert_eq!(api_base("http://h:8000/api/v1/"), "http://h:8000/api/v1");
256    }
257}