From 58679d88d91e2576c008819594ab48ec7119cc59 Mon Sep 17 00:00:00 2001 From: Kingsley <10992364+kingsleydon@users.noreply.github.com> Date: Fri, 27 Nov 2026 06:06:01 +0000 Subject: [PATCH 1/3] fix(guest-agent): avoid TDX Info quotes and bound attestation waits Legacy Info minted a full TDX quote just to read MRTD, the RTMRs, and the event log. Rocket kept running handlers after clients disconnected. With an unbounded FIFO, abandoned requests consumed quote capacity until live callers timed out too. Read TDREPORT measurements and the event log for TDX Info outside the quote queue. Bound attestation waits and return retryable HTTP 503 when a wait expires. The 15-second default absorbs roughly 15 one-second quotes while leaving time within AntSeed's 20-second deadline and the proposed 20-second pig-tail deadline. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Kingsley <10992364+kingsleydon@users.noreply.github.com> --- CHANGELOG.md | 7 + dstack/guest-agent-simulator/dstack.toml | 1 + dstack/guest-agent/Cargo.toml | 1 + dstack/guest-agent/dstack.toml | 4 + dstack/guest-agent/src/backend.rs | 71 ++++- dstack/guest-agent/src/config.rs | 12 +- dstack/guest-agent/src/rpc_service.rs | 332 ++++++++++++++++++----- dstack/tdx-attest/src/dummy.rs | 4 + dstack/tdx-attest/src/lib.rs | 43 +++ dstack/tdx-attest/src/linux.rs | 13 +- 10 files changed, 417 insertions(+), 71 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d254f54c7f..7c5be77460 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 requirement in the policy bound by `compose_hash` instead of the `gpu-attestation` event. SEV-SNP in public clouds stays unsupported. +### Fixed + +- The guest agent reads TDX measurements for legacy `Info` locally on guests + with a TDREPORT device. The attestation queue can absorb roughly 15 + one-second TDX quotes with the default 15-second wait. Requests that exceed + `attest_queue_timeout_secs` receive HTTP 503 and can retry. + ## [0.6.6] - 2026-11-20 ### Upgrade notes diff --git a/dstack/guest-agent-simulator/dstack.toml b/dstack/guest-agent-simulator/dstack.toml index b1c7325a6a..4cd673cbc0 100644 --- a/dstack/guest-agent-simulator/dstack.toml +++ b/dstack/guest-agent-simulator/dstack.toml @@ -15,6 +15,7 @@ keys_file = "appkeys.json" compose_file = "app-compose.json" sys_config_file = "sys-config.json" data_disks = ["/"] +attest_queue_timeout_secs = 15 [default.core.simulator] attestation_file = "attestation.bin" diff --git a/dstack/guest-agent/Cargo.toml b/dstack/guest-agent/Cargo.toml index 4d81c6172b..2f7d739af5 100644 --- a/dstack/guest-agent/Cargo.toml +++ b/dstack/guest-agent/Cargo.toml @@ -67,3 +67,4 @@ lspci.workspace = true # the synthetic-attestation helpers. Declared here so the production build of # this crate does not carry them. dstack-attest = { workspace = true, features = ["simulator"] } +tokio = { workspace = true, features = ["test-util"] } diff --git a/dstack/guest-agent/dstack.toml b/dstack/guest-agent/dstack.toml index 8b4bcd5db1..42355aac57 100644 --- a/dstack/guest-agent/dstack.toml +++ b/dstack/guest-agent/dstack.toml @@ -15,6 +15,10 @@ keys_file = "/dstack/.host-shared/.appkeys.json" compose_file = "/dstack/.host-shared/app-compose.json" sys_config_file = "/dstack/.host-shared/.sys-config.json" data_disks = ["/"] +# Maximum time in seconds to wait for an attestation slot (positive integer). +# The 15-second default accommodates roughly 15 queued one-second TDX quotes. +# Requests that exceed this wait receive HTTP 503 and can retry. +attest_queue_timeout_secs = 15 [internal-v0] diff --git a/dstack/guest-agent/src/backend.rs b/dstack/guest-agent/src/backend.rs index fcdf471bb2..4d53b5add3 100644 --- a/dstack/guest-agent/src/backend.rs +++ b/dstack/guest-agent/src/backend.rs @@ -3,11 +3,43 @@ // SPDX-License-Identifier: Apache-2.0 use anyhow::{Context, Result}; +use cc_eventlog::TdxEvent; +use dstack_attest::attestation::{ + detect_tee_variant, Attestation, AttestationV1, PlatformEvidence, QuoteContentType, + TdxAttestationExt, TeeVariant, VersionedAttestation, +}; use dstack_guest_agent_rpc::v0::GetQuoteResponse; -use ra_tls::attestation::Attestation; -use ra_tls::attestation::{QuoteContentType, VersionedAttestation}; +use tdx_attest::TdxMeasurements; + +pub struct TcbInfo { + pub measurements: Option, + pub event_log: Vec, +} + +impl From for TcbInfo { + fn from(attestation: AttestationV1) -> Self { + let measurements = attestation.td10_report().map(|report| TdxMeasurements { + mrtd: report.mr_td, + rtmrs: [report.rt_mr0, report.rt_mr1, report.rt_mr2, report.rt_mr3], + }); + let event_log = match attestation.platform { + PlatformEvidence::Tdx { event_log, .. } + | PlatformEvidence::GcpTdx { event_log, .. } => event_log, + _ => Vec::new(), + }; + Self { + measurements, + event_log, + } + } +} pub trait PlatformBackend: Send + Sync { + /// Read TCB info outside the quote queue, or return `None` to use attestation. + fn local_tcb_info(&self) -> Result> { + Ok(None) + } + fn attestation_for_info(&self) -> Result; fn certificate_attestation(&self, pubkey: &[u8]) -> Result; fn quote_response(&self, report_data: [u8; 64], vm_config: &str) -> Result; @@ -16,10 +48,41 @@ pub trait PlatformBackend: Send + Sync { fn attest_cvm(&self, report_data: [u8; 64]) -> Result; } -#[derive(Debug, Default)] -pub struct RealPlatform; +#[derive(Debug)] +pub struct RealPlatform { + has_local_tcb_info: bool, +} + +impl Default for RealPlatform { + fn default() -> Self { + // Probe once at startup. The SEV-SNP configfs probe can wait on the + // kernel lock held during TDX quote generation. + let has_local_tcb_info = tdx_attest::is_report_available() + && matches!( + detect_tee_variant(), + Ok(TeeVariant::DstackTdx | TeeVariant::DstackGcpTdx) + ); + Self { has_local_tcb_info } + } +} impl PlatformBackend for RealPlatform { + fn local_tcb_info(&self) -> Result> { + // Configfs-only guests (including the development TEE simulator) can + // quote but have no TDREPORT ioctl, so keep their existing path. + if !self.has_local_tcb_info { + return Ok(None); + } + let report = tdx_attest::get_report(&[0; 64]).context("failed to get TDREPORT")?; + let mut event_log = + cc_eventlog::tdx::read_event_log().context("failed to read event log")?; + cc_eventlog::tdx::fill_v2_preimages(&mut event_log); + Ok(Some(TcbInfo { + measurements: Some(report.measurements()), + event_log, + })) + } + fn attestation_for_info(&self) -> Result { Ok(Attestation::local() .context("Failed to get local attestation")? diff --git a/dstack/guest-agent/src/config.rs b/dstack/guest-agent/src/config.rs index fb816f2f12..438358d52d 100644 --- a/dstack/guest-agent/src/config.rs +++ b/dstack/guest-agent/src/config.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -use std::{collections::HashSet, ops::Deref, path::PathBuf}; +use std::{collections::HashSet, num::NonZeroU32, ops::Deref, path::PathBuf}; use dstack_types::AppCompose; use figment::Figment; @@ -49,6 +49,12 @@ pub struct Config { pub app_compose: AppComposeWrapper, pub sys_config_file: PathBuf, pub data_disks: HashSet, + /// Maximum time to wait for the attestation queue, in seconds. + /// The 15-second default lets roughly 15 one-second TDX quotes queue while + /// leaving time to finish within the 20-second AntSeed prover deadline and + /// planned pig-tail RPC deadline. Callers with shorter deadlines should + /// avoid relying on queued quotes. + pub attest_queue_timeout_secs: NonZeroU32, } fn deserialize_app_compose<'de, D>(deserializer: D) -> Result @@ -83,6 +89,7 @@ keys_file = "/embedded/keys.json" compose_file = "/embedded/compose.json" sys_config_file = "/embedded/sys-config.json" data_disks = ["/"] +attest_queue_timeout_secs = 15 "#; fn minimal_compose(extra: &str) -> String { @@ -128,7 +135,7 @@ data_disks = ["/", "{directory}/data"] let temporary = TempDir::new().unwrap(); let compose = temporary.path().join("compose.json"); fs::write(&compose, minimal_compose("")).unwrap(); - let leaf = leaf_config(temporary.path(), &compose, ""); + let leaf = leaf_config(temporary.path(), &compose, "attest_queue_timeout_secs = 3"); let config = extract(DEFAULTS, &leaf).unwrap(); @@ -142,6 +149,7 @@ data_disks = ["/", "{directory}/data"] ); assert!(config.data_disks.contains(&PathBuf::from("/"))); assert!(config.data_disks.contains(&temporary.path().join("data"))); + assert_eq!(config.attest_queue_timeout_secs.get(), 3); } #[test] diff --git a/dstack/guest-agent/src/rpc_service.rs b/dstack/guest-agent/src/rpc_service.rs index 234e95f638..eff94a524b 100644 --- a/dstack/guest-agent/src/rpc_service.rs +++ b/dstack/guest-agent/src/rpc_service.rs @@ -3,7 +3,8 @@ // SPDX-License-Identifier: Apache-2.0 use std::collections::HashMap; -use std::sync::{Arc, Mutex}; +use std::fmt; +use std::sync::{Arc, OnceLock}; use std::time::{Duration, Instant}; use anyhow::{Context, Result}; @@ -24,24 +25,22 @@ use ed25519_dalek::ed25519::signature::hazmat::{PrehashSigner, PrehashVerifier}; use ed25519_dalek::{Signer as Ed25519Signer, SigningKey as Ed25519SigningKey, Verifier}; use fs_err as fs; use k256::ecdsa::SigningKey; -use or_panic::ResultOrPanic; -use ra_rpc::{CallContext, RpcCall}; +use ra_rpc::{CallContext, ErrorExt, RpcCall}; use ra_tls::{ api_v1::sign_recoverable_keccak256, - attestation::{ - QuoteContentType, TdxAttestationExt, VersionedAttestation, DEFAULT_HASH_ALGORITHM, - }, + attestation::{QuoteContentType, VersionedAttestation, DEFAULT_HASH_ALGORITHM}, cert::{CertConfigV2, CertSigningRequestV2, Csr}, kdf::{derive_key, derive_p256_key_pair_from_bytes}, }; use rcgen::KeyPair; use ring::rand::{SecureRandom, SystemRandom}; use serde_json::json; +use tokio::time::{timeout_at, Instant as TokioInstant}; use tracing::error; use crate::{ - backend::{PlatformBackend, RealPlatform}, + backend::{PlatformBackend, RealPlatform, TcbInfo}, config::Config, }; @@ -62,6 +61,21 @@ const IDENTITY_RETRY_INTERVAL: Duration = Duration::from_secs(30); /// every `Info` may start: a quote plus an RA-TLS round trip to the KMS. const DEMO_CERT_RETRY_INTERVAL: Duration = Duration::from_secs(30); +#[derive(Debug)] +struct AttestationQueueBusy; + +impl AttestationQueueBusy { + fn rpc_error() -> anyhow::Error { + anyhow::anyhow!("please retry").with_code(503).context(Self) + } +} + +impl fmt::Display for AttestationQueueBusy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("the attestation queue is busy") + } +} + /// Decode the immutable identity fields out of a boot attestation. /// /// Costs a quote and an event-log replay, which is why its result is cached for @@ -143,10 +157,9 @@ struct AppStateInner { /// when each parsed the key itself. app_root_signing_key: Option, /// Identity as decoded from the boot attestation. See [`AppIdentity`]. - identity: tokio::sync::OnceCell, - /// When the last identity decode failed, so the retry can be throttled. - /// See [`IDENTITY_RETRY_INTERVAL`]. - identity_last_failure: Mutex>, + identity: OnceLock, + /// Serializes identity initialization and stores the last decode failure. + identity_last_failure: Arc>>, /// Queues platform calls; see [`AppStateInner::attest`]. attest_lock: Arc>, /// `sys_vendor` and `product_name`, read once. Neither changes while the @@ -177,19 +190,37 @@ pub(crate) struct AppIdentity { } impl AppStateInner { + fn attest_deadline(&self) -> TokioInstant { + TokioInstant::now() + + Duration::from_secs(self.config.attest_queue_timeout_secs.get().into()) + } + /// Run a platform call on the blocking pool, one at a time. /// /// Platform calls block on the hardware quote (about a second on TDX), so /// running one on the executor stalls every connection the agent serves, /// including the systemd watchdog heartbeat. Callers queue here rather than /// on `dstack-attest`'s quote lock, so a flood of requests holds no threads. - /// The guard moves into the task, so a cancelled caller cannot let the - /// next call in while its own is still running. + /// The wait is bounded so old requests stop taking queue slots. The guard + /// moves into the task, so a cancelled caller cannot let the next call in + /// while its own is still running. async fn attest( &self, work: impl FnOnce(&dyn PlatformBackend) -> Result + Send + 'static, ) -> Result { - let guard = self.attest_lock.clone().lock_owned().await; + self.attest_until(self.attest_deadline(), work).await + } + + async fn attest_until( + &self, + deadline: TokioInstant, + work: impl FnOnce(&dyn PlatformBackend) -> Result + Send + 'static, + ) -> Result { + let guard = timeout_at(deadline, self.attest_lock.clone().lock_owned()).await; + // The lock and timer can both be ready when the waiter is polled again. + let Some(guard) = guard.ok().filter(|_| TokioInstant::now() < deadline) else { + return Err(AttestationQueueBusy::rpc_error()); + }; let platform = self.platform.clone(); tokio::task::spawn_blocking(move || { let _guard = guard; @@ -199,6 +230,20 @@ impl AppStateInner { .context("the attestation task panicked")? } + async fn tcb_info(&self) -> Result { + let platform = self.platform.clone(); + if let Some(tcb) = tokio::task::spawn_blocking(move || platform.local_tcb_info()) + .await + .context("the local TCB info task panicked")?? + { + return Ok(tcb); + } + let attestation = self + .attest(|platform| platform.attestation_for_info()) + .await?; + Ok(attestation.into_v1().into()) + } + async fn issue_cert( &self, key: &KeyPair, @@ -226,7 +271,7 @@ impl AppStateInner { } async fn request_demo_cert(&self) -> Result { - let key = KeyPair::generate().context("Failed to generate demo key")?; + let key = KeyPair::generate().context("failed to generate demo key")?; let demo_cert = self .issue_cert( &key, @@ -271,6 +316,7 @@ impl AppState { } match state.request_demo_cert().await { Ok(demo_cert) => _ = state.demo_cert.set(demo_cert), + Err(err) if err.is::() => {} Err(e) => { error!("failed to request demo cert: {e:?}"); *last_failure = Some(Instant::now()); @@ -359,7 +405,7 @@ impl AppState { } pub async fn new(config: Config) -> Result { - Self::new_with_platform(config, Arc::new(RealPlatform)).await + Self::new_with_platform(config, Arc::new(RealPlatform::default())).await } pub fn config(&self) -> &Config { @@ -508,28 +554,46 @@ impl AppState { /// identity is unavailable and when the next attempt is, and the platform /// is not touched at all. pub(crate) async fn identity(&self) -> Result<&AppIdentity> { + if let Some(identity) = self.inner.identity.get() { + return Ok(identity); + } + // Share one wait budget between the initializer and the platform queue. + let deadline = self.inner.attest_deadline(); + let mut last_failure = timeout_at( + deadline, + self.inner.identity_last_failure.clone().lock_owned(), + ) + .await + .map_err(|_| AttestationQueueBusy::rpc_error())?; + if let Some(identity) = self.inner.identity.get() { + return Ok(identity); + } + if let Some(failed_at) = *last_failure { + let elapsed = failed_at.elapsed(); + if elapsed < IDENTITY_RETRY_INTERVAL { + let retry_in = (IDENTITY_RETRY_INTERVAL - elapsed).as_secs() + 1; + anyhow::bail!( + "the app identity is unavailable: decoding it failed and the next attempt is at most {retry_in}s away" + ); + } + } + + // Keep the initializer lock with the decode so a cancelled caller + // still leaves a cached identity or records the failure. + let state = self.inner.clone(); self.inner - .identity - .get_or_try_init(|| async { - let last_failure = &self.inner.identity_last_failure; - if let Some(failed_at) = *last_failure.lock().or_panic("lock should never fail") { - let elapsed = failed_at.elapsed(); - if elapsed < IDENTITY_RETRY_INTERVAL { - let retry_in = (IDENTITY_RETRY_INTERVAL - elapsed).as_secs() + 1; - anyhow::bail!( - "the app identity is unavailable: decoding it failed and the next attempt is at most {retry_in}s away" - ); - } - } - self.inner - .attest(decode_identity) - .await - .inspect_err(|_| { - *last_failure.lock().or_panic("lock should never fail") = - Some(Instant::now()); - }) + .attest_until(deadline, move |platform| { + let identity = decode_identity(platform).inspect_err(|_| { + *last_failure = Some(Instant::now()); + })?; + let _ = state.identity.set(identity); + Ok(()) }) - .await + .await?; + self.inner + .identity + .get() + .context("app identity was not cached") } /// The VM's hardware configuration, as the VMM produced it. @@ -667,32 +731,19 @@ pub async fn get_info(state: &AppState, external: bool) -> Result { let (tcb_info, vm_config) = if hide_tcb_info { Default::default() } else { - let attestation = state - .inner - .attest(|platform| platform.attestation_for_info()) - .await? - .into_v1(); - let td_report = match attestation.td10_report() { - Some(report) => json!({ - "mrtd": hex::encode(report.mr_td), - "rtmr0": hex::encode(report.rt_mr0), - "rtmr1": hex::encode(report.rt_mr1), - "rtmr2": hex::encode(report.rt_mr2), - "rtmr3": hex::encode(report.rt_mr3), - }), - None => json!({}), - }; + let tcb = state.inner.tcb_info().await?; + let measurements = tcb.measurements.as_ref(); let tcb_info = serde_json::to_string_pretty(&json!({ - "mrtd": td_report["mrtd"], - "rtmr0": td_report["rtmr0"], - "rtmr1": td_report["rtmr1"], - "rtmr2": td_report["rtmr2"], - "rtmr3": td_report["rtmr3"], + "mrtd": measurements.map(|m| hex::encode(m.mrtd)), + "rtmr0": measurements.map(|m| hex::encode(m.rtmrs[0])), + "rtmr1": measurements.map(|m| hex::encode(m.rtmrs[1])), + "rtmr2": measurements.map(|m| hex::encode(m.rtmrs[2])), + "rtmr3": measurements.map(|m| hex::encode(m.rtmrs[3])), "mr_aggregated": hex::encode(&identity.mr_aggregated), "os_image_hash": hex::encode(&identity.os_image_hash), "compose_hash": hex::encode(&identity.compose_hash), "device_id": hex::encode(&identity.device_id), - "event_log": attestation.tdx_event_log().unwrap_or_default(), + "event_log": tcb.event_log, "app_compose": state.config().app_compose.raw, })) .unwrap_or_default(); @@ -1221,12 +1272,15 @@ pub(crate) mod tests { Signature as Ed25519Signature, Verifier, VerifyingKey as Ed25519VerifyingKey, }; use k256::ecdsa::{Signature as K256Signature, VerifyingKey}; - use ra_tls::attestation::{AttestationV1, PlatformEvidence, VersionedAttestation}; + use ra_tls::attestation::{ + AttestationV1, PlatformEvidence, TdxAttestationExt, VersionedAttestation, + }; use sha2::{Digest as _, Sha256}; use std::collections::HashSet; use std::convert::TryFrom; use std::io::Write; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + use std::sync::Mutex; pub(crate) const DUMMY_K256_KEY: [u8; 32] = [ 0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F, 0x7A, 0x8B, 0x9C, 0x0D, 0x1E, 0x2F, 0x3A, 0x4B, 0x5C, @@ -1312,6 +1366,7 @@ pub(crate) mod tests { struct InfoAttestationProbe { calls: AtomicUsize, cert_calls: AtomicUsize, + quote_calls: Mutex>, failing: AtomicBool, gate: Mutex< Option<( @@ -1441,6 +1496,7 @@ pub(crate) mod tests { app_compose: dummy_appcompose_wrapper, sys_config_file: String::new().into(), data_disks: HashSet::new(), + attest_queue_timeout_secs: 15.try_into().unwrap(), }; configure(&mut dummy_config); @@ -1527,6 +1583,14 @@ pNs85uhOZE8z2jr8Pg== } impl PlatformBackend for TestSimulatorPlatform { + fn local_tcb_info(&self) -> Result> { + let attestation = self.attestation.clone().into_v1(); + if !matches!(attestation.platform, PlatformEvidence::Tdx { .. }) { + return Ok(None); + } + Ok(Some(attestation.into())) + } + fn attestation_for_info(&self) -> Result { self.probe.calls.fetch_add(1, Ordering::Relaxed); if self.probe.failing.load(Ordering::Relaxed) { @@ -1556,6 +1620,7 @@ pNs85uhOZE8z2jr8Pg== report_data: [u8; 64], vm_config: &str, ) -> Result { + self.probe.quote_calls.lock().unwrap().push(report_data); self.probe.pass_gate(); let attestation = patch_report_data(&self.attestation, report_data); let Some(quote) = attestation.platform.tdx_quote().map(ToOwned::to_owned) else { @@ -2274,6 +2339,151 @@ pNs85uhOZE8z2jr8Pg== quote.await.unwrap().unwrap(); } + #[tokio::test] + async fn tdx_info_returns_the_legacy_tcb_document_during_a_quote() { + let probe = Arc::new(InfoAttestationProbe::default()); + let (state, fixture) = setup_test_state_with_probe(probe.clone()).await; + let identity = state.identity().await.unwrap(); + state.inner.demo_cert.set(String::new()).unwrap(); + let (entered, release) = probe.arm_gate(); + let quote = tokio::spawn({ + let state = state.clone(); + async move { state.quote_response([0; 64]).await } + }); + entered.await.unwrap(); + + let info = tokio::time::timeout(Duration::from_secs(2), get_info(&state, false)) + .await + .expect("Info answers before the quote is released") + .unwrap(); + let attestation = VersionedAttestation::from_bytes(&fs::read(fixture.path()).unwrap()) + .unwrap() + .into_v1(); + let report = attestation.td10_report().unwrap(); + let expected = json!({ + "mrtd": hex::encode(report.mr_td), + "rtmr0": hex::encode(report.rt_mr0), + "rtmr1": hex::encode(report.rt_mr1), + "rtmr2": hex::encode(report.rt_mr2), + "rtmr3": hex::encode(report.rt_mr3), + "mr_aggregated": hex::encode(&identity.mr_aggregated), + "os_image_hash": hex::encode(&identity.os_image_hash), + "compose_hash": hex::encode(&identity.compose_hash), + "device_id": hex::encode(&identity.device_id), + "event_log": attestation.tdx_event_log().unwrap(), + "app_compose": "", + }); + assert_eq!( + info.tcb_info, + serde_json::to_string_pretty(&expected).unwrap() + ); + assert_eq!(probe.calls(), 1, "only the cached identity needs a quote"); + assert_eq!(*probe.quote_calls.lock().unwrap(), [[0; 64]]); + release.send(()).unwrap(); + quote.await.unwrap().unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn an_expired_quote_waiter_returns_rpc_unavailable_and_never_runs() { + let probe = Arc::new(InfoAttestationProbe::default()); + let (state, _guard) = build_test_state( + None, + |config| config.attest_queue_timeout_secs = 3.try_into().unwrap(), + probe.clone(), + ) + .await; + let (entered, release) = probe.arm_gate(); + let quote = tokio::spawn({ + let state = state.clone(); + async move { state.quote_response([1; 64]).await } + }); + entered.await.unwrap(); + + let request = InternalRpcHandler::new(state.clone()).call( + "GetQuote".into(), + b"{}".to_vec(), + true, + false, + ); + tokio::pin!(request); + assert!(futures::poll!(&mut request).is_pending()); + tokio::time::advance(Duration::from_secs(4)).await; + let (code, body) = request.await; + assert_eq!(code, 503); + assert!(String::from_utf8(body).unwrap().contains("queue is busy")); + + release.send(()).unwrap(); + quote.await.unwrap().unwrap(); + state.quote_response([2; 64]).await.unwrap(); + assert_eq!(*probe.quote_calls.lock().unwrap(), [[1; 64], [2; 64]]); + } + + #[tokio::test(start_paused = true)] + async fn queued_quotes_run_in_order_after_a_cancelled_waiter_leaves() { + let probe = Arc::new(InfoAttestationProbe::default()); + let (state, _guard) = setup_test_state_with_probe(probe.clone()).await; + let (entered, release) = probe.arm_gate(); + let quote = tokio::spawn({ + let state = state.clone(); + async move { state.quote_response([1; 64]).await } + }); + entered.await.unwrap(); + + let first = state.quote_response([2; 64]); + let mut cancelled = Box::pin(state.quote_response([3; 64])); + let second = state.quote_response([4; 64]); + tokio::pin!(first, second); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut cancelled).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + drop(cancelled); + release.send(()).unwrap(); + + let (second, first) = tokio::join!(second, first); + first.unwrap(); + second.unwrap(); + quote.await.unwrap().unwrap(); + assert_eq!( + *probe.quote_calls.lock().unwrap(), + [[1; 64], [2; 64], [4; 64]] + ); + } + + #[tokio::test(start_paused = true)] + async fn identity_retries_immediately_after_a_queue_timeout() { + let probe = Arc::new(InfoAttestationProbe::default()); + let (state, _fixture) = setup_test_state_with_probe(probe.clone()).await; + let guard = state.inner.attest_lock.lock().await; + + let err = state.identity().await.expect_err("the queue is still busy"); + assert_eq!(ra_rpc::code_of(&err), Some(503)); + assert_eq!(probe.calls(), 0); + drop(guard); + + state + .identity() + .await + .expect("identity retries immediately"); + assert_eq!(probe.calls(), 1); + } + + #[tokio::test(start_paused = true)] + async fn concurrent_identity_requests_time_out_within_one_queue_wait() { + let probe = Arc::new(InfoAttestationProbe::default()); + let (state, _fixture) = setup_test_state_with_probe(probe.clone()).await; + let _guard = state.inner.attest_lock.lock().await; + + let (first, second) = tokio::time::timeout(Duration::from_secs(16), async { + tokio::join!(state.identity(), state.identity()) + }) + .await + .expect("both callers time out within one 15-second queue wait"); + + assert_eq!(ra_rpc::code_of(&first.unwrap_err()), Some(503)); + assert_eq!(ra_rpc::code_of(&second.unwrap_err()), Some(503)); + assert_eq!(probe.calls(), 0); + } + /// A failed decode must be as cheap to repeat as a cached success is. /// `identity()` is reached from the anonymous `/prpc/v1/Info`, and each /// attempt is a hardware quote plus an RTMR replay under the global quote @@ -2318,11 +2528,7 @@ pNs85uhOZE8z2jr8Pg== .expect_err("the platform refuses to attest"); // Age the recorded failure rather than sleeping out the interval. - *state - .inner - .identity_last_failure - .lock() - .expect("lock should never fail") = Some( + *state.inner.identity_last_failure.lock().await = Some( Instant::now() .checked_sub(IDENTITY_RETRY_INTERVAL) .expect("the monotonic clock is older than the throttle window"), diff --git a/dstack/tdx-attest/src/dummy.rs b/dstack/tdx-attest/src/dummy.rs index b153474def..60b067ebb8 100644 --- a/dstack/tdx-attest/src/dummy.rs +++ b/dstack/tdx-attest/src/dummy.rs @@ -53,3 +53,7 @@ pub fn extend_rtmr(_index: u32, _event_type: u32, _digest: [u8; 48]) -> Result<( pub fn is_tdx_available() -> bool { false } + +pub fn is_report_available() -> bool { + false +} diff --git a/dstack/tdx-attest/src/lib.rs b/dstack/tdx-attest/src/lib.rs index 4c73fb02c6..8b20497bf8 100644 --- a/dstack/tdx-attest/src/lib.rs +++ b/dstack/tdx-attest/src/lib.rs @@ -22,3 +22,46 @@ pub type TdxReportData = [u8; 64]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TdxReport(pub [u8; 1024]); + +pub struct TdxMeasurements { + pub mrtd: [u8; 48], + pub rtmrs: [[u8; 48]; 4], +} + +impl TdxReport { + /// Extract the measurements from the TDINFO section of a TDREPORT0. + pub fn measurements(&self) -> TdxMeasurements { + const MRTD_OFFSET: usize = 512 + 16; // TDINFO starts with ATTRIBUTES and XFAM. + const RTMR0_OFFSET: usize = MRTD_OFFSET + 4 * 48; // After MRTD and three owner/config hashes. + + let digest_at = |offset| { + let mut digest = [0; 48]; + let bytes = &self.0[offset..offset + digest.len()]; + digest.copy_from_slice(bytes); + digest + }; + TdxMeasurements { + mrtd: digest_at(MRTD_OFFSET), + rtmrs: std::array::from_fn(|index| digest_at(RTMR0_OFFSET + index * 48)), + } + } +} + +#[cfg(test)] +mod tests { + use super::TdxReport; + + #[test] + fn extracts_the_tdinfo_measurements() { + let mut bytes = [0xff; 1024]; + bytes[528..576].fill(1); + bytes[720..768].fill(2); + bytes[768..816].fill(3); + bytes[816..864].fill(4); + bytes[864..912].fill(5); + + let measurements = TdxReport(bytes).measurements(); + assert_eq!(measurements.mrtd, [1; 48]); + assert_eq!(measurements.rtmrs, [[2; 48], [3; 48], [4; 48], [5; 48]]); + } +} diff --git a/dstack/tdx-attest/src/linux.rs b/dstack/tdx-attest/src/linux.rs index bde47ce342..df0327874f 100644 --- a/dstack/tdx-attest/src/linux.rs +++ b/dstack/tdx-attest/src/linux.rs @@ -153,7 +153,7 @@ pub enum TdxAttestError { // Global state // ============================================================================ -/// Global lock for TDX operations - the driver doesn't support concurrent access +/// Serializes quote requests that share a configfs report or use the QGS transport. static TDX_LOCK: Mutex<()> = Mutex::new(()); /// Track if we've already tried to create the configfs directory @@ -216,7 +216,7 @@ fn absolute_env_path(var: &str, value: impl AsRef) -> Result { /// Return whether a TDX guest provider is available through either the legacy /// misc device or the standard TSM report interface. pub fn is_tdx_available() -> bool { - if Path::new(TDX_GUEST_DEVICE).exists() { + if is_report_available() { return true; } @@ -239,11 +239,20 @@ pub fn is_tdx_available() -> bool { .any(|entry| verify_configfs_provider(&entry.path()).unwrap_or(false)) } +/// Return whether the guest exposes the local TDREPORT device. +pub fn is_report_available() -> bool { + Path::new(TDX_GUEST_DEVICE).exists() +} + fn is_vsock_available() -> bool { read_vsock_port().map(|p| p > 0).unwrap_or(false) } /// Get a TDX report for the given report data. +/// +/// The ioctl uses per-call buffers on older kernels and the driver's measurement +/// lock on newer kernels. Configfs releases that lock before waiting for the quote, +/// and the vsock path completes this ioctl before contacting QGS. pub fn get_report(report_data: &TdxReportData) -> Result { let file = OpenOptions::new() .read(true) From 6cbed9115b851a043ba3cfd0d6adb88c9848eee3 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Fri, 27 Nov 2026 00:35:41 -0800 Subject: [PATCH 2/3] refactor(guest-agent): simplify Info TCB reads and the queue bound Read MRTD and RTMR0-3 for legacy Info from the kernel's TSM measurement sysfs (tdx_guest/measurements) instead of parsing TDREPORT offsets. The kernel already decodes the report there, and the directory's presence is enough to pick the local path, so the startup TEE probe and the TDREPORT helpers are gone. Kernels without the interface fall back to the attestation path as before. On a dstack 0.6.5 CVM the sysfs values match the quote's and a read takes about 0.1 ms, also while a configfs quote is in flight. Bound the attestation queue wait with a constant 10-second timeout in attest() only, matching the gateway's legacy Info timeout. A timed-out wait returns HTTP 503 as an ordinary error, so the existing identity and demo-cert throttles treat it like any other failure: congestion backs off too. With the bound and the throttle in place every identity caller waits at most one timeout, so identity() keeps its OnceCell and needs no deadline of its own. This drops the attest_queue_timeout_secs option, attest_until, the AttestationQueueBusy type, the OnceLock/tokio::Mutex identity rewrite, the demo-cert special case, and the unrelated message and comment edits. Signed-off-by: Kevin Wang --- CHANGELOG.md | 8 +- dstack/guest-agent-simulator/dstack.toml | 1 - dstack/guest-agent/dstack.toml | 4 - dstack/guest-agent/src/backend.rs | 58 ++--- dstack/guest-agent/src/config.rs | 12 +- dstack/guest-agent/src/rpc_service.rs | 294 ++++++++--------------- dstack/tdx-attest/src/dummy.rs | 8 +- dstack/tdx-attest/src/lib.rs | 40 +-- dstack/tdx-attest/src/linux.rs | 39 ++- 9 files changed, 153 insertions(+), 311 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c5be77460..8f5cc0dca4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,10 +69,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- The guest agent reads TDX measurements for legacy `Info` locally on guests - with a TDREPORT device. The attestation queue can absorb roughly 15 - one-second TDX quotes with the default 15-second wait. Requests that exceed - `attest_queue_timeout_secs` receive HTTP 503 and can retry. +- The guest agent answers legacy `Info` without a quote on TDX guests whose + kernel exposes the TSM measurement sysfs, so `Info` no longer queues behind + quote callers. Callers that wait more than 10 seconds for the attestation + queue receive HTTP 503 and can retry. ## [0.6.6] - 2026-11-20 diff --git a/dstack/guest-agent-simulator/dstack.toml b/dstack/guest-agent-simulator/dstack.toml index 4cd673cbc0..b1c7325a6a 100644 --- a/dstack/guest-agent-simulator/dstack.toml +++ b/dstack/guest-agent-simulator/dstack.toml @@ -15,7 +15,6 @@ keys_file = "appkeys.json" compose_file = "app-compose.json" sys_config_file = "sys-config.json" data_disks = ["/"] -attest_queue_timeout_secs = 15 [default.core.simulator] attestation_file = "attestation.bin" diff --git a/dstack/guest-agent/dstack.toml b/dstack/guest-agent/dstack.toml index 42355aac57..8b4bcd5db1 100644 --- a/dstack/guest-agent/dstack.toml +++ b/dstack/guest-agent/dstack.toml @@ -15,10 +15,6 @@ keys_file = "/dstack/.host-shared/.appkeys.json" compose_file = "/dstack/.host-shared/app-compose.json" sys_config_file = "/dstack/.host-shared/.sys-config.json" data_disks = ["/"] -# Maximum time in seconds to wait for an attestation slot (positive integer). -# The 15-second default accommodates roughly 15 queued one-second TDX quotes. -# Requests that exceed this wait receive HTTP 503 and can retry. -attest_queue_timeout_secs = 15 [internal-v0] diff --git a/dstack/guest-agent/src/backend.rs b/dstack/guest-agent/src/backend.rs index 4d53b5add3..c671a34328 100644 --- a/dstack/guest-agent/src/backend.rs +++ b/dstack/guest-agent/src/backend.rs @@ -4,13 +4,14 @@ use anyhow::{Context, Result}; use cc_eventlog::TdxEvent; -use dstack_attest::attestation::{ - detect_tee_variant, Attestation, AttestationV1, PlatformEvidence, QuoteContentType, - TdxAttestationExt, TeeVariant, VersionedAttestation, -}; use dstack_guest_agent_rpc::v0::GetQuoteResponse; +use ra_tls::attestation::Attestation; +use ra_tls::attestation::{ + AttestationV1, QuoteContentType, TdxAttestationExt, VersionedAttestation, +}; use tdx_attest::TdxMeasurements; +/// The TDX measurements and event log legacy `Info` reports. pub struct TcbInfo { pub measurements: Option, pub event_log: Vec, @@ -18,24 +19,19 @@ pub struct TcbInfo { impl From for TcbInfo { fn from(attestation: AttestationV1) -> Self { - let measurements = attestation.td10_report().map(|report| TdxMeasurements { - mrtd: report.mr_td, - rtmrs: [report.rt_mr0, report.rt_mr1, report.rt_mr2, report.rt_mr3], - }); - let event_log = match attestation.platform { - PlatformEvidence::Tdx { event_log, .. } - | PlatformEvidence::GcpTdx { event_log, .. } => event_log, - _ => Vec::new(), - }; Self { - measurements, - event_log, + measurements: attestation.td10_report().map(|report| TdxMeasurements { + mrtd: report.mr_td, + rtmrs: [report.rt_mr0, report.rt_mr1, report.rt_mr2, report.rt_mr3], + }), + event_log: attestation.tdx_event_log().unwrap_or_default().to_vec(), } } } pub trait PlatformBackend: Send + Sync { - /// Read TCB info outside the quote queue, or return `None` to use attestation. + /// Read the TCB info without a quote, or `None` to fall back to + /// [`Self::attestation_for_info`]. fn local_tcb_info(&self) -> Result> { Ok(None) } @@ -48,37 +44,21 @@ pub trait PlatformBackend: Send + Sync { fn attest_cvm(&self, report_data: [u8; 64]) -> Result; } -#[derive(Debug)] -pub struct RealPlatform { - has_local_tcb_info: bool, -} - -impl Default for RealPlatform { - fn default() -> Self { - // Probe once at startup. The SEV-SNP configfs probe can wait on the - // kernel lock held during TDX quote generation. - let has_local_tcb_info = tdx_attest::is_report_available() - && matches!( - detect_tee_variant(), - Ok(TeeVariant::DstackTdx | TeeVariant::DstackGcpTdx) - ); - Self { has_local_tcb_info } - } -} +#[derive(Debug, Default)] +pub struct RealPlatform; impl PlatformBackend for RealPlatform { fn local_tcb_info(&self) -> Result> { - // Configfs-only guests (including the development TEE simulator) can - // quote but have no TDREPORT ioctl, so keep their existing path. - if !self.has_local_tcb_info { + let Some(measurements) = + tdx_attest::read_measurements().context("failed to read TDX measurements")? + else { return Ok(None); - } - let report = tdx_attest::get_report(&[0; 64]).context("failed to get TDREPORT")?; + }; let mut event_log = cc_eventlog::tdx::read_event_log().context("failed to read event log")?; cc_eventlog::tdx::fill_v2_preimages(&mut event_log); Ok(Some(TcbInfo { - measurements: Some(report.measurements()), + measurements: Some(measurements), event_log, })) } diff --git a/dstack/guest-agent/src/config.rs b/dstack/guest-agent/src/config.rs index 438358d52d..fb816f2f12 100644 --- a/dstack/guest-agent/src/config.rs +++ b/dstack/guest-agent/src/config.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -use std::{collections::HashSet, num::NonZeroU32, ops::Deref, path::PathBuf}; +use std::{collections::HashSet, ops::Deref, path::PathBuf}; use dstack_types::AppCompose; use figment::Figment; @@ -49,12 +49,6 @@ pub struct Config { pub app_compose: AppComposeWrapper, pub sys_config_file: PathBuf, pub data_disks: HashSet, - /// Maximum time to wait for the attestation queue, in seconds. - /// The 15-second default lets roughly 15 one-second TDX quotes queue while - /// leaving time to finish within the 20-second AntSeed prover deadline and - /// planned pig-tail RPC deadline. Callers with shorter deadlines should - /// avoid relying on queued quotes. - pub attest_queue_timeout_secs: NonZeroU32, } fn deserialize_app_compose<'de, D>(deserializer: D) -> Result @@ -89,7 +83,6 @@ keys_file = "/embedded/keys.json" compose_file = "/embedded/compose.json" sys_config_file = "/embedded/sys-config.json" data_disks = ["/"] -attest_queue_timeout_secs = 15 "#; fn minimal_compose(extra: &str) -> String { @@ -135,7 +128,7 @@ data_disks = ["/", "{directory}/data"] let temporary = TempDir::new().unwrap(); let compose = temporary.path().join("compose.json"); fs::write(&compose, minimal_compose("")).unwrap(); - let leaf = leaf_config(temporary.path(), &compose, "attest_queue_timeout_secs = 3"); + let leaf = leaf_config(temporary.path(), &compose, ""); let config = extract(DEFAULTS, &leaf).unwrap(); @@ -149,7 +142,6 @@ data_disks = ["/", "{directory}/data"] ); assert!(config.data_disks.contains(&PathBuf::from("/"))); assert!(config.data_disks.contains(&temporary.path().join("data"))); - assert_eq!(config.attest_queue_timeout_secs.get(), 3); } #[test] diff --git a/dstack/guest-agent/src/rpc_service.rs b/dstack/guest-agent/src/rpc_service.rs index eff94a524b..2ba67bc460 100644 --- a/dstack/guest-agent/src/rpc_service.rs +++ b/dstack/guest-agent/src/rpc_service.rs @@ -3,8 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 use std::collections::HashMap; -use std::fmt; -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::{Context, Result}; @@ -25,7 +24,8 @@ use ed25519_dalek::ed25519::signature::hazmat::{PrehashSigner, PrehashVerifier}; use ed25519_dalek::{Signer as Ed25519Signer, SigningKey as Ed25519SigningKey, Verifier}; use fs_err as fs; use k256::ecdsa::SigningKey; -use ra_rpc::{CallContext, ErrorExt, RpcCall}; +use or_panic::ResultOrPanic; +use ra_rpc::{CallContext, ResultExt as _, RpcCall}; use ra_tls::{ api_v1::sign_recoverable_keccak256, attestation::{QuoteContentType, VersionedAttestation, DEFAULT_HASH_ALGORITHM}, @@ -35,7 +35,6 @@ use ra_tls::{ use rcgen::KeyPair; use ring::rand::{SecureRandom, SystemRandom}; use serde_json::json; -use tokio::time::{timeout_at, Instant as TokioInstant}; use tracing::error; @@ -61,20 +60,12 @@ const IDENTITY_RETRY_INTERVAL: Duration = Duration::from_secs(30); /// every `Info` may start: a quote plus an RA-TLS round trip to the KMS. const DEMO_CERT_RETRY_INTERVAL: Duration = Duration::from_secs(30); -#[derive(Debug)] -struct AttestationQueueBusy; - -impl AttestationQueueBusy { - fn rpc_error() -> anyhow::Error { - anyhow::anyhow!("please retry").with_code(503).context(Self) - } -} - -impl fmt::Display for AttestationQueueBusy { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("the attestation queue is busy") - } -} +/// How long a caller may wait for the attestation queue. +/// +/// Callers keep running after their client disconnects, so without a bound a +/// slow platform lets abandoned requests take every quote slot from live ones. +/// A timeout counts as a failure for the identity and demo-cert throttles. +const ATTEST_QUEUE_TIMEOUT: Duration = Duration::from_secs(10); /// Decode the immutable identity fields out of a boot attestation. /// @@ -157,9 +148,10 @@ struct AppStateInner { /// when each parsed the key itself. app_root_signing_key: Option, /// Identity as decoded from the boot attestation. See [`AppIdentity`]. - identity: OnceLock, - /// Serializes identity initialization and stores the last decode failure. - identity_last_failure: Arc>>, + identity: tokio::sync::OnceCell, + /// When the last identity decode failed, so the retry can be throttled. + /// See [`IDENTITY_RETRY_INTERVAL`]. + identity_last_failure: Mutex>, /// Queues platform calls; see [`AppStateInner::attest`]. attest_lock: Arc>, /// `sys_vendor` and `product_name`, read once. Neither changes while the @@ -190,37 +182,24 @@ pub(crate) struct AppIdentity { } impl AppStateInner { - fn attest_deadline(&self) -> TokioInstant { - TokioInstant::now() - + Duration::from_secs(self.config.attest_queue_timeout_secs.get().into()) - } - /// Run a platform call on the blocking pool, one at a time. /// /// Platform calls block on the hardware quote (about a second on TDX), so /// running one on the executor stalls every connection the agent serves, /// including the systemd watchdog heartbeat. Callers queue here rather than /// on `dstack-attest`'s quote lock, so a flood of requests holds no threads. - /// The wait is bounded so old requests stop taking queue slots. The guard - /// moves into the task, so a cancelled caller cannot let the next call in - /// while its own is still running. + /// The wait is bounded by [`ATTEST_QUEUE_TIMEOUT`]. The guard moves into + /// the task, so a cancelled caller cannot let the next call in while its + /// own is still running. async fn attest( &self, work: impl FnOnce(&dyn PlatformBackend) -> Result + Send + 'static, ) -> Result { - self.attest_until(self.attest_deadline(), work).await - } - - async fn attest_until( - &self, - deadline: TokioInstant, - work: impl FnOnce(&dyn PlatformBackend) -> Result + Send + 'static, - ) -> Result { - let guard = timeout_at(deadline, self.attest_lock.clone().lock_owned()).await; - // The lock and timer can both be ready when the waiter is polled again. - let Some(guard) = guard.ok().filter(|_| TokioInstant::now() < deadline) else { - return Err(AttestationQueueBusy::rpc_error()); - }; + let guard = + tokio::time::timeout(ATTEST_QUEUE_TIMEOUT, self.attest_lock.clone().lock_owned()) + .await + .context("the attestation queue is busy, retry later") + .with_code(503)?; let platform = self.platform.clone(); tokio::task::spawn_blocking(move || { let _guard = guard; @@ -230,18 +209,21 @@ impl AppStateInner { .context("the attestation task panicked")? } + /// The TCB info for legacy `Info`, read without a quote where the platform + /// allows, so `Info` does not queue behind quote callers. async fn tcb_info(&self) -> Result { let platform = self.platform.clone(); - if let Some(tcb) = tokio::task::spawn_blocking(move || platform.local_tcb_info()) + let local = tokio::task::spawn_blocking(move || platform.local_tcb_info()) .await - .context("the local TCB info task panicked")?? - { - return Ok(tcb); + .context("the TCB info task panicked")??; + match local { + Some(tcb) => Ok(tcb), + None => Ok(self + .attest(|platform| platform.attestation_for_info()) + .await? + .into_v1() + .into()), } - let attestation = self - .attest(|platform| platform.attestation_for_info()) - .await?; - Ok(attestation.into_v1().into()) } async fn issue_cert( @@ -271,7 +253,7 @@ impl AppStateInner { } async fn request_demo_cert(&self) -> Result { - let key = KeyPair::generate().context("failed to generate demo key")?; + let key = KeyPair::generate().context("Failed to generate demo key")?; let demo_cert = self .issue_cert( &key, @@ -316,7 +298,6 @@ impl AppState { } match state.request_demo_cert().await { Ok(demo_cert) => _ = state.demo_cert.set(demo_cert), - Err(err) if err.is::() => {} Err(e) => { error!("failed to request demo cert: {e:?}"); *last_failure = Some(Instant::now()); @@ -405,7 +386,7 @@ impl AppState { } pub async fn new(config: Config) -> Result { - Self::new_with_platform(config, Arc::new(RealPlatform::default())).await + Self::new_with_platform(config, Arc::new(RealPlatform)).await } pub fn config(&self) -> &Config { @@ -554,46 +535,28 @@ impl AppState { /// identity is unavailable and when the next attempt is, and the platform /// is not touched at all. pub(crate) async fn identity(&self) -> Result<&AppIdentity> { - if let Some(identity) = self.inner.identity.get() { - return Ok(identity); - } - // Share one wait budget between the initializer and the platform queue. - let deadline = self.inner.attest_deadline(); - let mut last_failure = timeout_at( - deadline, - self.inner.identity_last_failure.clone().lock_owned(), - ) - .await - .map_err(|_| AttestationQueueBusy::rpc_error())?; - if let Some(identity) = self.inner.identity.get() { - return Ok(identity); - } - if let Some(failed_at) = *last_failure { - let elapsed = failed_at.elapsed(); - if elapsed < IDENTITY_RETRY_INTERVAL { - let retry_in = (IDENTITY_RETRY_INTERVAL - elapsed).as_secs() + 1; - anyhow::bail!( - "the app identity is unavailable: decoding it failed and the next attempt is at most {retry_in}s away" - ); - } - } - - // Keep the initializer lock with the decode so a cancelled caller - // still leaves a cached identity or records the failure. - let state = self.inner.clone(); - self.inner - .attest_until(deadline, move |platform| { - let identity = decode_identity(platform).inspect_err(|_| { - *last_failure = Some(Instant::now()); - })?; - let _ = state.identity.set(identity); - Ok(()) - }) - .await?; self.inner .identity - .get() - .context("app identity was not cached") + .get_or_try_init(|| async { + let last_failure = &self.inner.identity_last_failure; + if let Some(failed_at) = *last_failure.lock().or_panic("lock should never fail") { + let elapsed = failed_at.elapsed(); + if elapsed < IDENTITY_RETRY_INTERVAL { + let retry_in = (IDENTITY_RETRY_INTERVAL - elapsed).as_secs() + 1; + anyhow::bail!( + "the app identity is unavailable: decoding it failed and the next attempt is at most {retry_in}s away" + ); + } + } + self.inner + .attest(decode_identity) + .await + .inspect_err(|_| { + *last_failure.lock().or_panic("lock should never fail") = + Some(Instant::now()); + }) + }) + .await } /// The VM's hardware configuration, as the VMM produced it. @@ -732,13 +695,13 @@ pub async fn get_info(state: &AppState, external: bool) -> Result { Default::default() } else { let tcb = state.inner.tcb_info().await?; - let measurements = tcb.measurements.as_ref(); + let mr = tcb.measurements.as_ref(); let tcb_info = serde_json::to_string_pretty(&json!({ - "mrtd": measurements.map(|m| hex::encode(m.mrtd)), - "rtmr0": measurements.map(|m| hex::encode(m.rtmrs[0])), - "rtmr1": measurements.map(|m| hex::encode(m.rtmrs[1])), - "rtmr2": measurements.map(|m| hex::encode(m.rtmrs[2])), - "rtmr3": measurements.map(|m| hex::encode(m.rtmrs[3])), + "mrtd": mr.map(|m| hex::encode(m.mrtd)), + "rtmr0": mr.map(|m| hex::encode(m.rtmrs[0])), + "rtmr1": mr.map(|m| hex::encode(m.rtmrs[1])), + "rtmr2": mr.map(|m| hex::encode(m.rtmrs[2])), + "rtmr3": mr.map(|m| hex::encode(m.rtmrs[3])), "mr_aggregated": hex::encode(&identity.mr_aggregated), "os_image_hash": hex::encode(&identity.os_image_hash), "compose_hash": hex::encode(&identity.compose_hash), @@ -1280,7 +1243,6 @@ pub(crate) mod tests { use std::convert::TryFrom; use std::io::Write; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - use std::sync::Mutex; pub(crate) const DUMMY_K256_KEY: [u8; 32] = [ 0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F, 0x7A, 0x8B, 0x9C, 0x0D, 0x1E, 0x2F, 0x3A, 0x4B, 0x5C, @@ -1366,7 +1328,6 @@ pub(crate) mod tests { struct InfoAttestationProbe { calls: AtomicUsize, cert_calls: AtomicUsize, - quote_calls: Mutex>, failing: AtomicBool, gate: Mutex< Option<( @@ -1496,7 +1457,6 @@ pub(crate) mod tests { app_compose: dummy_appcompose_wrapper, sys_config_file: String::new().into(), data_disks: HashSet::new(), - attest_queue_timeout_secs: 15.try_into().unwrap(), }; configure(&mut dummy_config); @@ -1620,7 +1580,6 @@ pNs85uhOZE8z2jr8Pg== report_data: [u8; 64], vm_config: &str, ) -> Result { - self.probe.quote_calls.lock().unwrap().push(report_data); self.probe.pass_gate(); let attestation = patch_report_data(&self.attestation, report_data); let Some(quote) = attestation.platform.tdx_quote().map(ToOwned::to_owned) else { @@ -2339,24 +2298,29 @@ pNs85uhOZE8z2jr8Pg== quote.await.unwrap().unwrap(); } + /// Legacy `Info` reads the TCB info without a quote, so it answers while a + /// quote holds the queue, with the same document the quote would give. #[tokio::test] - async fn tdx_info_returns_the_legacy_tcb_document_during_a_quote() { + async fn legacy_info_does_not_queue_behind_a_quote() { let probe = Arc::new(InfoAttestationProbe::default()); - let (state, fixture) = setup_test_state_with_probe(probe.clone()).await; + let (state, _guard) = setup_test_state_with_probe(probe.clone()).await; let identity = state.identity().await.unwrap(); state.inner.demo_cert.set(String::new()).unwrap(); - let (entered, release) = probe.arm_gate(); + let (entered_rx, release_tx) = probe.arm_gate(); let quote = tokio::spawn({ let state = state.clone(); async move { state.quote_response([0; 64]).await } }); - entered.await.unwrap(); + entered_rx.await.unwrap(); let info = tokio::time::timeout(Duration::from_secs(2), get_info(&state, false)) .await - .expect("Info answers before the quote is released") + .expect("Info answers while the quote is held") .unwrap(); - let attestation = VersionedAttestation::from_bytes(&fs::read(fixture.path()).unwrap()) + let attestation = state + .inner + .platform + .attestation_for_info() .unwrap() .into_v1(); let report = attestation.td10_report().unwrap(); @@ -2371,116 +2335,44 @@ pNs85uhOZE8z2jr8Pg== "compose_hash": hex::encode(&identity.compose_hash), "device_id": hex::encode(&identity.device_id), "event_log": attestation.tdx_event_log().unwrap(), - "app_compose": "", + "app_compose": state.config().app_compose.raw, }); assert_eq!( info.tcb_info, serde_json::to_string_pretty(&expected).unwrap() ); - assert_eq!(probe.calls(), 1, "only the cached identity needs a quote"); - assert_eq!(*probe.quote_calls.lock().unwrap(), [[0; 64]]); - release.send(()).unwrap(); - quote.await.unwrap().unwrap(); - } - - #[tokio::test(start_paused = true)] - async fn an_expired_quote_waiter_returns_rpc_unavailable_and_never_runs() { - let probe = Arc::new(InfoAttestationProbe::default()); - let (state, _guard) = build_test_state( - None, - |config| config.attest_queue_timeout_secs = 3.try_into().unwrap(), - probe.clone(), - ) - .await; - let (entered, release) = probe.arm_gate(); - let quote = tokio::spawn({ - let state = state.clone(); - async move { state.quote_response([1; 64]).await } - }); - entered.await.unwrap(); - - let request = InternalRpcHandler::new(state.clone()).call( - "GetQuote".into(), - b"{}".to_vec(), - true, - false, - ); - tokio::pin!(request); - assert!(futures::poll!(&mut request).is_pending()); - tokio::time::advance(Duration::from_secs(4)).await; - let (code, body) = request.await; - assert_eq!(code, 503); - assert!(String::from_utf8(body).unwrap().contains("queue is busy")); - - release.send(()).unwrap(); - quote.await.unwrap().unwrap(); - state.quote_response([2; 64]).await.unwrap(); - assert_eq!(*probe.quote_calls.lock().unwrap(), [[1; 64], [2; 64]]); - } - #[tokio::test(start_paused = true)] - async fn queued_quotes_run_in_order_after_a_cancelled_waiter_leaves() { - let probe = Arc::new(InfoAttestationProbe::default()); - let (state, _guard) = setup_test_state_with_probe(probe.clone()).await; - let (entered, release) = probe.arm_gate(); - let quote = tokio::spawn({ - let state = state.clone(); - async move { state.quote_response([1; 64]).await } - }); - entered.await.unwrap(); - - let first = state.quote_response([2; 64]); - let mut cancelled = Box::pin(state.quote_response([3; 64])); - let second = state.quote_response([4; 64]); - tokio::pin!(first, second); - assert!(futures::poll!(&mut first).is_pending()); - assert!(futures::poll!(&mut cancelled).is_pending()); - assert!(futures::poll!(&mut second).is_pending()); - drop(cancelled); - release.send(()).unwrap(); - - let (second, first) = tokio::join!(second, first); - first.unwrap(); - second.unwrap(); + release_tx.send(()).unwrap(); quote.await.unwrap().unwrap(); - assert_eq!( - *probe.quote_calls.lock().unwrap(), - [[1; 64], [2; 64], [4; 64]] - ); } #[tokio::test(start_paused = true)] - async fn identity_retries_immediately_after_a_queue_timeout() { - let probe = Arc::new(InfoAttestationProbe::default()); - let (state, _fixture) = setup_test_state_with_probe(probe.clone()).await; - let guard = state.inner.attest_lock.lock().await; + async fn a_platform_call_gives_up_on_a_held_queue_with_503() { + let (state, _guard) = setup_test_state_with_probe(Arc::default()).await; + let held = state.inner.attest_lock.lock().await; - let err = state.identity().await.expect_err("the queue is still busy"); + let err = state + .quote_response([0; 64]) + .await + .expect_err("the queue is held"); assert_eq!(ra_rpc::code_of(&err), Some(503)); - assert_eq!(probe.calls(), 0); - drop(guard); - state - .identity() - .await - .expect("identity retries immediately"); - assert_eq!(probe.calls(), 1); + drop(held); + state.quote_response([0; 64]).await.unwrap(); } #[tokio::test(start_paused = true)] - async fn concurrent_identity_requests_time_out_within_one_queue_wait() { + async fn identity_callers_wait_at_most_one_queue_timeout() { let probe = Arc::new(InfoAttestationProbe::default()); - let (state, _fixture) = setup_test_state_with_probe(probe.clone()).await; - let _guard = state.inner.attest_lock.lock().await; - - let (first, second) = tokio::time::timeout(Duration::from_secs(16), async { - tokio::join!(state.identity(), state.identity()) - }) - .await - .expect("both callers time out within one 15-second queue wait"); + let (state, _guard) = setup_test_state_with_probe(probe.clone()).await; + let _held = state.inner.attest_lock.lock().await; + let start = tokio::time::Instant::now(); + let (first, second) = tokio::join!(state.identity(), state.identity()); + assert_eq!(start.elapsed(), ATTEST_QUEUE_TIMEOUT); assert_eq!(ra_rpc::code_of(&first.unwrap_err()), Some(503)); - assert_eq!(ra_rpc::code_of(&second.unwrap_err()), Some(503)); + let throttled = second.unwrap_err().to_string(); + assert!(throttled.contains("next attempt"), "{throttled}"); assert_eq!(probe.calls(), 0); } @@ -2528,7 +2420,11 @@ pNs85uhOZE8z2jr8Pg== .expect_err("the platform refuses to attest"); // Age the recorded failure rather than sleeping out the interval. - *state.inner.identity_last_failure.lock().await = Some( + *state + .inner + .identity_last_failure + .lock() + .expect("lock should never fail") = Some( Instant::now() .checked_sub(IDENTITY_RETRY_INTERVAL) .expect("the monotonic clock is older than the throttle window"), diff --git a/dstack/tdx-attest/src/dummy.rs b/dstack/tdx-attest/src/dummy.rs index 60b067ebb8..9dd9ede0e7 100644 --- a/dstack/tdx-attest/src/dummy.rs +++ b/dstack/tdx-attest/src/dummy.rs @@ -8,7 +8,7 @@ use thiserror::Error; -use crate::{Result, TdxReport, TdxReportData}; +use crate::{Result, TdxMeasurements, TdxReport, TdxReportData}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] pub enum TdxAttestError { @@ -50,10 +50,10 @@ pub fn extend_rtmr(_index: u32, _event_type: u32, _digest: [u8; 48]) -> Result<( Err(TdxAttestError::NotSupported) } -pub fn is_tdx_available() -> bool { - false +pub fn read_measurements() -> Result> { + Ok(None) } -pub fn is_report_available() -> bool { +pub fn is_tdx_available() -> bool { false } diff --git a/dstack/tdx-attest/src/lib.rs b/dstack/tdx-attest/src/lib.rs index 8b20497bf8..f8aa966998 100644 --- a/dstack/tdx-attest/src/lib.rs +++ b/dstack/tdx-attest/src/lib.rs @@ -23,45 +23,9 @@ pub type TdxReportData = [u8; 64]; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TdxReport(pub [u8; 1024]); +/// MRTD and RTMR0-3 of the running TD. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct TdxMeasurements { pub mrtd: [u8; 48], pub rtmrs: [[u8; 48]; 4], } - -impl TdxReport { - /// Extract the measurements from the TDINFO section of a TDREPORT0. - pub fn measurements(&self) -> TdxMeasurements { - const MRTD_OFFSET: usize = 512 + 16; // TDINFO starts with ATTRIBUTES and XFAM. - const RTMR0_OFFSET: usize = MRTD_OFFSET + 4 * 48; // After MRTD and three owner/config hashes. - - let digest_at = |offset| { - let mut digest = [0; 48]; - let bytes = &self.0[offset..offset + digest.len()]; - digest.copy_from_slice(bytes); - digest - }; - TdxMeasurements { - mrtd: digest_at(MRTD_OFFSET), - rtmrs: std::array::from_fn(|index| digest_at(RTMR0_OFFSET + index * 48)), - } - } -} - -#[cfg(test)] -mod tests { - use super::TdxReport; - - #[test] - fn extracts_the_tdinfo_measurements() { - let mut bytes = [0xff; 1024]; - bytes[528..576].fill(1); - bytes[720..768].fill(2); - bytes[768..816].fill(3); - bytes[816..864].fill(4); - bytes[864..912].fill(5); - - let measurements = TdxReport(bytes).measurements(); - assert_eq!(measurements.mrtd, [1; 48]); - assert_eq!(measurements.rtmrs, [[2; 48], [3; 48], [4; 48], [5; 48]]); - } -} diff --git a/dstack/tdx-attest/src/linux.rs b/dstack/tdx-attest/src/linux.rs index df0327874f..badc0928d0 100644 --- a/dstack/tdx-attest/src/linux.rs +++ b/dstack/tdx-attest/src/linux.rs @@ -23,7 +23,7 @@ use std::time::{Duration, Instant}; use thiserror::Error; -use crate::{Result, TdxReport, TdxReportData}; +use crate::{Result, TdxMeasurements, TdxReport, TdxReportData}; // ============================================================================ // Constants @@ -153,7 +153,7 @@ pub enum TdxAttestError { // Global state // ============================================================================ -/// Serializes quote requests that share a configfs report or use the QGS transport. +/// Global lock for TDX operations - the driver doesn't support concurrent access static TDX_LOCK: Mutex<()> = Mutex::new(()); /// Track if we've already tried to create the configfs directory @@ -216,7 +216,7 @@ fn absolute_env_path(var: &str, value: impl AsRef) -> Result { /// Return whether a TDX guest provider is available through either the legacy /// misc device or the standard TSM report interface. pub fn is_tdx_available() -> bool { - if is_report_available() { + if Path::new(TDX_GUEST_DEVICE).exists() { return true; } @@ -239,20 +239,11 @@ pub fn is_tdx_available() -> bool { .any(|entry| verify_configfs_provider(&entry.path()).unwrap_or(false)) } -/// Return whether the guest exposes the local TDREPORT device. -pub fn is_report_available() -> bool { - Path::new(TDX_GUEST_DEVICE).exists() -} - fn is_vsock_available() -> bool { read_vsock_port().map(|p| p > 0).unwrap_or(false) } /// Get a TDX report for the given report data. -/// -/// The ioctl uses per-call buffers on older kernels and the driver's measurement -/// lock on newer kernels. Configfs releases that lock before waiting for the quote, -/// and the vsock path completes this ioctl before contacting QGS. pub fn get_report(report_data: &TdxReportData) -> Result { let file = OpenOptions::new() .read(true) @@ -318,6 +309,30 @@ fn rtmr_sysfs_base() -> Result> { .then(|| PathBuf::from(RTMR_SYSFS_BASE))) } +/// Read MRTD and RTMR0-3 from the kernel's TSM measurement sysfs, or `None` on +/// kernels without it. +pub fn read_measurements() -> Result> { + let Some(base) = rtmr_sysfs_base()? else { + return Ok(None); + }; + let read = |name: &str| -> Result<[u8; 48]> { + let path = base.join(format!("{name}:sha384")); + fs::read(&path) + .map_err(|e| TdxAttestError::DeviceFailure(format!("read {}: {e}", path.display())))? + .try_into() + .map_err(|_| TdxAttestError::DeviceFailure(format!("{}: not 48 bytes", path.display()))) + }; + Ok(Some(TdxMeasurements { + mrtd: read("mrtd")?, + rtmrs: [ + read("rtmr0")?, + read("rtmr1")?, + read("rtmr2")?, + read("rtmr3")?, + ], + })) +} + fn extend_rtmr_via_sysfs(base: &Path, index: u32, digest: &[u8; 48]) -> Result<()> { let path = base.join(format!("rtmr{index}:sha384")); From 44b1d9b745b41911ad60f7ec1f4b4e49dae21638 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Fri, 27 Nov 2026 00:57:47 -0800 Subject: [PATCH 3/3] fix(tdx-attest): read Info measurements only from the kernel sysfs The TEE simulator sets DCAP_TDX_RTMR_SYSFS_PATH to its own measurements directory, which has rtmr0-3 but no mrtd. Following that override made read_measurements() fail there, so legacy Info errored in the TDX simulator, and in the SEV-SNP and Nitro simulators, where the directory does not exist at all. Read only the kernel's tdx_guest/measurements path. Simulated guests do not have it and fall back to reading the measurements from a quote, as before. Signed-off-by: Kevin Wang --- dstack/tdx-attest/src/linux.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/dstack/tdx-attest/src/linux.rs b/dstack/tdx-attest/src/linux.rs index badc0928d0..66d4d1a944 100644 --- a/dstack/tdx-attest/src/linux.rs +++ b/dstack/tdx-attest/src/linux.rs @@ -311,10 +311,15 @@ fn rtmr_sysfs_base() -> Result> { /// Read MRTD and RTMR0-3 from the kernel's TSM measurement sysfs, or `None` on /// kernels without it. +/// +/// Unlike [`extend_rtmr`], this ignores `DCAP_TDX_RTMR_SYSFS_PATH`: the TEE +/// simulator points it at a directory without `mrtd`, and callers there can +/// read the measurements from a quote instead. pub fn read_measurements() -> Result> { - let Some(base) = rtmr_sysfs_base()? else { + let base = Path::new(RTMR_SYSFS_BASE); + if !base.is_dir() { return Ok(None); - }; + } let read = |name: &str| -> Result<[u8; 48]> { let path = base.join(format!("{name}:sha384")); fs::read(&path)