From e700c77cd66cca5e8bb68f85280b85cac00daaf4 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:43:43 +0000 Subject: [PATCH 01/12] fix(sev-snp): accept version 5 attestation reports SEV-SNP firmware 1.58 and later returns version 5 attestation reports, which put LAUNCH_MIT_VECTOR and CURRENT_MIT_VECTOR in bytes that sev 6.0.0 parses as reserved and requires to be zero. On such hosts every report fails to parse ("Skipped bytes were expected to be zeroed"), so an SNP guest stops at boot when it reads its HOST_DATA, and the KMS cannot verify SNP guests. Bump sev to 6.3.0, which parses and re-serializes version 5 reports, and let sev-snp-qvl verify versions 3 to 5: it rejected anything newer than 3, and the fields it reads are laid out the same in version 5. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/Cargo.lock | 84 ++++++++----------- dstack/Cargo.toml | 2 +- dstack/crates/mock-attestation/src/sev_snp.rs | 17 ++-- dstack/sev-snp-qvl/src/lib.rs | 23 ++++- 4 files changed, 66 insertions(+), 60 deletions(-) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 6b4dae1d2..0c01edef4 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -597,9 +597,23 @@ dependencies = [ [[package]] name = "bitfield" -version = "0.15.0" +version = "0.19.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c821a6e124197eb56d907ccc2188eab1038fb919c914f47976e64dd8dbc855d1" +checksum = "b45721c9db4c7a20899d05efb7ad9235f50b256e980db30ffb229abf732934c3" +dependencies = [ + "bitfield-macros", +] + +[[package]] +name = "bitfield-macros" +version = "0.19.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0cb6f3d4773a2107b94cbeccaa5b5f0b35a88389b5d522d13d659f64317b22d" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] [[package]] name = "bitflags" @@ -1818,34 +1832,13 @@ dependencies = [ "ctutils", ] -[[package]] -name = "dirs" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" -dependencies = [ - "dirs-sys 0.4.1", -] - [[package]] name = "dirs" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ - "dirs-sys 0.5.0", -] - -[[package]] -name = "dirs-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" -dependencies = [ - "libc", - "option-ext", - "redox_users 0.4.6", - "windows-sys 0.48.0", + "dirs-sys", ] [[package]] @@ -1856,7 +1849,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users 0.5.2", + "redox_users", "windows-sys 0.61.2", ] @@ -2563,7 +2556,7 @@ dependencies = [ "bon", "clap", "dcap-qvl", - "dirs 6.0.0", + "dirs", "dstack-api-auth", "dstack-build-info", "dstack-kms-rpc", @@ -6297,17 +6290,6 @@ dependencies = [ "bitflags 2.11.1", ] -[[package]] -name = "redox_users" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" -dependencies = [ - "getrandom 0.2.17", - "libredox", - "thiserror 1.0.69", -] - [[package]] name = "redox_users" version = "0.5.2" @@ -7404,17 +7386,17 @@ dependencies = [ [[package]] name = "sev" -version = "6.0.0" +version = "6.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20ac277517d8fffdf3c41096323ed705b3a7c75e397129c072fb448339839d0f" +checksum = "d295a3e215c5c2a7d16bebd55c29e6e379599287846c5f9c6e7ef7e334383ced" dependencies = [ "base64 0.22.1", "bincode 1.3.3", "bitfield", - "bitflags 1.3.2", + "bitflags 2.11.1", "byteorder", "codicon", - "dirs 5.0.1", + "dirs", "hex", "iocuddle", "lazy_static", @@ -7867,6 +7849,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -9179,15 +9172,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - [[package]] name = "windows-sys" version = "0.52.0" diff --git a/dstack/Cargo.toml b/dstack/Cargo.toml index 75e20bdba..24c85f247 100644 --- a/dstack/Cargo.toml +++ b/dstack/Cargo.toml @@ -180,7 +180,7 @@ hpke = { version = "0.15.1", default-features = false, features = ["alloc", "get hex-literal = "1.0.0" prost = "0.13.5" prost-types = "0.13.5" -sev = { version = "=6.0.0", default-features = false, features = ["snp", "crypto_nossl"] } +sev = { version = "=6.3.0", default-features = false, features = ["snp", "crypto_nossl"] } scale = { version = "3.7.4", package = "parity-scale-codec", features = [ "derive", ] } diff --git a/dstack/crates/mock-attestation/src/sev_snp.rs b/dstack/crates/mock-attestation/src/sev_snp.rs index edcbc659d..940fde983 100644 --- a/dstack/crates/mock-attestation/src/sev_snp.rs +++ b/dstack/crates/mock-attestation/src/sev_snp.rs @@ -129,13 +129,16 @@ impl SevSnpGenerator { measurement: [u8; 48], ) -> Result { let mut encoded = Vec::new(); - AttestationReport::default().write_bytes(&mut encoded)?; - encoded[0..4].copy_from_slice(&2u32.to_le_bytes()); - encoded[52..56].copy_from_slice(&1u32.to_le_bytes()); - encoded[0x50..0x90].copy_from_slice(&report_data); - encoded[0x90..0xc0].copy_from_slice(&measurement); - encoded[0xc0..0xe0].copy_from_slice(&host_data); - encoded[0x1a0..0x1e0].copy_from_slice(&CHIP_ID); + let mut report = AttestationReport { + version: 2, + sig_algo: 1, + ..Default::default() + }; + *report.report_data = report_data; + *report.measurement = measurement; + *report.host_data = host_data; + *report.chip_id = CHIP_ID; + report.write_bytes(&mut encoded)?; self.sign(&mut encoded)?; Ok(SevSnpEvidence { report: encoded, diff --git a/dstack/sev-snp-qvl/src/lib.rs b/dstack/sev-snp-qvl/src/lib.rs index 128bbc104..7b0449d47 100644 --- a/dstack/sev-snp-qvl/src/lib.rs +++ b/dstack/sev-snp-qvl/src/lib.rs @@ -1098,7 +1098,9 @@ fn amd_snp_product_candidates_for_report(report: &AttestationReport) -> Result Result> { match report.version { 2 => return Ok(None), - 3 => {} + // v5 (firmware 1.58+) adds the mitigation vectors; the fields used + // here are laid out as in v3. + 3..=5 => {} version => bail!("unsupported amd sev-snp report version: {version}"), } @@ -1216,7 +1218,7 @@ fn parse_certificate(cert: &CertBytes, name: &str) -> Result { } fn validate_amd_snp_report_policy(report: &AttestationReport) -> Result<()> { - if !matches!(report.version, 2 | 3) { + if !matches!(report.version, 2..=5) { bail!("unsupported amd sev-snp report version: {}", report.version); } if report.vmpl != 0 { @@ -1903,6 +1905,23 @@ mod tests { validate_amd_snp_report_policy(&report).unwrap(); } + #[test] + fn report_v5_is_accepted_and_newer_versions_are_not() { + let mut report = base_report(); + report.version = 5; + report.cpuid_fam_id = Some(0x1a); + report.cpuid_mod_id = Some(0x02); + validate_amd_snp_report_policy(&report).unwrap(); + assert_eq!( + amd_snp_product_candidates_for_report(&report).unwrap(), + vec![AmdSnpProduct::Turin] + ); + + report.version = 6; + assert!(validate_amd_snp_report_policy(&report).is_err()); + assert!(amd_snp_product_candidates_for_report(&report).is_err()); + } + fn base_report() -> AttestationReport { AttestationReport { version: 2, From ec2f3d487e43dcc1e429f55196e1af0132e86c80 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:42:53 +0000 Subject: [PATCH 02/12] fix(dstackup): write WorkingDirectory as a bare path in unit files systemd does not unquote `WorkingDirectory=`, so the quoted value dstackup wrote is read as a relative path. systemd 259 rejects it ("path is not absolute"), and `dstackup install` then fails to start dstack-auth. Write the path bare, escaping only `%`. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstackup/src/systemd.rs | 30 +++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/dstack/crates/dstackup/src/systemd.rs b/dstack/crates/dstackup/src/systemd.rs index 974521e43..9c2142d76 100644 --- a/dstack/crates/dstackup/src/systemd.rs +++ b/dstack/crates/dstackup/src/systemd.rs @@ -68,7 +68,7 @@ pub(crate) fn auth_unit_file(bin: &str, allowlist: &Path, port: u16, prefix: &Pa [Install]\nWantedBy=multi-user.target\n", bin = systemd_arg(bin), cfg = systemd_arg(&allowlist.display().to_string()), - wd = systemd_arg(&prefix.display().to_string()), + wd = systemd_path(&prefix.display().to_string()), ) } @@ -83,10 +83,16 @@ pub(crate) fn vmm_unit_file(bin: &str, config: &Path, prefix: &Path, auth_unit: auth = auth_unit, bin = systemd_arg(bin), cfg = systemd_arg(&config.display().to_string()), - wd = systemd_arg(&prefix.display().to_string()), + wd = systemd_path(&prefix.display().to_string()), ) } +/// `WorkingDirectory=` takes a bare absolute path; systemd does not unquote it +/// (systemd 259 rejects a quoted value as "path is not absolute"). +fn systemd_path(value: &str) -> String { + value.replace('%', "%%") +} + fn systemd_arg(value: &str) -> String { let mut out = String::with_capacity(value.len() + 2); out.push('"'); @@ -109,6 +115,26 @@ fn systemd_arg(value: &str) -> String { mod tests { use super::*; + #[test] + fn working_directory_is_a_bare_path() { + let prefix = Path::new("/var/lib/dstack"); + for unit in [ + auth_unit_file("/bin/auth", Path::new("/etc/a.json"), 8001, prefix), + vmm_unit_file( + "/bin/vmm", + Path::new("/etc/vmm.toml"), + prefix, + "dstack-auth", + ), + ] { + assert!( + unit.contains("\nWorkingDirectory=/var/lib/dstack\n"), + "{unit}" + ); + } + assert_eq!(systemd_path("/srv/100%"), "/srv/100%%"); + } + #[test] fn systemd_arg_quotes_paths_and_escapes_specifiers() { assert_eq!( From 61645d8468586d6b797c595d22f91534f075043b Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:43:10 +0000 Subject: [PATCH 03/12] fix(dstackup): load vhost_vsock before starting the VMM The VMM host API binds vsock CID 2, which needs the vhost_vsock transport. /dev/vhost-vsock is a static device node that loads the module only on first open, so on a fresh host the bind fails with EADDRNOTAVAIL and the VMM exits ("Failed to bind host API"). Load the module in ExecStartPre. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstackup/src/systemd.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/dstack/crates/dstackup/src/systemd.rs b/dstack/crates/dstackup/src/systemd.rs index 9c2142d76..f35006222 100644 --- a/dstack/crates/dstackup/src/systemd.rs +++ b/dstack/crates/dstackup/src/systemd.rs @@ -75,9 +75,13 @@ pub(crate) fn auth_unit_file(bin: &str, allowlist: &Path, port: u16, prefix: &Pa pub(crate) fn vmm_unit_file(bin: &str, config: &Path, prefix: &Path, auth_unit: &str) -> String { // KillMode defaults to control-group, so `systemctl stop` tears down the // VMM + supervisor + CVM qemus together (deterministic teardown). + // + // The host API listens on vsock CID 2, which only exists once the + // vhost_vsock transport is loaded. /dev/vhost-vsock is a static device node + // that loads the module on first open, so it can exist without the module. format!( "[Unit]\nDescription=dstack VMM\nAfter=network.target docker.service {auth}.service\nWants={auth}.service\n\n\ - [Service]\nExecStart={bin} -c {cfg}\nRestart=always\nRestartSec=2\n\ + [Service]\nExecStartPre=/sbin/modprobe vhost_vsock\nExecStart={bin} -c {cfg}\nRestart=always\nRestartSec=2\n\ TimeoutStopSec=120\nWorkingDirectory={wd}\n\n\ [Install]\nWantedBy=multi-user.target\n", auth = auth_unit, @@ -135,6 +139,15 @@ mod tests { assert_eq!(systemd_path("/srv/100%"), "/srv/100%%"); } + #[test] + fn vmm_unit_loads_vhost_vsock_first() { + let unit = vmm_unit_file("/bin/vmm", Path::new("/etc/vmm.toml"), Path::new("/d"), "a"); + let pre = unit + .find("ExecStartPre=/sbin/modprobe vhost_vsock\n") + .unwrap(); + assert!(pre < unit.find("ExecStart=").unwrap()); + } + #[test] fn systemd_arg_quotes_paths_and_escapes_specifiers() { assert_eq!( From c14be63a9f88ebda0b203bde7f0c5b0fa0866c95 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:41:22 +0000 Subject: [PATCH 04/12] fix(dstackup): find mkosi-os-v guest-OS releases Guest-OS releases are tagged `mkosi-os-v` by the mkosi release workflow, but `dstackup image pull` only looked for `guest-os-v`, so both a pinned `--version` and the latest-release lookup found nothing for 0.6.x. Look up `mkosi-os-v` first and keep `guest-os-v` as a fallback. These releases also publish `dstack--kernel-devel.tar.gz`, which the asset picker accepted as a host image; skip it like the `-uki` archive. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstackup/src/image.rs | 130 ++++++++++++++++++---------- 1 file changed, 86 insertions(+), 44 deletions(-) diff --git a/dstack/crates/dstackup/src/image.rs b/dstack/crates/dstackup/src/image.rs index 91293b645..b1148bdf5 100644 --- a/dstack/crates/dstackup/src/image.rs +++ b/dstack/crates/dstackup/src/image.rs @@ -4,7 +4,7 @@ //! `dstackup image` — fetch, list, and remove guest OS images. //! -//! Images are published as `guest-os-v*` release tarballs in the dstack +//! Images are published as `mkosi-os-v*` release tarballs in the dstack //! monorepo. Current releases use one hardware-adaptive `dstack-` image; //! legacy releases may also contain `dstack-nvidia-` variants. //! `install` validates the selected image against `digest.txt`, the OS image @@ -25,8 +25,10 @@ use std::time::SystemTime; const REPO: &str = "Dstack-TEE/dstack"; const LEGACY_REPO: &str = "Dstack-TEE/meta-dstack"; -const RELEASE_TAG_PREFIX: &str = "guest-os-v"; -pub(crate) const RELEASES_URL: &str = "https://github.com/Dstack-TEE/dstack/releases?q=guest-os-v"; +/// Tag prefixes of monorepo guest-OS releases. The mkosi release workflow tags +/// them `mkosi-os-v`; `guest-os-v` is still accepted. +const RELEASE_TAG_PREFIXES: [&str; 2] = ["mkosi-os-v", "guest-os-v"]; +pub(crate) const RELEASES_URL: &str = "https://github.com/Dstack-TEE/dstack/releases?q=mkosi-os-v"; const LEGACY_RELEASES_URL: &str = "https://github.com/Dstack-TEE/meta-dstack/releases"; const MONOREPO_GUEST_OS_MIN_VERSION: (u64, u64, u64) = (0, 6, 0); @@ -620,12 +622,13 @@ fn missing_named_image_message(image_dir: &str, name: &str) -> String { async fn fetch_release(version: Option<&str>, release_api_base_url: &str) -> Result { let client = reqwest::Client::new(); if let Some(version) = version { - let (version, url, releases_url) = tagged_release_location(version, release_api_base_url)?; - return fetch_tagged_release(&client, &url, releases_url) - .await? - .with_context(|| { - format!("guest-OS version {version} was not found; check {releases_url}") - }); + let (version, urls, releases_url) = tagged_release_location(version, release_api_base_url)?; + for url in &urls { + if let Some(release) = fetch_tagged_release(&client, url, releases_url).await? { + return Ok(release); + } + } + bail!("guest-OS version {version} was not found; check {releases_url}"); } let api_base = release_api_base_url.trim().trim_end_matches('/'); @@ -642,10 +645,11 @@ async fn fetch_release(version: Option<&str>, release_api_base_url: &str) -> Res .json() .await .context("parsing dstack release list")?; - if let Some(release) = releases - .into_iter() - .find(|release| release.tag_name.starts_with(RELEASE_TAG_PREFIX)) - { + if let Some(release) = releases.into_iter().find(|release| { + RELEASE_TAG_PREFIXES + .iter() + .any(|prefix| release.tag_name.starts_with(prefix)) + }) { return Ok(release); } @@ -655,27 +659,33 @@ async fn fetch_release(version: Option<&str>, release_api_base_url: &str) -> Res .with_context(|| format!("no guest-OS release found; check {RELEASES_URL}")) } +/// The release lookup URLs for a pinned version, in the order to try them. fn tagged_release_location( version: &str, release_api_base_url: &str, -) -> Result<(String, String, &'static str)> { - let version = version - .trim_start_matches(RELEASE_TAG_PREFIX) +) -> Result<(String, Vec, &'static str)> { + let version = RELEASE_TAG_PREFIXES + .iter() + .find_map(|prefix| version.strip_prefix(prefix)) + .unwrap_or(version) .trim_start_matches('v'); let core = numeric_version_core(version)?; - let (repo, tag_prefix, releases_url) = if core < MONOREPO_GUEST_OS_MIN_VERSION { - (LEGACY_REPO, "v", LEGACY_RELEASES_URL) + let api_base = release_api_base_url.trim().trim_end_matches('/'); + let (urls, releases_url) = if core < MONOREPO_GUEST_OS_MIN_VERSION { + ( + vec![format!("{api_base}/{LEGACY_REPO}/releases/tags/v{version}")], + LEGACY_RELEASES_URL, + ) } else { - (REPO, RELEASE_TAG_PREFIX, RELEASES_URL) + ( + RELEASE_TAG_PREFIXES + .iter() + .map(|prefix| format!("{api_base}/{REPO}/releases/tags/{prefix}{version}")) + .collect(), + RELEASES_URL, + ) }; - Ok(( - version.to_string(), - format!( - "{}/{repo}/releases/tags/{tag_prefix}{version}", - release_api_base_url.trim().trim_end_matches('/') - ), - releases_url, - )) + Ok((version.to_string(), urls, releases_url)) } fn numeric_version_core(version: &str) -> Result<(u64, u64, u64)> { @@ -721,7 +731,8 @@ async fn fetch_tagged_release( )) } -/// Pick a full bare-metal image tarball, never the `-uki` archive. For a GPU +/// Pick a full bare-metal image tarball, never the `-uki` or `-kernel-devel` +/// archive. For a GPU /// request, prefer a legacy `dstack-nvidia-*` asset when present and otherwise /// use the current unified image (which already contains conditional NVIDIA /// support). @@ -734,7 +745,11 @@ fn pick_asset(assets: &[Asset], gpu: bool) -> Option<&Asset> { |n: &str| n.starts_with("dstack-dev-") || n.starts_with("dstack-nvidia-dev-"); let matches = |a: &&Asset, want_legacy_gpu: bool| { let n = a.name.as_str(); - if !n.ends_with(".tar.gz") || n.ends_with("-uki.tar.gz") || is_dev_flavour(n) { + if !n.ends_with(".tar.gz") + || n.ends_with("-uki.tar.gz") + || n.ends_with("-kernel-devel.tar.gz") + || is_dev_flavour(n) + { return false; } let is_gpu = n.starts_with("dstack-nvidia-"); @@ -893,28 +908,55 @@ mod tests { assert!(pick_asset(&assets, true).is_none()); } + #[test] + fn kernel_devel_archive_is_never_selected_as_a_host_image() { + let assets = vec![ + asset("dstack-0.6.5-kernel-devel.tar.gz"), + asset("dstack-0.6.5-uki.tar.gz"), + asset("dstack-0.6.5.tar.gz"), + ]; + assert_eq!( + pick_asset(&assets, false).map(|a| a.name.as_str()), + Some("dstack-0.6.5.tar.gz") + ); + assert_eq!( + pick_asset(&assets, true).map(|a| a.name.as_str()), + Some("dstack-0.6.5.tar.gz") + ); + } + #[test] fn routes_pinned_releases_at_the_monorepo_boundary() { - for version in ["0.5.11", "v0.5.11", "guest-os-v0.5.11"] { - let (normalized, url, releases_url) = + for version in ["0.5.11", "v0.5.11", "guest-os-v0.5.11", "mkosi-os-v0.5.11"] { + let (normalized, urls, releases_url) = tagged_release_location(version, crate::cli::DEFAULT_RELEASE_API_BASE_URL).unwrap(); assert_eq!(normalized, "0.5.11"); assert_eq!( - url, - "https://api.github.com/repos/Dstack-TEE/meta-dstack/releases/tags/v0.5.11" + urls, + ["https://api.github.com/repos/Dstack-TEE/meta-dstack/releases/tags/v0.5.11"] ); assert_eq!(releases_url, LEGACY_RELEASES_URL); } for version in ["0.6.0", "0.6.0.a2", "1.0.0"] { - let (normalized, url, releases_url) = - tagged_release_location(version, crate::cli::DEFAULT_RELEASE_API_BASE_URL).unwrap(); - assert_eq!(normalized, version); - assert_eq!( - url, - format!("https://api.github.com/repos/Dstack-TEE/dstack/releases/tags/guest-os-v{version}") - ); - assert_eq!(releases_url, RELEASES_URL); + for input in [ + version.to_string(), + format!("mkosi-os-v{version}"), + format!("guest-os-v{version}"), + ] { + let (normalized, urls, releases_url) = + tagged_release_location(&input, crate::cli::DEFAULT_RELEASE_API_BASE_URL) + .unwrap(); + assert_eq!(normalized, version); + assert_eq!( + urls, + [ + format!("https://api.github.com/repos/Dstack-TEE/dstack/releases/tags/mkosi-os-v{version}"), + format!("https://api.github.com/repos/Dstack-TEE/dstack/releases/tags/guest-os-v{version}"), + ] + ); + assert_eq!(releases_url, RELEASES_URL); + } } } @@ -930,11 +972,11 @@ mod tests { #[test] fn release_api_base_url_is_configurable_and_trailing_slash_safe() { - let (_, url, _) = + let (_, urls, _) = tagged_release_location("0.6.0", " http://127.0.0.1:1234/api/ ").unwrap(); assert_eq!( - url, - "http://127.0.0.1:1234/api/Dstack-TEE/dstack/releases/tags/guest-os-v0.6.0" + urls[0], + "http://127.0.0.1:1234/api/Dstack-TEE/dstack/releases/tags/mkosi-os-v0.6.0" ); } From b41c1a13feeddab703cace82bc325afb9b087a57 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:42:35 +0000 Subject: [PATCH 05/12] fix(dstack-cli): pick auto host ports inside the VMM port-mapping range `free_local_port()` bound port 0, which returns a kernel ephemeral port (32768 and up). The vmm.toml that `dstackup install` writes only allows tcp 1-20000, so the VMM refused every auto-picked port: the KMS CVM deploy in `dstackup install` failed with "Port mapping is not allowed", and so did `dstack deploy --port ` without a host port. Pick a free loopback port from 10000-19999 instead, and test that the rendered port-mapping range covers it. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstack-cli-core/src/config.rs | 17 +++++++++++ dstack/crates/dstack-cli-core/src/ports.rs | 33 ++++++++++++++++++--- 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index d2f832bce..7ceecaf3d 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -482,6 +482,23 @@ mod tests { toml::from_str::(&rendered).expect("vmm.toml must be valid TOML"); } + #[test] + fn vmm_toml_port_mapping_allows_auto_picked_host_ports() { + let rendered: toml::Value = toml::from_str(&vmm_toml(&VmmRender::default())).unwrap(); + let ranges = rendered["cvm"]["port_mapping"]["range"].as_array().unwrap(); + let covered = ranges.iter().any(|r| { + r["protocol"].as_str() == Some("tcp") + && r["from"].as_integer().unwrap() + <= i64::from(*crate::ports::AUTO_HOST_PORT_RANGE.start()) + && r["to"].as_integer().unwrap() + >= i64::from(*crate::ports::AUTO_HOST_PORT_RANGE.end()) + }); + assert!( + covered, + "port_mapping must cover ports::AUTO_HOST_PORT_RANGE" + ); + } + #[test] fn vmm_toml_auth_disabled_renders_empty_tokens() { let rendered = vmm_toml(&VmmRender::default()); diff --git a/dstack/crates/dstack-cli-core/src/ports.rs b/dstack/crates/dstack-cli-core/src/ports.rs index 142be1b16..16241918a 100644 --- a/dstack/crates/dstack-cli-core/src/ports.rs +++ b/dstack/crates/dstack-cli-core/src/ports.rs @@ -8,15 +8,32 @@ use anyhow::{bail, Context, Result}; use dstack_vmm_rpc::PortMapping; use std::net::TcpListener; +use std::ops::RangeInclusive; +use std::time::{SystemTime, UNIX_EPOCH}; -/// pick a currently-free TCP port on loopback by binding to port 0. +/// host ports handed out when the caller does not choose one. The range sits +/// below the Linux ephemeral range and inside the port-mapping allowlist that +/// `dstackup install` writes to vmm.toml (tcp 1-20000). A port from binding +/// port 0 is ephemeral, so the VMM would refuse to map it. +pub const AUTO_HOST_PORT_RANGE: RangeInclusive = 10000..=19999; + +/// pick a currently-free TCP port on loopback from [`AUTO_HOST_PORT_RANGE`]. /// /// inherently racy (the port could be taken before the VMM binds it), but fine /// for a single interactive deploy; the VMM will surface a bind conflict. pub fn free_local_port() -> Result { - let listener = TcpListener::bind("127.0.0.1:0").context("failed to find a free host port")?; - let port = listener.local_addr()?.port(); - Ok(port) + let (first, last) = (*AUTO_HOST_PORT_RANGE.start(), *AUTO_HOST_PORT_RANGE.end()); + let len = u32::from(last - first) + 1; + // start the scan at a varying offset so back-to-back picks spread out + let seed = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0) + ^ std::process::id(); + (0..len) + .map(|i| first + (seed.wrapping_add(i) % len) as u16) + .find(|&port| tcp_port_free("127.0.0.1", port)) + .with_context(|| format!("failed to find a free host port in {first}-{last}")) } /// whether `addr:port` can be bound right now. Best-effort and racy, but it @@ -94,6 +111,14 @@ fn parse_port_number(value: &str, label: &str, spec: &str) -> Result { mod tests { use super::*; + #[test] + fn auto_host_ports_come_from_the_auto_range() { + let port = free_local_port().unwrap(); + assert!(AUTO_HOST_PORT_RANGE.contains(&port), "{port}"); + let mapping = parse_port("80").unwrap(); + assert!(AUTO_HOST_PORT_RANGE.contains(&(mapping.host_port as u16))); + } + #[test] fn parses_fixed_direct_host_mapping() { let p = parse_port("8080:80").unwrap(); From 3756c18163fdf1ac1a7c620bce1c91ce7f6cbb92 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:52:15 +0000 Subject: [PATCH 06/12] fix(dstackup): render the KMS 0.6 listener layout dstackup wrote kms.toml with the listener settings at their pre-0.6 locations ([rpc], [core.admin], core.onboard.address/port), had no core.keyring_dir, and deployed KMS 0.5.11 by default. The 0.6 KMS refuses that config at startup ("the config sets listener settings at their old locations", and keyring_dir has no default), and 0.5.11 has no SEV-SNP support, so a dstackup install on an SNP host never gets a working KMS. Render [listeners.default.tls], [listeners.guest], [listeners.admin] and [listeners.onboard], put the keyring on the persistent KMS volume (/kms/keyring), and default to the 0.6.7 KMS image, which reads that layout. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstack-cli-core/src/config.rs | 57 +++++++++++++-------- 1 file changed, 35 insertions(+), 22 deletions(-) diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index 7ceecaf3d..0973fdd9f 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -123,16 +123,29 @@ pub fn kms_toml(cfg: &HostConfig) -> String { format!( r#"# generated by `dstackup install` — single-node KMS -[rpc] +[listeners.default.tls] +key = "/kms/certs/rpc.key" +certs = "/kms/certs/rpc.crt" + +[listeners.guest] address = "0.0.0.0" port = 8000 -[rpc.tls] -key = "/kms/certs/rpc.key" -certs = "/kms/certs/rpc.crt" +# the key handover path a serving KMS requires; the token stays on the host. +[listeners.admin] +enabled = true +address = "127.0.0.1" +port = 8001 +auth_token_hash = "{admin_token_hash}" + +[listeners.onboard] +address = "0.0.0.0" +port = 8000 [core] cert_dir = "/kms/certs" +# the root keys of every epoch; on the persistent kms-volume. +keyring_dir = "/kms/keyring" # single-node: the KMS does not self-attest to its own auth API before # bootstrap (it still attests the genesis keys via the guest agent, and app # auth + per-app quote checks are unaffected). @@ -152,22 +165,9 @@ type = "webhook" [core.auth_api.webhook] url = "{webhook_url}" -# the key handover path a serving KMS requires; the token stays on the host. -[core.admin] -enabled = true -address = "127.0.0.1" -port = 8001 -auth_token_hash = "{admin_token_hash}" - -[core.admin.tls] -key = "/kms/certs/rpc.key" -certs = "/kms/certs/rpc.crt" - [core.onboard] enabled = true auto_bootstrap_domain = "{bootstrap_domain}" -address = "0.0.0.0" -port = 8000 "#, // AMD SEV-SNP gates EVERY key release (incl. the KMS's own bootstrap) on // `sev_snp_key_release`, which defaults to false — so it must be set on @@ -207,8 +207,8 @@ pub fn auth_allowlist_json(cfg: &HostConfig) -> String { } /// default reproducibly-built KMS image, digest-pinned since it is measured into the -/// compose hash. -pub const DEFAULT_KMS_IMAGE: &str = "dstacktee/dstack-kms:0.5.11@sha256:84b793feed825a5b5e70d04386e931e0e110461492793f17ab2128e39808d989"; +/// compose hash. It has to read the `[listeners.*]` layout `kms_toml` renders. +pub const DEFAULT_KMS_IMAGE: &str = "ghcr.io/dstack-tee/dstack-kms:0.6.7@sha256:693b7c80bad6f759a17f3cc62503eb1ef768852527d448dcfbbb9edb3e8f99f3"; /// Build the KMS app-compose manifest with an embedded `kms.toml` init script. /// Select SGX local provisioning on TDX and native SNP provisioning on AMD. @@ -519,14 +519,27 @@ mod tests { let toml = kms_toml(&cfg); assert!(toml.contains("enforce_self_authorization = false")); let v: toml::Value = toml::from_str(&toml).unwrap(); - let admin = &v["core"]["admin"]; + // the 0.6 KMS refuses to start on listener settings at their old + // locations: [rpc], [core.admin], core.onboard.address/port. + let top: Vec<&String> = v.as_table().unwrap().keys().collect(); + assert_eq!(top, ["core", "listeners"]); + assert!(v["core"].get("admin").is_none()); + assert!(v["core"]["onboard"].get("address").is_none()); + assert!(v["core"]["onboard"].get("port").is_none()); + let listeners = &v["listeners"]; + assert_eq!(listeners["guest"]["port"].as_integer(), Some(8000)); + let admin = &listeners["admin"]; assert_eq!(admin["enabled"].as_bool(), Some(true)); + assert_eq!(admin["address"].as_str(), Some("127.0.0.1")); assert_eq!( admin["auth_token_hash"].as_str(), Some("ab".repeat(32).as_str()) ); - assert_eq!(admin["tls"]["key"].as_str(), Some("/kms/certs/rpc.key")); - assert_eq!(admin["tls"]["certs"].as_str(), Some("/kms/certs/rpc.crt")); + let tls = &listeners["default"]["tls"]; + assert_eq!(tls["key"].as_str(), Some("/kms/certs/rpc.key")); + assert_eq!(tls["certs"].as_str(), Some("/kms/certs/rpc.crt")); + // required, with no default, so the root keys land on the kms-volume. + assert_eq!(v["core"]["keyring_dir"].as_str(), Some("/kms/keyring")); assert!(toml.contains(r#"auto_bootstrap_domain = "10.0.2.2""#)); assert!(toml.contains(r#"type = "webhook""#)); assert!(toml.contains(r#"url = "http://10.0.2.2:8001""#)); From e982c8d76e2d432d3861d7010d71c83c33a9101f Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:34:04 +0000 Subject: [PATCH 07/12] fix(vmm): give SEV-SNP guests the host's physical address width SEV-SNP guests run with `-cpu EPYC-v4`. A named CPU model gets QEMU's default of 40 physical address bits, so the guest has 1 TiB of address space and OVMF sizes its 64-bit PCI MMIO window from that. GPUs with large BARs (a B200 BAR1 is 256 GiB) then cannot be mapped. TDX guests use `-cpu host`, which already takes the host's width. Pass host-phys-bits=on with the SEV-SNP CPU model. The CPUID page is measured as zeros, so the launch measurement does not change. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/vmm/src/app/qemu.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/dstack/vmm/src/app/qemu.rs b/dstack/vmm/src/app/qemu.rs index 9e8029102..17a07139d 100644 --- a/dstack/vmm/src/app/qemu.rs +++ b/dstack/vmm/src/app/qemu.rs @@ -679,7 +679,11 @@ impl QemuCommandBuilder<'_> { let mut command = Command::new(&self.cfg.qemu_path); command.arg("-accel").arg("kvm"); command.arg("-cpu").arg(if self.is_amd_sev_snp() { - "EPYC-v4" + // A named model gets QEMU's default 40 phys-bits (1 TiB), too small + // for the 64-bit MMIO window of large-BAR GPUs; `-cpu host` (TDX) + // already takes the host's. The CPUID page is not part of the SNP + // launch measurement, so this does not change it. + "EPYC-v4,host-phys-bits=on" } else { "host" }); @@ -1336,6 +1340,32 @@ mod tests { assert_eq!(params.reduced_phys_bits, 1); } + #[test] + fn amd_sev_snp_cpu_takes_host_phys_bits() { + let (config, mut vm, mut prepared) = test_launch_fixture(); + vm.manifest.no_tee = false; + prepared.platform = CvmPlatform::AmdSevSnp; + prepared.snp_host_data = Some("00".repeat(32)); + prepared.snp_launch_params = Some(AmdSevSnpLaunchParams { + cbitpos: 51, + reduced_phys_bits: 1, + }); + + let process = QemuCommandBuilder { + vm: &vm, + cfg: &config.cvm, + gpus: &GpuConfig::default(), + prepared: &prepared, + } + .build() + .unwrap(); + + assert!(process + .args + .windows(2) + .any(|args| args == ["-cpu", "EPYC-v4,host-phys-bits=on"])); + } + #[test] fn amd_sev_snp_uses_confidential_virtio_pci_options() { assert_eq!( From aacfba728e881a8243ca2c66e33d88d021e8c0a8 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:34:36 +0000 Subject: [PATCH 08/12] fix(os): build the SEV-SNP OVMF with 1 GiB page tables PcdUse1GPageTable defaults to FALSE and AmdSevX64.dsc does not set it, so OVMF caps the guest physical address width at 40 bits even when the vCPU reports more. Its dynamic 64-bit PCI MMIO window is then at most 128 GiB, smaller than a single B200 BAR1 (256 GiB), and an SEV-SNP guest cannot map the GPU. Build the AmdSev firmware with PcdUse1GPageTable=TRUE. With 46 physical address bits OVMF then opens an 8 TiB window. This changes ovmf-sev.fd and so the SEV-SNP launch measurement; the TDX firmware is unchanged. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- os/mkosi/components/ovmf/ovmf-build.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/os/mkosi/components/ovmf/ovmf-build.sh b/os/mkosi/components/ovmf/ovmf-build.sh index d365d1ea0..8a8a4bbdf 100755 --- a/os/mkosi/components/ovmf/ovmf-build.sh +++ b/os/mkosi/components/ovmf/ovmf-build.sh @@ -77,9 +77,13 @@ rm -f "$src/Conf/tools_def.txt" build -a X64 -t GCC5 -b RELEASE -n "${JOBS:-$(nproc)}" \ -p OvmfPkg/IntelTdx/IntelTdxX64.dsc) install -Dm0644 "$src/Build/IntelTdx/RELEASE_GCC5/FV/OVMF.fd" "$OUT" +# Without 1 GiB page tables OVMF caps the guest physical address width at 40 +# bits, which limits its 64-bit PCI MMIO window to 128 GiB: too small for +# large-BAR GPUs (a B200 BAR1 is 256 GiB). # shellcheck source=/dev/null (cd "$src" && set +u && source edksetup.sh BaseTools >/dev/null && \ build -a X64 -t GCC5 -b RELEASE -n "${JOBS:-$(nproc)}" \ + --pcd gEfiMdeModulePkgTokenSpaceGuid.PcdUse1GPageTable=TRUE \ -p OvmfPkg/AmdSev/AmdSevX64.dsc) install -Dm0644 "$src/Build/AmdSev/RELEASE_GCC5/FV/OVMF.fd" "$SEV_OUT" touch -d "@${SOURCE_DATE_EPOCH:?}" "$OUT" "$SEV_OUT" From e0f9c3e0799f4b0a77bf1f627bc689f9e47d11c3 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Sun, 22 Nov 2026 20:32:54 +0000 Subject: [PATCH 09/12] fix(volume): share extents when packing a volume Building a volume copied the filesystem image twice: into a scratch file, then into the GPT image through a 1 MiB userspace buffer. For a large image that doubles the disk space and the time. Clone instead with FICLONE / FICLONERANGE: the partitions are 1 MiB aligned and the data and hash images are padded to whole blocks, so XFS and Btrfs share the extents. Fall back to a copy where cloning is not supported. copy_file_range is not used because it does not reliably clone (it did not on Linux 7.0 with XFS). Tested: packing a 1.1 TB squashfs on XFS no longer needs a second 1.1 TB, and the scratch copy completes immediately. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/Cargo.lock | 1 + dstack/crates/dstack-volume/Cargo.toml | 1 + dstack/crates/dstack-volume/src/volume.rs | 65 +++++++++++++++++++---- 3 files changed, 58 insertions(+), 9 deletions(-) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 0c01edef4..2930d790f 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -2640,6 +2640,7 @@ dependencies = [ "fs-err", "gpt", "hex", + "libc", "serde_json", "sha2 0.10.9", "tempfile", diff --git a/dstack/crates/dstack-volume/Cargo.toml b/dstack/crates/dstack-volume/Cargo.toml index 76262b6fe..aff295957 100644 --- a/dstack/crates/dstack-volume/Cargo.toml +++ b/dstack/crates/dstack-volume/Cargo.toml @@ -20,6 +20,7 @@ sha2 = { workspace = true, features = ["std"] } hex = { workspace = true, features = ["std"] } fs-err.workspace = true gpt = "4.1.0" +libc.workspace = true tempfile.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/dstack/crates/dstack-volume/src/volume.rs b/dstack/crates/dstack-volume/src/volume.rs index ba9ee6ac1..d2c1d5b9d 100644 --- a/dstack/crates/dstack-volume/src/volume.rs +++ b/dstack/crates/dstack-volume/src/volume.rs @@ -114,7 +114,7 @@ pub fn build_fs_image(fs_image: &Path, output: &Path, salt_hex: &str) -> Result< let tmp = tempfile::tempdir().context("creating volume scratch dir")?; let data_path = tmp.path().join("data.fs"); - fs::copy(fs_image, &data_path) + clone_or_copy_file(fs_image, &data_path) .with_context(|| format!("copying {} into scratch", fs_image.display()))?; seal_data_image(&data_path, len, output, salt_hex) } @@ -368,21 +368,68 @@ fn write_volume_header(out: &mut fs::File, offset: u64, root_hash: &str) -> Resu Ok(()) } +/// Place `src` in `out` at `offset`. On a filesystem with reflinks (XFS, +/// Btrfs) the extents are shared instead of written again (the partitions are +/// 1 MiB aligned and the inputs are padded to whole blocks), so packing a +/// large directory needs no second copy of it on disk. Elsewhere it copies. fn copy_into(src: &Path, out: &mut fs::File, offset: u64) -> Result<()> { - use std::io::{Read, Seek, SeekFrom, Write}; + use std::io::{Seek, SeekFrom}; let mut input = fs::File::open(src)?; + if clone_range(input.file(), out.file(), offset).is_ok() { + return Ok(()); + } out.seek(SeekFrom::Start(offset))?; - let mut buf = vec![0u8; 1 << 20]; - loop { - let n = input.read(&mut buf)?; - if n == 0 { - break; - } - out.write_all(&buf[..n])?; + std::io::copy(&mut input, out)?; + Ok(()) +} + +/// Copy `src` to a new file `dst`, sharing extents where the filesystem can. +fn clone_or_copy_file(src: &Path, dst: &Path) -> Result<()> { + let input = fs::File::open(src)?; + let output = fs::File::create(dst)?; + if clone_range(input.file(), output.file(), 0).is_ok() { + return Ok(()); } + drop(output); + fs::copy(src, dst)?; Ok(()) } +/// `FICLONERANGE` of all of `src` (`src_length` 0: to its end) into `dst` at +/// `dest_offset`. `copy_file_range` does not reliably reflink (not on Linux +/// 7.0 with XFS), so this asks for the clone explicitly. +#[cfg(target_os = "linux")] +fn clone_range(src: &std::fs::File, dst: &std::fs::File, dest_offset: u64) -> std::io::Result<()> { + use std::os::fd::AsRawFd; + #[repr(C)] + struct FileCloneRange { + src_fd: i64, + src_offset: u64, + src_length: u64, + dest_offset: u64, + } + // _IOW(0x94, 13, struct file_clone_range) + const FICLONERANGE: libc::c_ulong = 0x4020_940d; + let arg = FileCloneRange { + src_fd: src.as_raw_fd() as i64, + src_offset: 0, + src_length: 0, + dest_offset, + }; + // SAFETY: FICLONERANGE reads a file_clone_range, which `arg` is laid out as. + let ret = unsafe { libc::ioctl(dst.as_raw_fd(), FICLONERANGE as _, &arg) }; + if ret == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(not(target_os = "linux"))] +fn clone_range(_: &std::fs::File, _: &std::fs::File, _: u64) -> std::io::Result<()> { + Err(std::io::ErrorKind::Unsupported.into()) +} + fn require_tool(name: &str) -> Result<()> { let present = run_cmd!(which $name >/dev/null 2>&1).is_ok(); if !present { From de12f6a31742e396141c114192af495af471dc7a Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:03:50 +0000 Subject: [PATCH 10/12] fix(vmm): prefer host kms_url when querying SEV-SNP app epoch On SEV-SNP launches with a 0.6.7+ guest image (app_epoch_pin: true), the VMM queries the KMS from the host to resolve the current app epoch before starting QEMU. Under single-node user-mode networking (as configured by dstackup), cvm.kms_urls holds the guest-only 10.0.2.2 alias, which is not routable from the host. When the VM manifest does not override kms_urls, try the host-side top-level kms_url first and fall back to cvm.kms_urls (deduplicated). Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/vmm/src/app/mr_config.rs | 71 ++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/dstack/vmm/src/app/mr_config.rs b/dstack/vmm/src/app/mr_config.rs index 76094891a..8b2a6206b 100644 --- a/dstack/vmm/src/app/mr_config.rs +++ b/dstack/vmm/src/app/mr_config.rs @@ -133,6 +133,28 @@ fn is_snp_launch(manifest: &Manifest, platform: CvmPlatform) -> bool { || (!manifest.no_tee && platform == CvmPlatform::AmdSevSnp) } +/// KMS URLs the VMM tries from the host to resolve the current app epoch. +/// +/// When the VM manifest does not override `kms_urls`, prefer the host-side +/// top-level `config.kms_url` ahead of `config.cvm.kms_urls`: under QEMU +/// user-mode networking `cvm.kms_urls` carries the guest-only `10.0.2.2` +/// alias, which is not routable from the host. +fn app_epoch_kms_urls<'a>(manifest: &'a Manifest, config: &'a Config) -> Vec<&'a str> { + if !manifest.kms_urls.is_empty() { + return manifest.kms_urls.iter().map(String::as_str).collect(); + } + let mut urls = Vec::new(); + if !config.kms_url.is_empty() { + urls.push(config.kms_url.as_str()); + } + for url in &config.cvm.kms_urls { + if !urls.contains(&url.as_str()) { + urls.push(url.as_str()); + } + } + urls +} + /// The app epoch a launch binds in MrConfigV3: the pin, or on SEV-SNP with KMS /// keys the KMS's current app epoch, since SEV-SNP has no runtime register to /// measure the epoch the guest is served. Images predating the field get none. @@ -154,11 +176,7 @@ pub(crate) async fn launch_app_epoch( { return Ok(manifest.app_epoch); } - let kms_urls = if manifest.kms_urls.is_empty() { - &config.cvm.kms_urls - } else { - &manifest.kms_urls - }; + let kms_urls = app_epoch_kms_urls(manifest, config); if kms_urls.is_empty() { bail!("an amd sev-snp launch with KMS keys needs a KMS URL to read the app epoch"); } @@ -372,4 +390,47 @@ mod tests { let document: serde_json::Value = serde_json::from_str(&document).unwrap(); assert_eq!(document["init_script_hashes"], serde_json::json!([])); } + + #[test] + fn app_epoch_kms_urls_prefers_host_kms_url() { + let mut config: Config = crate::Figment::from(crate::config::load_config_figment(None)) + .extract() + .unwrap(); + config.kms_url = "https://127.0.0.1:13443".into(); + config.cvm.kms_urls = vec![ + "https://10.0.2.2:13443".into(), + "https://127.0.0.1:13443".into(), + ]; + + let mut manifest = Manifest::from_json(serde_json::json!({ + "id": "vm-1", + "name": "vm-1", + "app_id": "11".repeat(20), + "vcpu": 2, + "memory": 2048, + "disk_size": 1024, + "image": "dstack-0.6.7", + "port_map": [], + "created_at_ms": 0 + })) + .unwrap(); + + assert_eq!( + app_epoch_kms_urls(&manifest, &config), + vec!["https://127.0.0.1:13443", "https://10.0.2.2:13443"] + ); + + manifest.kms_urls = vec!["https://override.example".into()]; + assert_eq!( + app_epoch_kms_urls(&manifest, &config), + vec!["https://override.example"] + ); + + manifest.kms_urls.clear(); + config.kms_url.clear(); + assert_eq!( + app_epoch_kms_urls(&manifest, &config), + vec!["https://10.0.2.2:13443", "https://127.0.0.1:13443"] + ); + } } From 361efa57fe703483d6a71af47069a53f373136ff Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:04:19 +0000 Subject: [PATCH 11/12] fix(dstackup): set host kms_url in vmm.toml dstackup install writes cvm.kms_urls with the QEMU user-mode guest alias (https://10.0.2.2:), which is not routable from the host, and left the top-level host kms_url empty. Set kms_url = https://127.0.0.1: when KMS is enabled so host-side VMM RPCs (app-epoch resolution on 0.6.7 SEV-SNP launches and env-key lookups) can reach the local KMS. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/crates/dstack-cli-core/src/config.rs | 8 +++++++- dstack/crates/dstackup/src/install.rs | 10 +++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index 0973fdd9f..34ce91bde 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -283,6 +283,8 @@ pub struct VmmRender { pub key_provider_addr: String, /// local key-provider port. pub key_provider_port: u32, + /// Host-reachable KMS URL used by the VMM itself (e.g. `https://127.0.0.1:`). + pub kms_url: String, /// KMS URLs injected into app CVMs (the guest-visible KMS address). pub kms_urls: Vec, /// confidential-computing platform (selects qemu/share-mode for the CVMs). @@ -308,6 +310,7 @@ impl Default for VmmRender { host_api_port: 10000, key_provider_addr: "127.0.0.1".to_string(), key_provider_port: 3443, + kms_url: String::new(), kms_urls: Vec::new(), platform: Platform::Tdx, auth_enabled: false, @@ -332,7 +335,7 @@ keep_alive = 10 log_level = "info" address = "{dashboard_addr}" reuse = true -kms_url = "" +kms_url = "{kms_url}" event_buffer_size = 20 node_name = "" run_path = "{vm_path}" @@ -436,6 +439,7 @@ port = {kp_port} Platform::AmdSevSnp => "vhd", Platform::Tdx => "9p", }, + kms_url = r.kms_url, kms_urls = r .kms_urls .iter() @@ -469,12 +473,14 @@ mod tests { dashboard_addr: "tcp:127.0.0.1:19080".into(), cid_start: 2000, host_api_port: 10001, + kms_url: "https://127.0.0.1:13443".into(), auth_enabled: true, auth_token: "deadbeef".into(), ..Default::default() }; let rendered = vmm_toml(&r); assert!(rendered.contains(r#"address = "tcp:127.0.0.1:19080""#)); + assert!(rendered.contains(r#"kms_url = "https://127.0.0.1:13443""#)); assert!(rendered.contains("cid_start = 2000")); assert!(rendered.contains("port = 10001")); assert!(rendered.contains("enabled = true")); diff --git a/dstack/crates/dstackup/src/install.rs b/dstack/crates/dstackup/src/install.rs index 1dc6fd0b9..46794e79e 100644 --- a/dstack/crates/dstackup/src/install.rs +++ b/dstack/crates/dstackup/src/install.rs @@ -156,10 +156,13 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) // KMS host port + URL, resolved during preflight so conflicts are caught // before image download, builds, or systemd writes. - let kms_urls = if o.no_kms { - vec![] + let (kms_url, kms_urls) = if o.no_kms { + (String::new(), vec![]) } else { - vec![format!("https://10.0.2.2:{kms_port}")] + ( + format!("https://127.0.0.1:{kms_port}"), + vec![format!("https://10.0.2.2:{kms_port}")], + ) }; // 9. render configs. @@ -174,6 +177,7 @@ pub(crate) async fn cmd_install(mut o: InstallOpts, release_api_base_url: &str) host_api_port: o.host_api_port, key_provider_addr: kp_addr, key_provider_port: kp_port as u32, + kms_url, kms_urls: kms_urls.clone(), platform, auth_enabled: true, From 1e908f978e9d8c7d245a18342c8cfbe3bd799ae8 Mon Sep 17 00:00:00 2001 From: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:18:51 +0000 Subject: [PATCH 12/12] fix(vmm-cli): allow --env-file with --kms-encrypt-url alone create_vm rejected --env-file when --kms-url was omitted even if --kms-encrypt-url was given (unlike update_vm, which already allowed it). Allowing --kms-encrypt-url without --kms-url lets single-node hosts encrypt envs against the host-side KMS without overriding cvm.kms_urls on the VM. Signed-off-by: Pierre LE GUEN <26087574+PierreLeGuen@users.noreply.github.com> --- dstack/vmm/src/tests/test_vmm_cli.py | 14 ++++++++++++++ dstack/vmm/src/vmm-cli.py | 6 +++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/dstack/vmm/src/tests/test_vmm_cli.py b/dstack/vmm/src/tests/test_vmm_cli.py index 397004003..630a304f5 100644 --- a/dstack/vmm/src/tests/test_vmm_cli.py +++ b/dstack/vmm/src/tests/test_vmm_cli.py @@ -700,6 +700,20 @@ def rpc(method, params=None): methods = [c.args[0] for c in self.cli.rpc_call.call_args_list] self.assertNotIn("CreateVm", methods) + # --env-file with --kms-encrypt-url works without overriding manifest kms_urls. + capability = {"sealed_env": True} + args.env_file = "env" + args.app_epoch = None + args.kms_url = None + args.kms_encrypt_url = "https://127.0.0.1:13444" + client.return_value.request.return_value = (200, self.response) + self.cli.rpc_call.reset_mock() + self.cli.create_vm(args) + method, payload = self.cli.rpc_call.call_args.args + self.assertEqual(method, "CreateVm") + self.assertNotIn("kms_urls", payload) + self.decrypt(payload) + if __name__ == "__main__": unittest.main() diff --git a/dstack/vmm/src/vmm-cli.py b/dstack/vmm/src/vmm-cli.py index b273dcf3b..79f65550b 100755 --- a/dstack/vmm/src/vmm-cli.py +++ b/dstack/vmm/src/vmm-cli.py @@ -1165,11 +1165,11 @@ def create_vm(self, args) -> None: envs = parse_env_file(args.env_file) - # Validate: --env-file requires --kms-url and kms_enabled in compose + # Validate: --env-file requires --kms-url or --kms-encrypt-url, and kms_enabled in compose if envs: - if not args.kms_url: + if not args.kms_url and not args.kms_encrypt_url: raise Exception( - "--env-file requires --kms-url to encrypt environment variables" + "--env-file requires --kms-url or --kms-encrypt-url to encrypt environment variables" ) try: compose_json = json.loads(compose_content)