Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 35 additions & 50 deletions dstack/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion dstack/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
] }
Expand Down
82 changes: 59 additions & 23 deletions dstack/crates/dstack-cli-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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
Expand Down Expand Up @@ -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";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Register root epochs before selecting the epoch-aware KMS

On a fresh default dstackup install, auth_allowlist_json() still writes neither rootEpochs nor kmsContractAddr, and cmd_install() never populates them after bootstrap. Unlike the previous 0.5.11 default, KMS 0.6.7 authorizes application key release through /authorizeApp; dstack/crates/dstack-auth/src/main.rs:435-455 rejects non-bootstrap operations without registered roots and also requires the KMS app ID. Consequently, installation can report success, but even a subsequently allowlisted application cannot obtain its boot keys without an additional manual migration. Populate the verified epoch-zero roots and KMS app ID during installation before making this image the default.

Useful? React with 👍 / 👎.


/// 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.
Expand Down Expand Up @@ -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:<port>`).
pub kms_url: String,
/// KMS URLs injected into app CVMs (the guest-visible KMS address).
pub kms_urls: Vec<String>,
/// confidential-computing platform (selects qemu/share-mode for the CVMs).
Expand All @@ -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,
Expand All @@ -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}"
Expand Down Expand Up @@ -436,6 +439,7 @@ port = {kp_port}
Platform::AmdSevSnp => "vhd",
Platform::Tdx => "9p",
},
kms_url = r.kms_url,
kms_urls = r
.kms_urls
.iter()
Expand Down Expand Up @@ -469,19 +473,38 @@ 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"));
assert!(rendered.contains(r#"tokens = ["deadbeef"]"#));
toml::from_str::<toml::Value>(&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());
Expand All @@ -502,14 +525,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""#));
Expand Down
33 changes: 29 additions & 4 deletions dstack/crates/dstack-cli-core/src/ports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u16> = 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<u16> {
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
Expand Down Expand Up @@ -94,6 +111,14 @@ fn parse_port_number(value: &str, label: &str, spec: &str) -> Result<u16> {
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();
Expand Down
Loading
Loading