From 5cee2ac97088af62e0d89f0fba39057314429670 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 Oct 2026 06:12:03 +0000 Subject: [PATCH 001/572] build(deps): bump fast-uri in /dstack/kms/auth-eth Bumps and [fast-uri](https://github.com/fastify/fast-uri). These dependencies needed to be updated together. Updates `fast-uri` from 3.1.7 to 3.1.8 - [Release notes](https://github.com/fastify/fast-uri/releases) - [Commits](https://github.com/fastify/fast-uri/compare/v3.1.7...v3.1.8) Updates `fast-uri` from 4.1.4 to 4.2.1 - [Release notes](https://github.com/fastify/fast-uri/releases) - [Commits](https://github.com/fastify/fast-uri/compare/v3.1.7...v3.1.8) --- updated-dependencies: - dependency-name: fast-uri dependency-version: 3.1.8 dependency-type: indirect - dependency-name: fast-uri dependency-version: 4.2.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- dstack/kms/auth-eth/package-lock.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/dstack/kms/auth-eth/package-lock.json b/dstack/kms/auth-eth/package-lock.json index d98dec8b12..7eb073d0cf 100644 --- a/dstack/kms/auth-eth/package-lock.json +++ b/dstack/kms/auth-eth/package-lock.json @@ -2418,9 +2418,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.8", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", + "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", "funding": [ { "type": "github", @@ -2497,9 +2497,9 @@ } }, "node_modules/fastify/node_modules/fast-uri": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.1.4.tgz", - "integrity": "sha512-dODXrIxlS9JSdgAnhIUKOosKV1oMtU2VtVw87QRaHzyl5jxO290Ii5tEZfCfzfWNHi3jKWwBSdQj0qIyshdZdQ==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-4.2.1.tgz", + "integrity": "sha512-TmHQgewjHtMq1E5QKA0tOE0yeYGQs25KZC/ziJpubRtWI15W92e6vPFydWOeZBVROSHBYw/QhD9d5OefdD6LDg==", "funding": [ { "type": "github", From 326b9ff152530b970d5491e3ca3b38bcf11f21c4 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 12 Oct 2026 17:50:11 -0700 Subject: [PATCH 002/572] fix(guest-agent): reject unsafe container names in the logs route bollard puts the container name into the Docker API request path without escaping it, so a decoded name containing path or query characters could redirect the logs request to a different Docker API endpoint. Reject names that are not valid Docker container names ([a-zA-Z0-9][a-zA-Z0-9_.-]*) before calling bollard. Signed-off-by: Kevin Wang --- dstack/guest-agent/src/http_routes.rs | 39 +++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/dstack/guest-agent/src/http_routes.rs b/dstack/guest-agent/src/http_routes.rs index af08338438..833cd0bd3d 100644 --- a/dstack/guest-agent/src/http_routes.rs +++ b/dstack/guest-agent/src/http_routes.rs @@ -231,10 +231,22 @@ mod docker_logs { Ok(now.as_secs().saturating_sub(seconds) as i64) } + fn validate_container_name(name: &str) -> Result<()> { + let mut chars = name.chars(); + let valid = chars.next().is_some_and(|c| c.is_ascii_alphanumeric()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-')); + if !valid { + anyhow::bail!("invalid container name"); + } + Ok(()) + } + pub fn get_logs( container_name: &str, config: LogConfig, ) -> Result>> { + // bollard interpolates the name into the request path without escaping it + validate_container_name(container_name)?; let LogConfig { since, until, @@ -295,6 +307,33 @@ mod docker_logs { use super::*; use std::time::{SystemTime, UNIX_EPOCH}; + #[test] + fn test_validate_container_name() { + for name in [ + "test/json?", + "test/json#", + "../info?", + "test%2Fjson%3F", + "/test", + ".", + "..", + "test\\name", + "test name", + "tést", + "", + ] { + assert!(validate_container_name(name).is_err(), "{name}"); + } + for name in [ + "test", + "dstack-gateway-1", + "Test_1.local", + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + ] { + assert!(validate_container_name(name).is_ok(), "{name}"); + } + } + #[test] fn test_parse_duration_empty() { assert_eq!(parse_duration("").unwrap(), 0); From 19f8d6e5082411467b8e0a54d999693c20362e0a Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 12 Oct 2026 18:10:07 -0700 Subject: [PATCH 003/572] chore(release): bump version to 0.6.1 Signed-off-by: Kevin Wang --- dstack/Cargo.lock | 114 +++++++++--------- dstack/Cargo.toml | 2 +- os/mkosi/README.md | 2 +- os/mkosi/mkosi.conf | 2 +- os/mkosi/versions.env | 2 +- .../meta-dstack/conf/distro/dstack.conf | 2 +- 6 files changed, 62 insertions(+), 62 deletions(-) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index a5cb819e1e..31a97f3894 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -801,7 +801,7 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "cached-cell" -version = "0.6.0" +version = "0.6.1" dependencies = [ "tokio", ] @@ -820,7 +820,7 @@ dependencies = [ [[package]] name = "cc-eventlog" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "digest 0.10.7", @@ -840,7 +840,7 @@ dependencies = [ [[package]] name = "cert-client" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "dstack-guest-agent-rpc", @@ -860,7 +860,7 @@ dependencies = [ [[package]] name = "certbot" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "bon", @@ -888,7 +888,7 @@ dependencies = [ [[package]] name = "certbot-cli" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "certbot", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "ct_monitor" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "clap", @@ -1820,7 +1820,7 @@ dependencies = [ [[package]] name = "dstack-api-auth" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "base64 0.22.1", @@ -1832,7 +1832,7 @@ dependencies = [ [[package]] name = "dstack-attest" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -1881,7 +1881,7 @@ dependencies = [ [[package]] name = "dstack-auth" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "clap", @@ -1892,14 +1892,14 @@ dependencies = [ [[package]] name = "dstack-build-info" -version = "0.6.0" +version = "0.6.1" dependencies = [ "git-version", ] [[package]] name = "dstack-cli" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "clap", @@ -1916,7 +1916,7 @@ dependencies = [ [[package]] name = "dstack-cli-core" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "dstack-types", @@ -1930,7 +1930,7 @@ dependencies = [ [[package]] name = "dstack-gateway" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "arc-swap", @@ -1999,7 +1999,7 @@ dependencies = [ [[package]] name = "dstack-gateway-rpc" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "parity-scale-codec", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "base64 0.22.1", @@ -2068,7 +2068,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent-rpc" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "hex", @@ -2084,7 +2084,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent-simulator" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "cc-eventlog", @@ -2106,7 +2106,7 @@ dependencies = [ [[package]] name = "dstack-kms" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "cc-eventlog", @@ -2151,7 +2151,7 @@ dependencies = [ [[package]] name = "dstack-kms-rpc" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "fs-err", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "dstack-mr" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "binrw", @@ -2205,7 +2205,7 @@ dependencies = [ [[package]] name = "dstack-netd-rpc" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "prost 0.13.5", @@ -2217,7 +2217,7 @@ dependencies = [ [[package]] name = "dstack-nvidia-attest-proxy" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "base64 0.22.1", @@ -2245,7 +2245,7 @@ dependencies = [ [[package]] name = "dstack-tee-simulator" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -2282,7 +2282,7 @@ dependencies = [ [[package]] name = "dstack-types" -version = "0.6.0" +version = "0.6.1" dependencies = [ "ciborium", "hex", @@ -2300,7 +2300,7 @@ dependencies = [ [[package]] name = "dstack-util" -version = "0.6.0" +version = "0.6.1" dependencies = [ "aes-gcm", "anyhow", @@ -2364,7 +2364,7 @@ dependencies = [ [[package]] name = "dstack-verifier" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "cc-eventlog", @@ -2400,7 +2400,7 @@ dependencies = [ [[package]] name = "dstack-vmm" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "base64 0.22.1", @@ -2463,7 +2463,7 @@ dependencies = [ [[package]] name = "dstack-vmm-rpc" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "parity-scale-codec", @@ -2476,7 +2476,7 @@ dependencies = [ [[package]] name = "dstack-volume" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "binrw", @@ -2497,7 +2497,7 @@ dependencies = [ [[package]] name = "dstackup" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "clap", @@ -3173,7 +3173,7 @@ dependencies = [ [[package]] name = "guest-api" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "http-client", @@ -3434,7 +3434,7 @@ dependencies = [ [[package]] name = "host-api" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "http-client", @@ -3480,7 +3480,7 @@ dependencies = [ [[package]] name = "http-client" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "http-body-util", @@ -3889,7 +3889,7 @@ checksum = "d8972d5be69940353d5347a1344cb375d9b457d6809b428b05bb1ca2fb9ce007" [[package]] name = "iohash" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "blake2", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "key-provider-client" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "dstack-types", @@ -4270,7 +4270,7 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "load_config" -version = "0.6.0" +version = "0.6.1" dependencies = [ "figment", "rocket", @@ -4280,7 +4280,7 @@ dependencies = [ [[package]] name = "local-key-provider" -version = "0.6.0" +version = "0.6.1" dependencies = [ "blake2", "dcap-qvl", @@ -4342,7 +4342,7 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" [[package]] name = "lspci" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "insta", @@ -4512,7 +4512,7 @@ dependencies = [ [[package]] name = "mock-attestation" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "axum", @@ -4740,7 +4740,7 @@ dependencies = [ [[package]] name = "nsm-attest" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -4752,7 +4752,7 @@ dependencies = [ [[package]] name = "nsm-qvl" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "ciborium", @@ -4934,7 +4934,7 @@ dependencies = [ [[package]] name = "nvattest" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "serde", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "pki-fetch" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "pem", @@ -5844,7 +5844,7 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "ra-rpc" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "bon", @@ -5866,7 +5866,7 @@ dependencies = [ [[package]] name = "ra-tls" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "bon", @@ -6371,7 +6371,7 @@ dependencies = [ [[package]] name = "rocket-vsock-listener" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "derive_more 2.1.1", @@ -6951,7 +6951,7 @@ dependencies = [ [[package]] name = "serde-duration" -version = "0.6.0" +version = "0.6.1" dependencies = [ "serde", "serde_json", @@ -7173,7 +7173,7 @@ dependencies = [ [[package]] name = "sev-snp-attest" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "fs-err", @@ -7184,7 +7184,7 @@ dependencies = [ [[package]] name = "sev-snp-qvl" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "hex", @@ -7363,7 +7363,7 @@ checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" [[package]] name = "size-parser" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "serde", @@ -7532,7 +7532,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "supervisor" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "bon", @@ -7555,7 +7555,7 @@ dependencies = [ [[package]] name = "supervisor-client" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "clap", @@ -7708,7 +7708,7 @@ dependencies = [ [[package]] name = "tdx-attest" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "cc-eventlog", @@ -8092,7 +8092,7 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tpm-attest" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "dstack-types", @@ -8111,7 +8111,7 @@ dependencies = [ [[package]] name = "tpm-qvl" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "base64 0.22.1", @@ -8134,7 +8134,7 @@ dependencies = [ [[package]] name = "tpm-types" -version = "0.6.0" +version = "0.6.1" dependencies = [ "cc-eventlog", "dstack-types", @@ -8145,7 +8145,7 @@ dependencies = [ [[package]] name = "tpm2" -version = "0.6.0" +version = "0.6.1" dependencies = [ "anyhow", "hex", diff --git a/dstack/Cargo.toml b/dstack/Cargo.toml index 7d7cbaf711..8877f62967 100644 --- a/dstack/Cargo.toml +++ b/dstack/Cargo.toml @@ -5,7 +5,7 @@ # SPDX-License-Identifier: Apache-2.0 [workspace.package] -version = "0.6.0" +version = "0.6.1" authors = ["Kevin Wang ", "Leechael "] edition = "2021" license = "MIT" diff --git a/os/mkosi/README.md b/os/mkosi/README.md index 2311478ea9..b867ed2092 100644 --- a/os/mkosi/README.md +++ b/os/mkosi/README.md @@ -75,7 +75,7 @@ The native interface remains available when those host tools are present: # QEMU smoke-test the assembled UKI disk (host OVMF path is distro-specific) qemu-system-x86_64 -machine q35 -m 2G -nographic \ -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.fd \ - -drive if=virtio,format=raw,file=os/mkosi/build/out/prod/dstack-0.6.0/disk.raw + -drive if=virtio,format=raw,file=os/mkosi/build/out/prod/dstack-0.6.1/disk.raw ``` `image` reuses a component-output cache, which is what makes local iteration diff --git a/os/mkosi/mkosi.conf b/os/mkosi/mkosi.conf index 24b0a5a249..185087377b 100644 --- a/os/mkosi/mkosi.conf +++ b/os/mkosi/mkosi.conf @@ -22,7 +22,7 @@ Format=tar # order, so declaring Output first silently yields "--rootfs.tar". # ImageVersion is checked against DSTACK_VERSION by tests/acceptance.sh. ImageId=dstack -ImageVersion=0.6.0 +ImageVersion=0.6.1 Output=%i-%v-rootfs CompressOutput=no # Must stay empty. The default is [uki, kernel, initrd], and the kernel split diff --git a/os/mkosi/versions.env b/os/mkosi/versions.env index 97dfd2844c..fcebc7b159 100644 --- a/os/mkosi/versions.env +++ b/os/mkosi/versions.env @@ -20,7 +20,7 @@ RUST_STD_TOOLCHAIN_SHA256=5f106805ed86ebf8df287039e53a45cf974391ef4d088c2760776b GO_TOOLCHAIN_VERSION=1.26.2 GO_TOOLCHAIN_SHA256=990e6b4bbba816dc3ee129eaeaf4b42f17c2800b88a2166c265ac1a200262282 NITRO_TPM_TOOLS_REVISION=d76d6eeebd4169b00a3c3af9858852d48f40e748 -DSTACK_VERSION=0.6.0 +DSTACK_VERSION=0.6.1 DSTACK_CODENAME=trixie OVMF_VARIANT=pre202505 # Must match SRCREV in meta-dstack's dstack-ovmf_git.bb: a generic OVMF diff --git a/os/yocto/layers/meta-dstack/conf/distro/dstack.conf b/os/yocto/layers/meta-dstack/conf/distro/dstack.conf index 84bb9f6610..534e3ff031 100644 --- a/os/yocto/layers/meta-dstack/conf/distro/dstack.conf +++ b/os/yocto/layers/meta-dstack/conf/distro/dstack.conf @@ -7,7 +7,7 @@ DISTRO = "dstack" DISTRO_NAME = "dstack" DISTRO_FEATURES:append = " virtualization seccomp systemd usrmerge security dm-verity ipv6" -DISTRO_VERSION = "0.6.0" +DISTRO_VERSION = "0.6.1" DISTROOVERRIDES = "poky:dstack" INITRAMFS_IMAGE = "" From 9aef01e47b53563dddf1ad0ae7ff5db31ea1ceab Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 12 Oct 2026 18:10:08 -0700 Subject: [PATCH 004/572] docs: add the 0.6.1 changelog Signed-off-by: Kevin Wang --- CHANGELOG.md | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4acc7c906..b32a12a43d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,52 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.6.1] - 2026-10-12 + +dstack 0.6.1 is a security release. Upgrade the guest OS, KMS, and verifier. + +### Upgrade notes + +- **New guest image.** Register the 0.6.1 `os_image_hash` on chain before + deploying 0.6.1 images +- **KMS rejects a mismatched `vm_config`.** A request whose `vm_config` differs + from the copy embedded in the attestation is refused. Released guests always + send identical copies; only untagged `master` builds from Dec 2025 to + Jan 2026 are affected. A `vm_config` nested under a `vm_config` key no longer + parses (#1430) +- **Hugepage VMs:** the VMM now records the memory QEMU actually allocates + (whole GiB per NUMA node) in `vm_config`, so a hugepage VM whose requested + memory was not a multiple of that changes `vm_config` (#1418) + +### Security + +- guest-agent: `/logs/` rejects names that are not valid Docker + container names, so a crafted name can no longer reach a different Docker + API endpoint (#1442) +- KMS and verifier: a request `vm_config` must match the attested copy, and a + config has one layout. On AMD SEV-SNP the competing copies let a `SignCert` + request pass authorization with one `os_image_hash` and obtain a certificate + claiming another (#1430) + +### Added + +- verifier: measure multi-node NUMA layouts of hugepage VMs through + `vm_config.numa_nodes`; the VMM orders guest NUMA nodes by host node (#1418) +- verifier: `vm_config.extra_root_devices` describes root-bus devices that a + `qemu_path` wrapper appends, so their DSDT entries can be measured (#1424) +- vmm: `passt` networking is back. Each passt runs as a sidecar of the VM + launcher and talks to QEMU over a socketpair; see + `docs/passt-networking.md` (#1422, #1423) +- vmm: per-VM `annotations` for host-side tooling, stored in the VM manifest + and never passed to the guest or measured (#1419, #1421) + +### Changed + +- sdk/simulator: use the GHCR openssh installer image (#1417) +- dependency updates: rustls 0.23.45 in the Rust SDK, hickory-resolver 0.26.2, + and npm packages in KMS auth-eth and the VMM UI (#1429, #1432, #1434, #1436, + #1438, #1439, #1440) + ## [0.6.0] - 2026-09-28 > [!IMPORTANT] @@ -1655,7 +1701,8 @@ New contributors in this release: * @Leechael made their first contribution * @nanometerzhu made their first contribution * @h4x3rotab made their first contribution -[unreleased]: https://github.com/Dstack-TEE/dstack/compare/v0.6.0..HEAD +[unreleased]: https://github.com/Dstack-TEE/dstack/compare/v0.6.1..HEAD +[0.6.1]: https://github.com/Dstack-TEE/dstack/compare/v0.6.0..v0.6.1 [0.6.0]: https://github.com/Dstack-TEE/dstack/compare/v0.5.11..v0.6.0 [0.5.5]: https://github.com/Dstack-TEE/dstack/compare/v0.5.4..v0.5.5 [0.5.4]: https://github.com/Dstack-TEE/dstack/compare/v0.5.3..v0.5.4 From 3098c53df8269cf5e8ab985939d00cff79248ada Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 12 Oct 2026 19:33:45 -0700 Subject: [PATCH 005/572] docs(changelog): drop the 0.6.1 vm_config upgrade note No released guest sends a mismatched or nested vm_config, so the note has no audience. The security entry for #1430 stays. Signed-off-by: Kevin Wang --- CHANGELOG.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b32a12a43d..46f22bac87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,11 +15,6 @@ dstack 0.6.1 is a security release. Upgrade the guest OS, KMS, and verifier. - **New guest image.** Register the 0.6.1 `os_image_hash` on chain before deploying 0.6.1 images -- **KMS rejects a mismatched `vm_config`.** A request whose `vm_config` differs - from the copy embedded in the attestation is refused. Released guests always - send identical copies; only untagged `master` builds from Dec 2025 to - Jan 2026 are affected. A `vm_config` nested under a `vm_config` key no longer - parses (#1430) - **Hugepage VMs:** the VMM now records the memory QEMU actually allocates (whole GiB per NUMA node) in `vm_config`, so a hugepage VM whose requested memory was not a multiple of that changes `vm_config` (#1418) From a0ccc44f834e2de0be62e4b02818a64144c03fa8 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 12 Oct 2026 19:36:29 -0700 Subject: [PATCH 006/572] docs(changelog): fold the 0.6.1 hugepage memory note into #1418 VMs whose requested memory did not split into whole GiB per NUMA node never verified before #1418, so recording the allocated size is a fix, not an upgrade concern. Signed-off-by: Kevin Wang --- CHANGELOG.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46f22bac87..dd2d15c687 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,9 +15,6 @@ dstack 0.6.1 is a security release. Upgrade the guest OS, KMS, and verifier. - **New guest image.** Register the 0.6.1 `os_image_hash` on chain before deploying 0.6.1 images -- **Hugepage VMs:** the VMM now records the memory QEMU actually allocates - (whole GiB per NUMA node) in `vm_config`, so a hugepage VM whose requested - memory was not a multiple of that changes `vm_config` (#1418) ### Security @@ -32,7 +29,8 @@ dstack 0.6.1 is a security release. Upgrade the guest OS, KMS, and verifier. ### Added - verifier: measure multi-node NUMA layouts of hugepage VMs through - `vm_config.numa_nodes`; the VMM orders guest NUMA nodes by host node (#1418) + `vm_config.numa_nodes`; the VMM orders guest NUMA nodes by host node and + records the memory QEMU actually allocates, so such VMs now verify (#1418) - verifier: `vm_config.extra_root_devices` describes root-bus devices that a `qemu_path` wrapper appends, so their DSDT entries can be measured (#1424) - vmm: `passt` networking is back. Each passt runs as a sidecar of the VM From d1fbb6237b6916d333cb03defd30d76c27fcb45f Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 12 Oct 2026 23:51:00 -0700 Subject: [PATCH 007/572] feat(vmm): enable the QMP socket by default Without a QMP socket a running CVM has no runtime control channel, so fixing a disk option or compacting a bloated hda.img requires stopping the CVM. With qmp.sock the host can use blockdev-mirror to move the disk to a compact image live. The socket lives in the VM work dir and is only reachable by the VMM user. The host is outside the TDX trust boundary, so this does not widen what a CVM has to trust. Signed-off-by: Kevin Wang --- CHANGELOG.md | 3 +++ docs/tutorials/vmm-configuration.md | 2 +- dstack/crates/dstack-cli-core/src/config.rs | 2 +- dstack/vmm/vmm.toml | 5 +++-- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dd2d15c687..0d80200b61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed +- vmm: `qmp_socket` now defaults to `true`. Each CVM's QEMU exposes `qmp.sock` in its work dir, so the host can change disk options or compact a bloated `hda.img` (`blockdev-mirror`) without stopping the CVM. Applies to CVMs started after the change; set `qmp_socket = false` to opt out + ## [0.6.1] - 2026-10-12 dstack 0.6.1 is a security release. Upgrade the guest OS, KMS, and verifier. diff --git a/docs/tutorials/vmm-configuration.md b/docs/tutorials/vmm-configuration.md index b3dede9e22..b4a0becede 100644 --- a/docs/tutorials/vmm-configuration.md +++ b/docs/tutorials/vmm-configuration.md @@ -113,7 +113,7 @@ cid_start = 1000 cid_pool_size = 1000 max_allocable_vcpu = 124 # Adjust: total cores - 4 max_allocable_memory_in_mb = 990616 # Adjust: total MB - 16384 -qmp_socket = false +qmp_socket = true use_mrconfigid = true qemu_pci_hole64_size = 0 qemu_hotplug_off = true diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index cb0855ce30..2618bc6d98 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -340,7 +340,7 @@ cid_start = {cid_start} cid_pool_size = {cid_pool_size} max_allocable_vcpu = 20 max_allocable_memory_in_mb = 100_000 -qmp_socket = false +qmp_socket = true user = "" use_mrconfigid = {use_mrconfigid} qemu_pci_hole64_size = 0 diff --git a/dstack/vmm/vmm.toml b/dstack/vmm/vmm.toml index cde5397fca..dc5dbf2d9e 100644 --- a/dstack/vmm/vmm.toml +++ b/dstack/vmm/vmm.toml @@ -43,8 +43,9 @@ cid_start = 1000 cid_pool_size = 1000 max_allocable_vcpu = 20 max_allocable_memory_in_mb = 100_000 # MB -# Enable QMP socket -qmp_socket = false +# Expose a QMP socket (qmp.sock in each VM work dir) for host-side runtime +# operations such as live disk migration +qmp_socket = true # The user to run the VM as. If empty, the VM will be run as the current user. # Unique namespace when multiple dstack-vmm instances share one host. When # empty, a stable value is derived from run_path. It is what netd records on From c7eb5c9582065aa15d3635b49906c2953a82402e Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Wed, 14 Oct 2026 08:21:01 +0800 Subject: [PATCH 008/572] fix(gateway): require canonical port numbers in SNI Signed-off-by: Leechael Yim --- dstack/gateway/src/proxy.rs | 55 +++++++++++++++++++++- dstack/gateway/src/proxy/tls_passthough.rs | 26 +++++++++- 2 files changed, 79 insertions(+), 2 deletions(-) diff --git a/dstack/gateway/src/proxy.rs b/dstack/gateway/src/proxy.rs index cffb49850a..82f36372c8 100644 --- a/dstack/gateway/src/proxy.rs +++ b/dstack/gateway/src/proxy.rs @@ -135,6 +135,15 @@ struct DstInfo { is_h2: bool, } +// Require one decimal spelling for each destination port. Port 0 is reserved, +// so reject it along with leading zeros and signs in both SNI and TXT records. +fn parse_canonical_port(port_str: &str) -> Result { + if port_str.starts_with('0') || !port_str.bytes().all(|byte| byte.is_ascii_digit()) { + bail!("invalid port"); + } + port_str.parse::().context("invalid port") +} + fn parse_dst_info(subdomain: &str) -> Result { let mut parts = subdomain.split('-'); let app_id = parts.next().context("no app id found")?.to_owned(); @@ -169,7 +178,7 @@ fn parse_dst_info(subdomain: &str) -> Result { port = if port_str.is_empty() { None } else { - Some(port_str.parse::().context("invalid port")?) + Some(parse_canonical_port(port_str)?) }; } }; @@ -725,6 +734,50 @@ mod tests { assert_eq!(sniffed.unwrap().0.as_deref(), Some(host)); } + #[test] + fn test_parse_destination_canonical_ports() { + for (subdomain, port, is_tls, is_h2) in [ + ("myapp-8090", 8090, false, false), + ("myapp-80", 80, false, false), + ("myapp-443s", 443, true, false), + ("myapp-8090s", 8090, true, false), + ("myapp-8090g", 8090, false, true), + ("myapp-65535", 65535, false, false), + ("myapp", 80, false, false), + ("myapp-s", 443, true, false), + ("myapp-g", 80, false, true), + ] { + let result = parse_dst_info(subdomain).unwrap(); + assert_eq!(result.app_id, "myapp"); + assert_eq!(result.port, port, "{subdomain}"); + assert_eq!(result.is_tls, is_tls, "{subdomain}"); + assert_eq!(result.is_h2, is_h2, "{subdomain}"); + } + } + + #[test] + fn test_parse_destination_invalid_ports() { + let mut accepted = Vec::new(); + for subdomain in [ + "myapp-08090", + "myapp-008090", + "myapp-08090s", + "myapp-08090g", + "myapp-0080", + "myapp-+8090", + "myapp-0", + "myapp-65536", + "myapp-80", + "myapp-80x", + ] { + match parse_dst_info(subdomain) { + Ok(_) => accepted.push(subdomain), + Err(err) => assert_eq!(err.to_string(), "invalid port", "{subdomain}"), + } + } + assert!(accepted.is_empty(), "accepted invalid ports: {accepted:?}"); + } + #[test] fn test_parse_destination() { // Test basic app_id only diff --git a/dstack/gateway/src/proxy/tls_passthough.rs b/dstack/gateway/src/proxy/tls_passthough.rs index 575b469ec8..01583abec8 100644 --- a/dstack/gateway/src/proxy/tls_passthough.rs +++ b/dstack/gateway/src/proxy/tls_passthough.rs @@ -25,6 +25,7 @@ use crate::{ use super::{ io_bridge::bridge_tcp, + parse_canonical_port, port_policy::{filter_allowed_addresses, should_send_pp}, AddressGroup, AddressInfo, }; @@ -45,7 +46,7 @@ impl AppAddress { let (app_id, port) = data.split_once(':').context("invalid app address")?; Ok(Self { app_id: app_id.to_string(), - port: port.parse().context("invalid port")?, + port: parse_canonical_port(port)?, }) } } @@ -348,6 +349,29 @@ pub(crate) async fn proxy_to_app( mod tests { use super::*; + #[test] + fn test_app_address_canonical_ports() { + for port in [1, 80, 443, 8090, 65535] { + let address = AppAddress::parse(format!("myapp:{port}").as_bytes()).unwrap(); + assert_eq!(address.app_id, "myapp"); + assert_eq!(address.port, port); + } + } + + #[test] + fn test_app_address_invalid_ports() { + let mut accepted = Vec::new(); + for port in [ + "08090", "008090", "0080", "+8090", "0", "65536", "", "80", "80s", "80g", + ] { + match AppAddress::parse(format!("myapp:{port}").as_bytes()) { + Ok(_) => accepted.push(port), + Err(err) => assert_eq!(err.to_string(), "invalid port", "{port}"), + } + } + assert!(accepted.is_empty(), "accepted invalid ports: {accepted:?}"); + } + #[test] fn the_connection_limit_check_takes_the_slot() { let counter = Arc::new(AtomicU64::new(0)); From be4c5f38e1c3c582e82bb842c87c5caf67b06a07 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Tue, 13 Oct 2026 18:29:22 -0700 Subject: [PATCH 009/572] test(gateway): consolidate canonical port tests Test parse_canonical_port directly and keep one wiring case per caller, folding the SNI cases into the existing parse_destination test. Signed-off-by: Kevin Wang --- dstack/gateway/src/proxy.rs | 52 ++++++---------------- dstack/gateway/src/proxy/tls_passthough.rs | 25 +++-------- 2 files changed, 18 insertions(+), 59 deletions(-) diff --git a/dstack/gateway/src/proxy.rs b/dstack/gateway/src/proxy.rs index 82f36372c8..6793390263 100644 --- a/dstack/gateway/src/proxy.rs +++ b/dstack/gateway/src/proxy.rs @@ -735,47 +735,13 @@ mod tests { } #[test] - fn test_parse_destination_canonical_ports() { - for (subdomain, port, is_tls, is_h2) in [ - ("myapp-8090", 8090, false, false), - ("myapp-80", 80, false, false), - ("myapp-443s", 443, true, false), - ("myapp-8090s", 8090, true, false), - ("myapp-8090g", 8090, false, true), - ("myapp-65535", 65535, false, false), - ("myapp", 80, false, false), - ("myapp-s", 443, true, false), - ("myapp-g", 80, false, true), - ] { - let result = parse_dst_info(subdomain).unwrap(); - assert_eq!(result.app_id, "myapp"); - assert_eq!(result.port, port, "{subdomain}"); - assert_eq!(result.is_tls, is_tls, "{subdomain}"); - assert_eq!(result.is_h2, is_h2, "{subdomain}"); + fn test_parse_canonical_port() { + for port in ["1", "80", "65535"] { + assert_eq!(parse_canonical_port(port).unwrap().to_string(), port); } - } - - #[test] - fn test_parse_destination_invalid_ports() { - let mut accepted = Vec::new(); - for subdomain in [ - "myapp-08090", - "myapp-008090", - "myapp-08090s", - "myapp-08090g", - "myapp-0080", - "myapp-+8090", - "myapp-0", - "myapp-65536", - "myapp-80", - "myapp-80x", - ] { - match parse_dst_info(subdomain) { - Ok(_) => accepted.push(subdomain), - Err(err) => assert_eq!(err.to_string(), "invalid port", "{subdomain}"), - } + for port in ["", "0", "08090", "+8090", "65536", "80", "80s"] { + assert!(parse_canonical_port(port).is_err(), "{port}"); } - assert!(accepted.is_empty(), "accepted invalid ports: {accepted:?}"); } #[test] @@ -815,5 +781,13 @@ mod tests { assert_eq!(result.app_id, "myapp"); assert_eq!(result.port, 443); assert!(result.is_tls); + + // Test app_id with custom port and HTTP/2 + let result = parse_dst_info("myapp-8090g").unwrap(); + assert_eq!(result.port, 8090); + assert!(result.is_h2); + + // Test non-canonical port + assert!(parse_dst_info("myapp-08090s").is_err()); } } diff --git a/dstack/gateway/src/proxy/tls_passthough.rs b/dstack/gateway/src/proxy/tls_passthough.rs index 01583abec8..1c7378ca22 100644 --- a/dstack/gateway/src/proxy/tls_passthough.rs +++ b/dstack/gateway/src/proxy/tls_passthough.rs @@ -350,26 +350,11 @@ mod tests { use super::*; #[test] - fn test_app_address_canonical_ports() { - for port in [1, 80, 443, 8090, 65535] { - let address = AppAddress::parse(format!("myapp:{port}").as_bytes()).unwrap(); - assert_eq!(address.app_id, "myapp"); - assert_eq!(address.port, port); - } - } - - #[test] - fn test_app_address_invalid_ports() { - let mut accepted = Vec::new(); - for port in [ - "08090", "008090", "0080", "+8090", "0", "65536", "", "80", "80s", "80g", - ] { - match AppAddress::parse(format!("myapp:{port}").as_bytes()) { - Ok(_) => accepted.push(port), - Err(err) => assert_eq!(err.to_string(), "invalid port", "{port}"), - } - } - assert!(accepted.is_empty(), "accepted invalid ports: {accepted:?}"); + fn test_app_address_parse() { + let address = AppAddress::parse(b"myapp:8090").unwrap(); + assert_eq!(address.app_id, "myapp"); + assert_eq!(address.port, 8090); + assert!(AppAddress::parse(b"myapp:08090").is_err()); } #[test] From 48a86bb81539788d3f9eee386ada755fbb121cc7 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Tue, 13 Oct 2026 19:03:08 -0700 Subject: [PATCH 010/572] tdx-attest: add read/write timeout for QGS vsock An unresponsive QGS could block get_quote_via_vsock forever while holding TDX_LOCK, stalling every later quote request in the process. Set a 30s read/write timeout on the vsock stream; connect is already bounded by the kernel (2s by default). Co-authored-by: peg Signed-off-by: Kevin Wang --- dstack/tdx-attest/src/linux.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dstack/tdx-attest/src/linux.rs b/dstack/tdx-attest/src/linux.rs index 5078e35f05..bde47ce342 100644 --- a/dstack/tdx-attest/src/linux.rs +++ b/dstack/tdx-attest/src/linux.rs @@ -47,6 +47,9 @@ const QUOTE_MIN_SIZE: usize = 1020; const QGS_MSG_LEN_PREFIX_SIZE: usize = 4; // 4-byte length prefix const QGS_REQ_BUF_SIZE: usize = 16 * 1024; // 16KB buffer for request/response +// Per read/write timeout for QGS; the kernel bounds vsock connect (2s by default). +const QGS_IO_TIMEOUT: Duration = Duration::from_secs(30); + // QGS message types const QGS_MSG_GET_QUOTE_REQ: u32 = 0; const QGS_MSG_GET_QUOTE_RESP: u32 = 1; @@ -580,6 +583,8 @@ fn get_quote_via_vsock(report_data: &TdxReportData) -> Result> { let request = build_qgs_get_quote_request(&report.0); let mut stream = vsock::VsockStream::connect_with_cid_port(vsock::VMADDR_CID_HOST, vsock_port)?; + stream.set_read_timeout(Some(QGS_IO_TIMEOUT))?; + stream.set_write_timeout(Some(QGS_IO_TIMEOUT))?; let len_header = (request.len() as u32).to_be_bytes(); stream.write_all(&len_header)?; From 93081ab937226535b4a830fb3428ef52455fc2a9 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 14 Oct 2026 22:58:03 -0700 Subject: [PATCH 011/572] vmm: disable GPU sanitize_on_attach by default On an 8x H200 PPCIe host, one GPU started failing SPDM session setup (_kgspEstablishSpdmSession timeout, RmInitAdapter 0x62:0x65) on every boot after an attach-time hot reset that followed a clean guest shutdown. Further SBRs, including manual ones, do not recover it. It is not yet clear whether the per-GPU SBR caused this, but it does not recover the state and resets GPUs individually without the NVSwitches. Make it opt-in until it is validated on PPCIe systems. Signed-off-by: Kevin Wang --- dstack/vmm/vmm.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dstack/vmm/vmm.toml b/dstack/vmm/vmm.toml index dc5dbf2d9e..f040d60f6b 100644 --- a/dstack/vmm/vmm.toml +++ b/dstack/vmm/vmm.toml @@ -301,7 +301,7 @@ allow_attach_all = true # immediately before QEMU attaches the device, using a VFIO PCI hot reset so # that no root privileges are needed. This clears stale GPU FSP/SPDM state # left by a VM that terminated during GPU firmware initialization. -sanitize_on_attach = true +sanitize_on_attach = false # Maximum time for all reset GPUs to become continuously VFIO-ready. sbr_timeout_ms = 10000 From 94a2f6af1e51129441116e88fc3313c8b713e33d Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Fri, 16 Oct 2026 09:27:33 -0700 Subject: [PATCH 012/572] os: stop the confidential guest acting on host-controlled GPT and credentials systemd-gpt-auto-generator reads the root disk's GPT and mounts or activates the partitions it finds. The partition table is host-controlled and outside the TDX/SEV measurements, so a partition the host appends (swap, /var, /home, ...) is acted on inside the guest. Reproduced on mkosi-os-v0.6.1: a host-appended swap partition is activated ~2s into boot under the generator's "Swap Partition" unit. Disable it with systemd.gpt_auto=0 on the measured kernel command line (parsed identically by every systemd since v252, unlike image_policy=) and remove the generator binary from the prod image, mirroring the deletion the Yocto backend did and the mkosi rewrite dropped. Reviewing the same class of mechanism, also set systemd.import_credentials=no so PID1 stops importing system credentials from SMBIOS and qemu fw_cfg (both host-controlled and unmeasured; consumed by sysusers, tmpfiles, udev rules, networkd, ...), and remove the hibernate-resume, bless-boot, system-update, sysv and rc-local generators, which are unreachable in this image or act on host-influenced input. Refs: GHSA-c79w-3x5w-gmm5 Signed-off-by: Kevin Wang --- os/image/kernel-cmdline.sh | 15 +++++++++++++++ os/mkosi/mkosi.profiles/prod/mkosi.conf | 18 ++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/os/image/kernel-cmdline.sh b/os/image/kernel-cmdline.sh index c900899be3..bedbf2722e 100644 --- a/os/image/kernel-cmdline.sh +++ b/os/image/kernel-cmdline.sh @@ -30,6 +30,20 @@ # Intel's confidential-computing guest hardening names early PCI code as # something to disable, so it stays off. +# `systemd.gpt_auto=0` disables systemd-gpt-auto-generator, which reads the root +# disk's GPT and mounts or activates partitions found there. That table is +# host-controlled and unmeasured, so without this a partition the host appends +# (swap, /var, /home, ...) is acted on inside the guest. The rootfs is located +# by PARTLABEL and verified by dm-verity in the initramfs, so nothing we rely on +# depends on the generator. Every systemd since v252 parses the flag the same +# way, unlike `systemd.image_policy=` which older versions ignore and v254/v255 +# mishandle. +# +# `systemd.import_credentials=no` stops PID1 importing system credentials from +# SMBIOS and qemu fw_cfg, both host-controlled and unmeasured. Many units +# consume such credentials (sysusers, tmpfiles, udev rules, networkd, ...), so +# this closes that injection path at the source instead of masking each consumer. + # Emit the guest kernel command line. # $1 dm-verity root hash # $2 rootfs data size in bytes @@ -39,5 +53,6 @@ dstack_kernel_cmdline() { echo "console=ttyS0 init=/init panic=1 net.ifnames=0 biosdevname=0" \ "mce=off oops=panic pci=noearly random.trust_cpu=y" \ "random.trust_bootloader=n tsc=reliable no-kvmclock" \ + "systemd.gpt_auto=0 systemd.import_credentials=no" \ "dstack.rootfs_hash=$root_hash dstack.rootfs_size=$data_size" } diff --git a/os/mkosi/mkosi.profiles/prod/mkosi.conf b/os/mkosi/mkosi.profiles/prod/mkosi.conf index a571f6a71f..2b163409df 100644 --- a/os/mkosi/mkosi.profiles/prod/mkosi.conf +++ b/os/mkosi/mkosi.profiles/prod/mkosi.conf @@ -46,6 +46,24 @@ RemoveFiles= /usr/lib/systemd/system/systemd-logind.service /usr/lib/systemd/system/multi-user.target.wants/systemd-logind.service /usr/lib/systemd/logind.conf.d + # Generators that act on host-controlled, unmeasured input or are + # simply unreachable in this image. systemd.gpt_auto=0 on the measured + # command line already disables gpt-auto; removing these binaries is + # defence in depth and mirrors meta-dstack's systemd_%.bbappend, whose + # deletion of gpt-auto the mkosi rewrite had dropped. + # + # - gpt-auto: mounts/activates partitions from the host-controlled GPT. + # - hibernate-resume: reads resume= and the EFI HibernateLocation; the + # kernel drops CONFIG_PM so hibernation cannot happen anyway. + # - bless-boot / system-update: boot-assessment and offline-update + # handshakes this image never performs. + # - sysv / rc-local: no SysV init scripts or /etc/rc.local exist. + /usr/lib/systemd/system-generators/systemd-gpt-auto-generator + /usr/lib/systemd/system-generators/systemd-hibernate-resume-generator + /usr/lib/systemd/system-generators/systemd-bless-boot-generator + /usr/lib/systemd/system-generators/systemd-system-update-generator + /usr/lib/systemd/system-generators/systemd-sysv-generator + /usr/lib/systemd/system-generators/systemd-rc-local-generator # Suspend/hibernate units: the kernel drops CONFIG_PM entirely, so # these can only produce failed jobs. /usr/lib/systemd/system/suspend.target From 6615c1073d753ad933c59c894751a91177d2cb1e Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Fri, 16 Oct 2026 19:55:26 -0700 Subject: [PATCH 013/572] os/mkosi: pin prod generators and assert the hardening the fix relies on The Yocto parity spec was derived from the image recipe's package list, so it checked that required files exist but never that what Yocto stripped stays stripped: deletions in bbappends and PACKAGECONFIG removals were not covered, which is how gpt-auto survived the mkosi rewrite. The only inverse check was a hand-kept denylist that grew after each incident. - check-parity.py pins the exact set of system generators prod may ship, so a package upgrade that adds one fails the build. - acceptance.sh asserts the measured command line keeps systemd.gpt_auto=0 and systemd.import_credentials=no. - The kernel fragment states DMI_SYSFS, FW_CFG_SYSFS and PSTORE off, so check-kernel-config.sh guards them like the other hardening symbols; all three are already off, so the built kernel is unchanged. - Prod also drops the ssh generator (no sshd in prod) and the hibernate resume/clear binary and units the removed generator left behind. Signed-off-by: Kevin Wang --- os/mkosi/components/kernel/kernel.config | 7 +++++++ os/mkosi/mkosi.profiles/prod/mkosi.conf | 11 ++++++++++- os/mkosi/parity.json | 8 +++++++- os/mkosi/tests/acceptance.sh | 9 +++++++++ os/mkosi/tests/check-parity.py | 17 +++++++++++++++++ 5 files changed, 50 insertions(+), 2 deletions(-) diff --git a/os/mkosi/components/kernel/kernel.config b/os/mkosi/components/kernel/kernel.config index f21a9ea2e4..04ad9425a0 100644 --- a/os/mkosi/components/kernel/kernel.config +++ b/os/mkosi/components/kernel/kernel.config @@ -214,6 +214,13 @@ CONFIG_SUSPEND=n CONFIG_PM=n CONFIG_PM_SLEEP=n +# SMBIOS tables and qemu fw_cfg blobs are host-controlled and unmeasured; these +# expose them to userspace, where systemd imports them as system credentials. +# pstore restores records the firmware hands back from a previous boot. +CONFIG_DMI_SYSFS=n +CONFIG_FW_CFG_SYSFS=n +CONFIG_PSTORE=n + # Yocto dstack fragments and minimal guest-only hardware policy. CONFIG_9P_FS_POSIX_ACL=y CONFIG_SERIAL_8250_PCI=y diff --git a/os/mkosi/mkosi.profiles/prod/mkosi.conf b/os/mkosi/mkosi.profiles/prod/mkosi.conf index 2b163409df..799cf3e5b5 100644 --- a/os/mkosi/mkosi.profiles/prod/mkosi.conf +++ b/os/mkosi/mkosi.profiles/prod/mkosi.conf @@ -57,13 +57,22 @@ RemoveFiles= # kernel drops CONFIG_PM so hibernation cannot happen anyway. # - bless-boot / system-update: boot-assessment and offline-update # handshakes this image never performs. - # - sysv / rc-local: no SysV init scripts or /etc/rc.local exist. + # - sysv / rc-local: every shipped SysV script has a native unit, and + # there is no /etc/rc.local. + # - ssh: binds sshd to AF_VSOCK, but prod ships no sshd. + # + # parity.json pins the generators prod may keep. /usr/lib/systemd/system-generators/systemd-gpt-auto-generator /usr/lib/systemd/system-generators/systemd-hibernate-resume-generator + /usr/lib/systemd/systemd-hibernate-resume + /usr/lib/systemd/system/systemd-hibernate-resume.service + /usr/lib/systemd/system/systemd-hibernate-clear.service + /usr/lib/systemd/system/sysinit.target.wants/systemd-hibernate-clear.service /usr/lib/systemd/system-generators/systemd-bless-boot-generator /usr/lib/systemd/system-generators/systemd-system-update-generator /usr/lib/systemd/system-generators/systemd-sysv-generator /usr/lib/systemd/system-generators/systemd-rc-local-generator + /usr/lib/systemd/system-generators/systemd-ssh-generator # Suspend/hibernate units: the kernel drops CONFIG_PM entirely, so # these can only produce failed jobs. /usr/lib/systemd/system/suspend.target diff --git a/os/mkosi/parity.json b/os/mkosi/parity.json index 2b2a627efa..77d9f8d453 100644 --- a/os/mkosi/parity.json +++ b/os/mkosi/parity.json @@ -166,12 +166,18 @@ "usr/bin/login", "usr/bin/loginctl", "usr/sbin/agetty", - "usr/lib/systemd/system-generators/systemd-getty-generator", "usr/lib/systemd/system/getty@.service", "usr/lib/systemd/system/serial-getty@.service", "usr/lib/systemd/system/debug-shell.service", "usr/lib/systemd/system/systemd-logind.service" ], + "prod_allowed_generators": [ + "systemd-debug-generator", + "systemd-fstab-generator", + "systemd-run-generator", + "systemd-tpm2-generator", + "zfs-mount-generator" + ], "required_ldconfig_entries": [ "libnvidia-ml.so.1", "libnvidia-container.so.1", diff --git a/os/mkosi/tests/acceptance.sh b/os/mkosi/tests/acceptance.sh index 0f34d11ce3..96d919338d 100755 --- a/os/mkosi/tests/acceptance.sh +++ b/os/mkosi/tests/acceptance.sh @@ -251,6 +251,15 @@ if grep -q 'random.trust_bootloader' "$D/scripts/make-release-artifacts.sh"; the echo 'kernel command line must not be restated outside kernel-cmdline.sh' >&2 exit 1 fi +# These keep the guest from acting on the host-controlled GPT and on host-supplied +# system credentials; they only protect anything while they stay measured. +cmdline=$(. "$D/../image/kernel-cmdline.sh" && dstack_kernel_cmdline hash size) +for flag in systemd.gpt_auto=0 systemd.import_credentials=no; do + if [[ " $cmdline " != *" $flag "* ]]; then + echo "kernel command line lacks $flag" >&2 + exit 1 + fi +done grep -q 'Archiving UKI image' "$D/../image/assemble.sh" grep -Fq "FLAVORS=\${FLAVORS:-prod}" "$D/build.sh" # A cache hit must never be able to answer the question repro-check asks. diff --git a/os/mkosi/tests/check-parity.py b/os/mkosi/tests/check-parity.py index ebfaab9839..6c324ed263 100755 --- a/os/mkosi/tests/check-parity.py +++ b/os/mkosi/tests/check-parity.py @@ -75,6 +75,23 @@ def resolves_in_rootfs(root: str, path: str) -> bool: for path in spec.get("prod_forbidden_paths", []): if os.path.lexists(os.path.join(rootfs, path)): missing.append(f"prod contains forbidden path:/{path}") + # Generators run as root before any unit and act on whatever they find, so + # prod pins the exact set: a package upgrade that ships a new one fails the + # build instead of silently widening what the host can influence. + generators = { + os.path.basename(path) + for pattern in ( + "usr/lib/systemd/system-generators/*", + "usr/local/lib/systemd/system-generators/*", + "etc/systemd/system-generators/*", + ) + for path in glob.glob(os.path.join(rootfs, pattern)) + } + allowed = set(spec["prod_allowed_generators"]) + for name in sorted(generators - allowed): + missing.append(f"prod contains unexpected generator: {name}") + for name in sorted(allowed - generators): + missing.append(f"prod is missing allowed generator: {name}") for path, expected in spec.get("required_symlink_resolutions", {}).items(): # Which netfilter frontend the image programs is decided by a symlink, and # on this backend that symlink comes from the distribution's default rather From 0a210869d7fdbf29558738781070e62950818f6b Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 19 Oct 2026 08:04:09 -0700 Subject: [PATCH 014/572] chore(release): bump version to 0.6.2 Signed-off-by: Kevin Wang --- dstack/Cargo.lock | 114 +++++++++--------- dstack/Cargo.toml | 2 +- os/mkosi/mkosi.conf | 2 +- os/mkosi/versions.env | 2 +- .../meta-dstack/conf/distro/dstack.conf | 2 +- 5 files changed, 61 insertions(+), 61 deletions(-) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 31a97f3894..bc08ab92b0 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -801,7 +801,7 @@ checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "cached-cell" -version = "0.6.1" +version = "0.6.2" dependencies = [ "tokio", ] @@ -820,7 +820,7 @@ dependencies = [ [[package]] name = "cc-eventlog" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "digest 0.10.7", @@ -840,7 +840,7 @@ dependencies = [ [[package]] name = "cert-client" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "dstack-guest-agent-rpc", @@ -860,7 +860,7 @@ dependencies = [ [[package]] name = "certbot" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "bon", @@ -888,7 +888,7 @@ dependencies = [ [[package]] name = "certbot-cli" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "certbot", @@ -1346,7 +1346,7 @@ dependencies = [ [[package]] name = "ct_monitor" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "clap", @@ -1820,7 +1820,7 @@ dependencies = [ [[package]] name = "dstack-api-auth" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "base64 0.22.1", @@ -1832,7 +1832,7 @@ dependencies = [ [[package]] name = "dstack-attest" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -1881,7 +1881,7 @@ dependencies = [ [[package]] name = "dstack-auth" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "clap", @@ -1892,14 +1892,14 @@ dependencies = [ [[package]] name = "dstack-build-info" -version = "0.6.1" +version = "0.6.2" dependencies = [ "git-version", ] [[package]] name = "dstack-cli" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "clap", @@ -1916,7 +1916,7 @@ dependencies = [ [[package]] name = "dstack-cli-core" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "dstack-types", @@ -1930,7 +1930,7 @@ dependencies = [ [[package]] name = "dstack-gateway" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "arc-swap", @@ -1999,7 +1999,7 @@ dependencies = [ [[package]] name = "dstack-gateway-rpc" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "parity-scale-codec", @@ -2012,7 +2012,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "base64 0.22.1", @@ -2068,7 +2068,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent-rpc" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "hex", @@ -2084,7 +2084,7 @@ dependencies = [ [[package]] name = "dstack-guest-agent-simulator" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "cc-eventlog", @@ -2106,7 +2106,7 @@ dependencies = [ [[package]] name = "dstack-kms" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "cc-eventlog", @@ -2151,7 +2151,7 @@ dependencies = [ [[package]] name = "dstack-kms-rpc" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "fs-err", @@ -2165,7 +2165,7 @@ dependencies = [ [[package]] name = "dstack-mr" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "binrw", @@ -2205,7 +2205,7 @@ dependencies = [ [[package]] name = "dstack-netd-rpc" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "prost 0.13.5", @@ -2217,7 +2217,7 @@ dependencies = [ [[package]] name = "dstack-nvidia-attest-proxy" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "base64 0.22.1", @@ -2245,7 +2245,7 @@ dependencies = [ [[package]] name = "dstack-tee-simulator" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -2282,7 +2282,7 @@ dependencies = [ [[package]] name = "dstack-types" -version = "0.6.1" +version = "0.6.2" dependencies = [ "ciborium", "hex", @@ -2300,7 +2300,7 @@ dependencies = [ [[package]] name = "dstack-util" -version = "0.6.1" +version = "0.6.2" dependencies = [ "aes-gcm", "anyhow", @@ -2364,7 +2364,7 @@ dependencies = [ [[package]] name = "dstack-verifier" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "cc-eventlog", @@ -2400,7 +2400,7 @@ dependencies = [ [[package]] name = "dstack-vmm" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "base64 0.22.1", @@ -2463,7 +2463,7 @@ dependencies = [ [[package]] name = "dstack-vmm-rpc" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "parity-scale-codec", @@ -2476,7 +2476,7 @@ dependencies = [ [[package]] name = "dstack-volume" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "binrw", @@ -2497,7 +2497,7 @@ dependencies = [ [[package]] name = "dstackup" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "clap", @@ -3173,7 +3173,7 @@ dependencies = [ [[package]] name = "guest-api" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "http-client", @@ -3434,7 +3434,7 @@ dependencies = [ [[package]] name = "host-api" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "http-client", @@ -3480,7 +3480,7 @@ dependencies = [ [[package]] name = "http-client" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "http-body-util", @@ -3889,7 +3889,7 @@ checksum = "d8972d5be69940353d5347a1344cb375d9b457d6809b428b05bb1ca2fb9ce007" [[package]] name = "iohash" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "blake2", @@ -4124,7 +4124,7 @@ dependencies = [ [[package]] name = "key-provider-client" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "dstack-types", @@ -4270,7 +4270,7 @@ checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "load_config" -version = "0.6.1" +version = "0.6.2" dependencies = [ "figment", "rocket", @@ -4280,7 +4280,7 @@ dependencies = [ [[package]] name = "local-key-provider" -version = "0.6.1" +version = "0.6.2" dependencies = [ "blake2", "dcap-qvl", @@ -4342,7 +4342,7 @@ checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" [[package]] name = "lspci" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "insta", @@ -4512,7 +4512,7 @@ dependencies = [ [[package]] name = "mock-attestation" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "axum", @@ -4740,7 +4740,7 @@ dependencies = [ [[package]] name = "nsm-attest" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "aws-nitro-enclaves-nsm-api", @@ -4752,7 +4752,7 @@ dependencies = [ [[package]] name = "nsm-qvl" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "ciborium", @@ -4934,7 +4934,7 @@ dependencies = [ [[package]] name = "nvattest" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "serde", @@ -5418,7 +5418,7 @@ dependencies = [ [[package]] name = "pki-fetch" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "pem", @@ -5844,7 +5844,7 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "ra-rpc" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "bon", @@ -5866,7 +5866,7 @@ dependencies = [ [[package]] name = "ra-tls" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "bon", @@ -6371,7 +6371,7 @@ dependencies = [ [[package]] name = "rocket-vsock-listener" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "derive_more 2.1.1", @@ -6951,7 +6951,7 @@ dependencies = [ [[package]] name = "serde-duration" -version = "0.6.1" +version = "0.6.2" dependencies = [ "serde", "serde_json", @@ -7173,7 +7173,7 @@ dependencies = [ [[package]] name = "sev-snp-attest" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "fs-err", @@ -7184,7 +7184,7 @@ dependencies = [ [[package]] name = "sev-snp-qvl" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "hex", @@ -7363,7 +7363,7 @@ checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" [[package]] name = "size-parser" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "serde", @@ -7532,7 +7532,7 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "supervisor" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "bon", @@ -7555,7 +7555,7 @@ dependencies = [ [[package]] name = "supervisor-client" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "clap", @@ -7708,7 +7708,7 @@ dependencies = [ [[package]] name = "tdx-attest" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "cc-eventlog", @@ -8092,7 +8092,7 @@ checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" [[package]] name = "tpm-attest" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "dstack-types", @@ -8111,7 +8111,7 @@ dependencies = [ [[package]] name = "tpm-qvl" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "base64 0.22.1", @@ -8134,7 +8134,7 @@ dependencies = [ [[package]] name = "tpm-types" -version = "0.6.1" +version = "0.6.2" dependencies = [ "cc-eventlog", "dstack-types", @@ -8145,7 +8145,7 @@ dependencies = [ [[package]] name = "tpm2" -version = "0.6.1" +version = "0.6.2" dependencies = [ "anyhow", "hex", diff --git a/dstack/Cargo.toml b/dstack/Cargo.toml index 8877f62967..d5e45080cb 100644 --- a/dstack/Cargo.toml +++ b/dstack/Cargo.toml @@ -5,7 +5,7 @@ # SPDX-License-Identifier: Apache-2.0 [workspace.package] -version = "0.6.1" +version = "0.6.2" authors = ["Kevin Wang ", "Leechael "] edition = "2021" license = "MIT" diff --git a/os/mkosi/mkosi.conf b/os/mkosi/mkosi.conf index 185087377b..a61a1ef89d 100644 --- a/os/mkosi/mkosi.conf +++ b/os/mkosi/mkosi.conf @@ -22,7 +22,7 @@ Format=tar # order, so declaring Output first silently yields "--rootfs.tar". # ImageVersion is checked against DSTACK_VERSION by tests/acceptance.sh. ImageId=dstack -ImageVersion=0.6.1 +ImageVersion=0.6.2 Output=%i-%v-rootfs CompressOutput=no # Must stay empty. The default is [uki, kernel, initrd], and the kernel split diff --git a/os/mkosi/versions.env b/os/mkosi/versions.env index fcebc7b159..92b5cd8152 100644 --- a/os/mkosi/versions.env +++ b/os/mkosi/versions.env @@ -20,7 +20,7 @@ RUST_STD_TOOLCHAIN_SHA256=5f106805ed86ebf8df287039e53a45cf974391ef4d088c2760776b GO_TOOLCHAIN_VERSION=1.26.2 GO_TOOLCHAIN_SHA256=990e6b4bbba816dc3ee129eaeaf4b42f17c2800b88a2166c265ac1a200262282 NITRO_TPM_TOOLS_REVISION=d76d6eeebd4169b00a3c3af9858852d48f40e748 -DSTACK_VERSION=0.6.1 +DSTACK_VERSION=0.6.2 DSTACK_CODENAME=trixie OVMF_VARIANT=pre202505 # Must match SRCREV in meta-dstack's dstack-ovmf_git.bb: a generic OVMF diff --git a/os/yocto/layers/meta-dstack/conf/distro/dstack.conf b/os/yocto/layers/meta-dstack/conf/distro/dstack.conf index 534e3ff031..e08076ef5e 100644 --- a/os/yocto/layers/meta-dstack/conf/distro/dstack.conf +++ b/os/yocto/layers/meta-dstack/conf/distro/dstack.conf @@ -7,7 +7,7 @@ DISTRO = "dstack" DISTRO_NAME = "dstack" DISTRO_FEATURES:append = " virtualization seccomp systemd usrmerge security dm-verity ipv6" -DISTRO_VERSION = "0.6.1" +DISTRO_VERSION = "0.6.2" DISTROOVERRIDES = "poky:dstack" INITRAMFS_IMAGE = "" From 4e60f321d3949312b3ab8ecc9649b05b9a8a7b25 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Sun, 18 Oct 2026 09:05:01 -0700 Subject: [PATCH 015/572] feat(qemu-acpi): model guest NUMA nodes without PXB expanders A QEMU wrapper can give a CVM guest NUMA nodes (SRAT and CPU _PXM) while leaving every device on the root bus. Such a layout depends only on the vCPU count and memory size, so the KMS can reproduce it, unlike the multi-PXB layout whose expander _CRS comes from firmware enumeration. NumaNodeConfig.pxb_bus becomes optional and is omitted when absent, so existing vm_configs deserialize and serialize unchanged and their MRs and verifier cache keys stay the same. Mixed layouts are still rejected. An older KMS fails to parse a node without pxb_bus and refuses the CVM. dstack-mr measure gains --numa-nodes, and both differential harnesses cover the new layout. Signed-off-by: Kevin Wang --- dstack/crates/qemu-acpi/examples/dump.rs | 8 +++- dstack/crates/qemu-acpi/fixtures/README.md | 4 ++ ...-11.1-q35-hotplug-off-numa2-plain-base.bin | Bin 0 -> 9536 bytes ...1.1-q35-hotplug-off-numa2-plain-loader.bin | Bin 0 -> 4096 bytes ...-11.1-q35-hotplug-off-numa2-plain-rsdp.bin | Bin 0 -> 20 bytes .../qemu-acpi/scripts/differential-qemu.sh | 20 ++++++--- .../qemu-acpi/scripts/differential-random.py | 40 +++++++++++++++--- dstack/crates/qemu-acpi/src/golden_tests.rs | 26 ++++++++++++ dstack/crates/qemu-acpi/src/topology.rs | 13 ++++-- dstack/dstack-mr/cli/src/main.rs | 18 +++++--- dstack/dstack-mr/src/acpi.rs | 2 +- dstack/dstack-types/src/lib.rs | 26 +++++++++++- dstack/vmm/src/app.rs | 2 +- 13 files changed, 130 insertions(+), 29 deletions(-) create mode 100644 dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin create mode 100644 dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-loader.bin create mode 100644 dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin diff --git a/dstack/crates/qemu-acpi/examples/dump.rs b/dstack/crates/qemu-acpi/examples/dump.rs index 312ab4feca..eb531c3a6d 100644 --- a/dstack/crates/qemu-acpi/examples/dump.rs +++ b/dstack/crates/qemu-acpi/examples/dump.rs @@ -29,11 +29,15 @@ fn main() -> Result<(), Box> { let memory_size = optional(&mut args, 2u64 << 30)?; let volumes = optional(&mut args, 0)?; let pic = optional::(&mut args, 0)? == 1; - // Comma-separated PXB bus of each NUMA node; empty keeps the legacy layout. + // Comma-separated PXB bus of each NUMA node, `-` for none; empty keeps the + // legacy layout. let numa_nodes = optional::(&mut args, String::new())? .split(',') .filter(|bus| !bus.is_empty()) - .map(|bus| bus.parse().map(|bus| NumaNode { pxb_bus: Some(bus) })) + .map(|bus| match bus { + "-" => Ok(NumaNode { pxb_bus: None }), + bus => bus.parse().map(|bus| NumaNode { pxb_bus: Some(bus) }), + }) .collect::>()?; // Devices appended after the root ports: `e` endpoint, `r` root port. let extra_root_devices = optional::(&mut args, String::new())? diff --git a/dstack/crates/qemu-acpi/fixtures/README.md b/dstack/crates/qemu-acpi/fixtures/README.md index e6fb7aa49a..2b2d11942e 100644 --- a/dstack/crates/qemu-acpi/fixtures/README.md +++ b/dstack/crates/qemu-acpi/fixtures/README.md @@ -55,6 +55,10 @@ for each compatibility family cover the Cartesian product of: whose PXBs sit on buses 5, 6 and 8 (12 vCPUs, 6 GiB, two NICs), together with their loader and RSDP blobs. +`qemu-11.1-q35-hotplug-off-numa2-plain-*.bin` capture two guest NUMA nodes +without PXBs (8 vCPUs, 2 GiB, one NIC, two GPU root ports and one extra +endpoint on the root bus). + `qemu-11.1-q35-one-nic.bin` is an untrimmed byte-for-byte regression fixture. Fixture names identify the emulated compatibility version, not necessarily the source tree's release number. diff --git a/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin new file mode 100644 index 0000000000000000000000000000000000000000..9e3f1f418c55cba227e59a06fcb8572e8c339189 GIT binary patch literal 9536 zcmbVSO>7&-8J*$pYDr3zL|gt*BE?D36fF|UvYnv6B9}j6B+4{bj#JP8Da&dlCqRfK zI=DdqTP_;MrzV1f9u-5m=hSNh^we8!4bVe#=_Qv2Xo0wwvhSO3hn!hbMpOdg&Nuts z_syH#owwXorQrEX;{X4Y{L*^&86l)7UiOy#`QmF0Zyq0sl+>newidfCT6aptYFnlv zG1__`M@;#!feG3QEAMLB% z+?S<2-46A9lIAW-wQ%@)ZY5qW`Sr}frTtr?I~kRtb8zM(9>5nb{pBD2#oyFFocX$b z`p;hduyc@nxZ_3+J6-qg{f-dmnBBkSCc9Jdh{%WzX5kGXHo6jjil%QI}UQev9t&|0~CE67+m8O0-f}pB{D1v1%m5HT$Jyd2~5D^Q&ao(qR zfa;K#$gi*w#RN8ph^e6wp_qUwCPHFjGzuG4Og)0AAf|>!nF*+3A|$4+5>re)f|z1z zXpEV9@CZ$vaZ6`hF*P*KOg(snrp|<=GohFony_^uG<7B|ok>e)($qKbk9J6$eSvtpTod`{xuBFqpbh@@qgr?4vr88yeOxZdSnmW^#&a|a7ZRdaU= zGnUSbtrMZCbKKH7Zs{Dibs{u%PFOl8ES(d!PK2h;tfez+>CDEr)(xdllin_ z>NWmp#nfy3)6CQhH$q}+Cz-Qq&RI3*?3xI6WC_=+P4JHiKV3L6vOfpb|2?I5lFi?X@ z25K*k3=|;_ zgAR$Q=N1NvNY5<{6p@}=GEjtiZplCq;%EDrHY`*er1#a2)kFG0`bmN|h1_)QioY%o z#@==BY>Pv8?9ff+F4V4g%`w<+Ge0@*ranlBG4<>Bws=5&ZXDmW?z`LWgrF7@HS?{# z)g*krpdTKjC-{+pgVO%wNq72#aWNK!LkXzSawA0~!VJIE?R2=a7)r-|Bhw9CH#s{U zZa0R~ao@;vL)XCxJ00#phSG80$aF*J^+`J&ZcK*Kao@;vL+9y?oep;^L+QBBPM6KK zs|}vHOu=i^^7;HFk*(k2$Ji@l*I$fMlODe|nq^;~o-VFRJjc#>jjQv^Z@$xgWB1qd zZ*9H(=I&dYTW^b&^ct%x!D*Ut-KzXD{bgFFZ{sOD7SeT@`ZDdNTX&zQpdjYGMtMzo zwKZRQ&HAg-E5DMbuZk2=&#RZ5*4-&WMm@j0IuCfMus+|~Tkc$cfyRb0@VEj23wf%{ zkK5z9a>84${4#Rj?r)3Vd62h5O-ap#orBc=wi}`Ld2UCky~yntwJ&fxPVI}_PEh+2 zx0BRl3G=A)&P`!{7*-0aFu7cTSo#Bn~Dc^K}+k>33DVEn`V4Y#+y<@QkT)9xtH!E-}X zN#|2{^F9rFL+ox~cq2e`z7YtDw#4ohK)ajtf~OqgH$23?AvWn8+61t*Fj~&g6r(ua z3L#MuiMH^PgevGnZuC25!RU5xj6PKLG4Ha!o<8DGjXvXsMu|!9?u?kut{VyW67*KM z6NhKy=vw!Fj_V?iH3%QP(!sUi9MTnnE3;l$pG>)qz*7sl7tW32Mc8_Z#E9*kTUf9$V(%cG?J}Rvh#QZMfEa+(a?QmKU*ZCvZedk z+z8BDkIjvQ^DW}dPB(RMUGhZ~E?*blIh4bOgub(d#3+IcO`C>Ys zY~53OFVathkY3!%_4CE!;e2s3Up$=e5*}@Z^T7rB`4Wk6zJ!@C5zhA#9(aZG;byC! zFPRMIOPcwT{d~Ez@Bx@uyPQ8S0>2_pprtHZm}HaS*Rk{(@|BeP$NL!(!P6vsdh{i$ z@^SicS~}>LX?0w`#qP)Hew@MUMj`&C-e2-@$FHwmkA8j8CnBsjn|JVL^Y6SzbgVt! z^m>2#FYoz${J{_LHZ;fvU<5%fLXHsN7gpC@#vN;aO2lh0?D=dP0vW|!t@=39FyKc83;^>(57YB$0I;@h|JAfy{dnf!01FnO;)k(iHz|YZrORae& z;&$A0){7}=t-C*dF-qbHNqZ&ze#US8D@FS9=&R(2d2GtmuFzMNzLuTV-i4K72~)uT z9}va5K{JV8`gDe#a!*ucM|6b5iFs4p#P(c79slR*m#_9&6S!SASdJS%NAJ;FdyC%X z`hw0K$BKzNHGCV`Np~EleDrZtIL~IqDI$HZx$gB-r*LR#Bw068g|&Bubj}G$unE6X z2o7CDU|y)B7<5F@QNc~*zj5+JpYZ<{baE}>PYOJL)*oJ7L@d}+w}bY)?vIEV{rKrk z^zdMnKeVEM`dj3|rVj> zgFZv>WX)gkbsyNCaM-isN!CwHF38j`Do!Z?@`(ikK!r@iD#oFX5hxC~za%j!C$$)dN=#t~pb$tu zC4d>InOyrlfqET)xIhs|kO@HHN3Q+k>bnATFALPY17ZJ-0k+>piGhIw>VHb&e<#o% z8-Vx=nQ;%&Mv47vf&N$m#2W_4{#a!Oh7ceQU?krG6!~8T=zk!#A>Vq6!v7`E?gv1u zL4o}Pk^gj52R8p346yws18l#=0NZbaWIrYOPY`Gh2M}9OEB%w${vfyh1GQUNpl(L- fKZ*9k>JSkM{6DI7Gz3ONU^E0qLtr!n1|kFi&GxPS literal 0 HcmV?d00001 diff --git a/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin b/dstack/crates/qemu-acpi/fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin new file mode 100644 index 0000000000000000000000000000000000000000..6128229d5f6b03fa69406ffecb3d06f5ff6808e3 GIT binary patch literal 20 bcmWFvc2Nij2~uEi@^|(KR$$;zWncgRF|Y&N literal 0 HcmV?d00001 diff --git a/dstack/crates/qemu-acpi/scripts/differential-qemu.sh b/dstack/crates/qemu-acpi/scripts/differential-qemu.sh index 07bce40535..1b34e0c349 100755 --- a/dstack/crates/qemu-acpi/scripts/differential-qemu.sh +++ b/dstack/crates/qemu-acpi/scripts/differential-qemu.sh @@ -24,17 +24,19 @@ rust_dump="$workspace/target/debug/examples/dump" run_case() { local version=$1 topology=$2 - # pxb_buses: one guest NUMA node per bus, GPUs split evenly across them. - local hugepages=0 gpus=0 pxb_buses=() + # pxb_buses: one guest NUMA node per bus, GPUs split evenly across them; + # plain_nodes: guest NUMA nodes without expanders, GPUs on the root bus. + local hugepages=0 gpus=0 pxb_buses=() plain_nodes=0 hotplug_off=0 case "$topology" in normal) ;; numa) hugepages=1 ;; numa-pxb) hugepages=1; gpus=8; pxb_buses=(5) ;; numa2-pxb) hugepages=1; gpus=8; pxb_buses=(5 10) ;; numa4-pxb-adjacent) hugepages=1; gpus=4; pxb_buses=(5 6 8 9) ;; + numa2-plain) gpus=4; plain_nodes=2; hotplug_off=1 ;; *) echo "invalid internal topology: $topology" >&2; exit 2 ;; esac - local nodes=${#pxb_buses[@]} + local nodes=$((${#pxb_buses[@]} + plain_nodes)) ((hugepages && nodes == 0)) && nodes=1 local output="$tmp/$version-$topology" @@ -58,26 +60,30 @@ run_case() { -numa "node,nodeid=$node,cpus=$((node * 8 / nodes))-$(((node + 1) * 8 / nodes - 1)),memdev=mem$node" -object "memory-backend-file,id=mem$node,size=$((2048 / nodes))M,mem-path=/dev/hugepages,share=on,prealloc=no" ) - if ((gpus)); then + if ((gpus && !plain_nodes)); then args+=(-device "pxb-pcie,id=pcie.node$node,bus=pcie.0,addr=$((10 + node)),numa_node=$node,bus_nr=${pxb_buses[$node]}") fi done if ((gpus)); then args+=(-object "iommufd,id=iommufd0") for ((index = 0; index < gpus; index++)); do + local bus=pcie.0 + ((plain_nodes)) || bus=pcie.node$((index * nodes / gpus)) args+=( - -device "pcie-root-port,id=pci.$index,bus=pcie.node$((index * nodes / gpus)),chassis=$index" + -device "pcie-root-port,id=pci.$index,bus=$bus,chassis=$index" -device "vfio-pci,host=00:00.0,bus=pci.$index,iommufd=iommufd0" ) done fi + ((hotplug_off)) && args+=(-global ICH9-LPC.acpi-pci-hotplug-with-bridge-support=off) QEMU_ACPI_COMPAT_VER="$version" QEMU_ACPI_DUMP_DIR="$output" \ "$qemu" "${args[@]}" -machine "$machine" local numa="" ((nodes > 1)) && numa=$(IFS=,; echo "${pxb_buses[*]}") + ((plain_nodes)) && numa=$(printf -- '-,%.0s' $(seq "$plain_nodes")) QEMU_ACPI_OUTPUT_DIR="$output/rust" \ - "$rust_dump" 2 8 "$version" "$gpus" 0 "$hugepages" 1 0 0 0 $((2048 << 20)) 0 0 "$numa" + "$rust_dump" 2 8 "$version" "$gpus" 0 "$hugepages" 1 "$hotplug_off" 0 0 $((2048 << 20)) 0 0 "$numa" for blob in tables loader rsdp; do cmp "$output/$blob.bin" "$output/rust/$blob.bin" done @@ -85,7 +91,7 @@ run_case() { } for version in 8.0.0 8.2.0 9.0.0 9.1.0 9.2.0 10.0.0 10.2.0 11.0.0 11.1.0 11.2.0; do - for topology in normal numa numa-pxb numa2-pxb numa4-pxb-adjacent; do + for topology in normal numa numa-pxb numa2-pxb numa4-pxb-adjacent numa2-plain; do run_case "$version" "$topology" done done diff --git a/dstack/crates/qemu-acpi/scripts/differential-random.py b/dstack/crates/qemu-acpi/scripts/differential-random.py index 9f688936bc..405248c2a5 100755 --- a/dstack/crates/qemu-acpi/scripts/differential-random.py +++ b/dstack/crates/qemu-acpi/scripts/differential-random.py @@ -39,7 +39,8 @@ class Case: smm: bool = False pic: bool = False pci_hole64_size: int = 0 - # PXB bus of each guest NUMA node; empty keeps the layout `hugepages` implies. + # PXB bus of each guest NUMA node, None for a node without one; empty + # keeps the layout `hugepages` implies. pxb_buses: tuple = () # Devices a QEMU wrapper appends to the root bus: "e" endpoint, "r" root port. extra: str = "" @@ -51,7 +52,7 @@ def numa_nodes(self): def pxbs(self): """PXB bus of each node that has one, explicit or implied.""" if self.pxb_buses: - return self.pxb_buses + return tuple(bus for bus in self.pxb_buses if bus is not None) return (5,) if self.hugepages and self.gpus else () @@ -106,6 +107,28 @@ def fixed_cases(): pxb_buses=(5, 7), extra="eree", ), + # Guest NUMA nodes without expanders: SRAT and _PXM only. + Case(cpus=2, pxb_buses=(None, None)), + Case(cpus=12, memory_mib=6144, nics=2, pxb_buses=(None,) * 3), + Case( + cpus=192, + memory_mib=8192, + gpus=4, + hotplug_off=True, + pci_hole64_size=1 << 43, + pxb_buses=(None, None), + extra="eeeee", + ), + Case( + version="9.2.0", + cpus=4, + hugepages=True, + gpus=2, + switches=1, + hotplug_off=True, + pxb_buses=(None, None), + extra="er", + ), ] return cases @@ -114,11 +137,14 @@ def random_case(rng): hugepages = rng.choice([False, True]) gpus = rng.randint(0, 8) switches = rng.randint(0, 4) if gpus else 0 - nodes = rng.choice([0, 0, 2, 3, 4]) if hugepages else 0 + nodes = rng.choice([0, 0, 2, 3, 4]) pxb_buses = [] - for _ in range(nodes): - pxb_buses.append(pxb_buses[-1] + rng.randint(1, 6) if pxb_buses else 5) - pxbs = len(pxb_buses) or int(hugepages and gpus > 0) + if hugepages: + for _ in range(nodes): + pxb_buses.append(pxb_buses[-1] + rng.randint(1, 6) if pxb_buses else 5) + else: + pxb_buses = [None] * nodes + pxbs = sum(bus is not None for bus in pxb_buses) or int(hugepages and gpus > 0) pxb = pxbs > 0 available = 26 - pxbs passthrough = switches if pxb else gpus + switches @@ -365,7 +391,7 @@ def run_case(case, image, rust_dump, output): str(case.memory_mib * 1024 * 1024), str(case.volumes), str(int(case.pic)), - ",".join(map(str, case.pxb_buses)), + ",".join("-" if bus is None else str(bus) for bus in case.pxb_buses), case.extra, ], check=True, diff --git a/dstack/crates/qemu-acpi/src/golden_tests.rs b/dstack/crates/qemu-acpi/src/golden_tests.rs index 2fb64fb168..0fe2f6448d 100644 --- a/dstack/crates/qemu-acpi/src/golden_tests.rs +++ b/dstack/crates/qemu-acpi/src/golden_tests.rs @@ -89,6 +89,31 @@ mod tests { Ok(()) } + /// Two nodes without expanders: GPUs and a wrapper's endpoint stay on + /// the root bus, and only the SRAT and the CPUs' `_PXM` carry the nodes. + #[test] + fn numa_nodes_without_pxb_match_qemu_byte_for_byte() -> Result<(), Error> { + let mut c = config(1, 0); + c.cpu_count = 8; + c.numa_nodes = vec![NumaNode { pxb_bus: None }; 2]; + c.num_gpus = 2; + c.extra_root_devices = vec![RootBusDevice::Endpoint]; + c.hotplug_off = true; + let actual = build(&c)?; + let expected = include_bytes!("../fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-base.bin"); + assert_eq!(&actual.tables[..expected.len()], expected); + assert!(actual.tables[expected.len()..].iter().all(|b| *b == 0)); + assert_eq!( + actual.loader, + include_bytes!("../fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-loader.bin") + ); + assert_eq!( + actual.rsdp, + include_bytes!("../fixtures/qemu-11.1-q35-hotplug-off-numa2-plain-rsdp.bin") + ); + Ok(()) + } + #[test] fn numa_layouts_qemu_cannot_build_are_rejected() { let nodes = |buses: &[u8]| { @@ -107,6 +132,7 @@ mod tests { 2, vec![NumaNode { pxb_bus: None }, NumaNode { pxb_bus: Some(5) }], ), + (3, vec![NumaNode { pxb_bus: None }; 2]), ] { c.cpu_count = cpus; c.numa_nodes = buses; diff --git a/dstack/crates/qemu-acpi/src/topology.rs b/dstack/crates/qemu-acpi/src/topology.rs index 8e2a66f639..40f74ca63f 100644 --- a/dstack/crates/qemu-acpi/src/topology.rs +++ b/dstack/crates/qemu-acpi/src/topology.rs @@ -89,8 +89,8 @@ pub enum TopologyError { }, #[error("{0} NUMA nodes exceed QEMU's limit of 128")] TooManyNumaNodes(usize), - #[error("every explicit NUMA node needs a PXB expander")] - NumaNodeWithoutPxb, + #[error("NUMA nodes must either all have a PXB expander or none")] + MixedPxbNumaNodes, #[error("{0} PXB expanders do not fit on the root bus")] TooManyPxbs(usize), #[error("PXB bus numbers must be nonzero and distinct: {0:?}")] @@ -125,8 +125,13 @@ impl MachineConfig { return Err(TopologyError::TooManyNumaNodes(nodes)); } // Node `i`'s expander sits on slot 0x10 + i only if every node has one. - if self.numa_nodes.iter().any(|node| node.pxb_bus.is_none()) { - return Err(TopologyError::NumaNodeWithoutPxb); + let pxbs = self + .numa_nodes + .iter() + .filter(|n| n.pxb_bus.is_some()) + .count(); + if pxbs != 0 && pxbs != nodes { + return Err(TopologyError::MixedPxbNumaNodes); } for (what, count) in [ ("cpu_count", u64::from(self.cpu_count)), diff --git a/dstack/dstack-mr/cli/src/main.rs b/dstack/dstack-mr/cli/src/main.rs index 104d6cf21b..4f67c5182d 100644 --- a/dstack/dstack-mr/cli/src/main.rs +++ b/dstack/dstack-mr/cli/src/main.rs @@ -66,6 +66,11 @@ struct MachineConfig { #[arg(long, value_delimiter = ',')] numa_pxb_buses: Vec, + /// Number of guest NUMA nodes without PXB expanders (every device on the + /// root bus) + #[arg(long, conflicts_with = "numa_pxb_buses")] + numa_nodes: Option, + /// Number of GPUs #[arg(long, default_value = "0")] num_gpus: u32, @@ -132,11 +137,14 @@ fn main() -> Result<()> { // The image declares its OVMF layout. Older metadata.json files // predate the field, so fall back to the only layout that existed. let ovmf_variant = image_info.ovmf_variant.unwrap_or_default(); - let numa_nodes: Vec<_> = config - .numa_pxb_buses - .iter() - .map(|&bus| dstack_types::NumaNodeConfig { pxb_bus: bus }) - .collect(); + let numa_nodes = match config.numa_nodes { + Some(nodes) => vec![dstack_types::NumaNodeConfig { pxb_bus: None }; nodes], + None => config + .numa_pxb_buses + .iter() + .map(|&bus| dstack_types::NumaNodeConfig { pxb_bus: Some(bus) }) + .collect(), + }; let machine = Machine::builder() .cpu_count(config.cpu) diff --git a/dstack/dstack-mr/src/acpi.rs b/dstack/dstack-mr/src/acpi.rs index facbdefc85..15d026ea26 100644 --- a/dstack/dstack-mr/src/acpi.rs +++ b/dstack/dstack-mr/src/acpi.rs @@ -40,7 +40,7 @@ impl Machine<'_> { .numa_nodes .iter() .map(|node| NumaNode { - pxb_bus: Some(node.pxb_bus), + pxb_bus: node.pxb_bus, }) .collect(), num_gpus: self.num_gpus, diff --git a/dstack/dstack-types/src/lib.rs b/dstack/dstack-types/src/lib.rs index a513d6401f..0e52e878ea 100644 --- a/dstack/dstack-types/src/lib.rs +++ b/dstack/dstack-types/src/lib.rs @@ -1427,8 +1427,10 @@ fn is_false(value: &bool) -> bool { /// node order. #[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)] pub struct NumaNodeConfig { - /// Bus number of the node's `pxb-pcie` expander (its `bus_nr`). - pub pxb_bus: u8, + /// Bus number of the node's `pxb-pcie` expander (its `bus_nr`). Either + /// every node has one or none does, leaving all devices on the root bus. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pxb_bus: Option, } /// A device a host QEMU wrapper appends to the root PCIe bus. @@ -2656,6 +2658,26 @@ mod vm_config_device_count_tests { ); } + #[test] + fn numa_nodes_keep_their_legacy_serialization() { + let mut json = legacy_json(); + json["numa_nodes"] = serde_json::json!([{ "pxb_bus": 5 }, { "pxb_bus": 10 }]); + let cfg: VmConfig = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(cfg.numa_nodes[1].pxb_bus, Some(10)); + assert_eq!( + serde_json::to_value(&cfg).unwrap()["numa_nodes"], + json["numa_nodes"] + ); + + json["numa_nodes"] = serde_json::json!([{}, {}]); + let cfg: VmConfig = serde_json::from_value(json.clone()).unwrap(); + assert_eq!(cfg.numa_nodes[0].pxb_bus, None); + assert_eq!( + serde_json::to_value(&cfg).unwrap()["numa_nodes"], + json["numa_nodes"] + ); + } + #[test] fn swtpm_is_serialized_only_when_enabled() { let mut cfg: VmConfig = serde_json::from_value(legacy_json()).unwrap(); diff --git a/dstack/vmm/src/app.rs b/dstack/vmm/src/app.rs index 5baf6aeae8..b43710e7be 100644 --- a/dstack/vmm/src/app.rs +++ b/dstack/vmm/src/app.rs @@ -2213,7 +2213,7 @@ fn make_vm_config( } else { pxb_buses .into_iter() - .map(|pxb_bus| dstack_types::NumaNodeConfig { pxb_bus }) + .map(|bus| dstack_types::NumaNodeConfig { pxb_bus: Some(bus) }) .collect() }; // Each resolved network interface becomes one virtio-net-pci device in the From 14675035b2db955a21a1ab541ead6c045f089391 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Mon, 19 Oct 2026 16:36:14 -0700 Subject: [PATCH 016/572] fix(volume): keep verity volumes out of the data disk search dstack-prepare finds the app data disk by its partition label, dstack-data. A verity volume built by `dstack verity` used the same label for its data partition, so on a fresh CVM, whose data disk has no partition yet, the guest picked the volume and ran luksFormat on it. That failed only because the VMM attaches volumes read-only, and the CVM did not boot. Label the volume's data partition dstack-volume-data; the guest opens volume partitions by number, so nothing else reads the label. Old volumes keep the old label, so dstack-prepare also skips any disk with a dstack-volume partition, and refuses more than one dstack-data partition instead of taking the first. Signed-off-by: Kevin Wang --- CHANGELOG.md | 3 ++ docs/verity-volumes.md | 11 +++++-- dstack/crates/dstack-volume/src/volume.rs | 4 +-- os/common/rootfs/dstack-prepare.sh | 35 +++++++++++++++++++++-- 4 files changed, 46 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d80200b61..5bbc05aef5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- guest: a fresh CVM with a verity volume could take the volume for its data disk and try to LUKS-format it: volumes labelled their data partition `dstack-data`, the data disk's label. `dstack verity` now labels it `dstack-volume-data`, and the guest skips disks that carry a `dstack-volume` partition, so volumes built by older releases are safe too + ### Changed - vmm: `qmp_socket` now defaults to `true`. Each CVM's QEMU exposes `qmp.sock` in its work dir, so the host can change disk options or compact a bloated `hda.img` (`blockdev-mirror`) without stopping the CVM. Applies to CVMs started after the change; set `qmp_socket = false` to opt out diff --git a/docs/verity-volumes.md b/docs/verity-volumes.md index 6c7dac2950..431f014001 100644 --- a/docs/verity-volumes.md +++ b/docs/verity-volumes.md @@ -9,11 +9,16 @@ hash measured in `app-compose.json`. A built volume is a raw GPT image: ```text -p1: DSTACK_VOLUME metadata envelope -p2: filesystem data -p3: dm-verity superblock and hash tree +p1 dstack-volume: DSTACK_VOLUME metadata envelope +p2 dstack-volume-data: filesystem data +p3 dstack-verity: dm-verity superblock and hash tree ``` +The guest opens the partitions by number; the labels only keep a volume apart +from the app data disk, whose partition is `dstack-data`. Older volumes label +p2 `dstack-data` too; the guest skips any disk with a `dstack-volume` +partition when it looks for the data disk. + The envelope identifies a candidate disk. It is not trusted. The guest passes the root from the measured app compose to `veritysetup`, so a forged envelope or partition table cannot substitute different contents. diff --git a/dstack/crates/dstack-volume/src/volume.rs b/dstack/crates/dstack-volume/src/volume.rs index 604e86ac13..ba9ee6ac18 100644 --- a/dstack/crates/dstack-volume/src/volume.rs +++ b/dstack/crates/dstack-volume/src/volume.rs @@ -332,7 +332,7 @@ fn write_gpt(mut out: fs::File, layout: &GptLayout, root_hash: &str) -> Result Date: Wed, 21 Oct 2026 13:34:51 +0800 Subject: [PATCH 017/572] fix(kms): raise Bun auth idleTimeout above the KMS webhook timeout Bun.serve defaults idleTimeout to 10s and closes the socket while the handler is still awaiting eth_call. That surfaces on GetMeta as "connection closed before message completed". Set idleTimeout to Bun's 255s maximum so the KMS client's 60s webhook timeout fires first. Signed-off-by: Leechael Yim --- dstack/kms/auth-eth-bun/README.md | 2 ++ dstack/kms/auth-eth-bun/index.test.ts | 10 ++++++++++ dstack/kms/auth-eth-bun/index.ts | 4 ++++ dstack/kms/auth-mock/index.ts | 3 +++ dstack/kms/auth-simple/index.ts | 3 +++ 5 files changed, 22 insertions(+) diff --git a/dstack/kms/auth-eth-bun/README.md b/dstack/kms/auth-eth-bun/README.md index 9fc755b6c7..a3f48a47b2 100644 --- a/dstack/kms/auth-eth-bun/README.md +++ b/dstack/kms/auth-eth-bun/README.md @@ -66,6 +66,8 @@ bun run check - `ETH_CHAIN_ID` - reject every decision if the RPC reports a different chain ID (default: unset, no check) - `ETH_FINALITY_CONFIRMATIONS` - read policy this many blocks behind the RPC head (default: 0, the head) +The Bun server sets `idleTimeout` to 255s (Bun's maximum). Bun's default of 10s closes the socket while a slow `eth_call` is still in flight, which surfaces on the KMS side as `connection closed before message completed`. + ## API endpoints ### GET / diff --git a/dstack/kms/auth-eth-bun/index.test.ts b/dstack/kms/auth-eth-bun/index.test.ts index fd97ffdb63..1dbf60b185 100644 --- a/dstack/kms/auth-eth-bun/index.test.ts +++ b/dstack/kms/auth-eth-bun/index.test.ts @@ -43,6 +43,16 @@ beforeEach(() => { mockGetBlockNumber.mockResolvedValue(100n); }); +describe('server runtime config', () => { + it('keeps Bun idleTimeout above the KMS webhook timeout', async () => { + // Vitest calls `fetch` directly and never hits Bun.serve, so this pins the + // config that production actually loads. Bun's default of 10s closes the + // socket while GET / is still awaiting eth_call. + const indexModule = await import('./index.ts'); + expect(indexModule.default.idleTimeout).toBeGreaterThanOrEqual(60); + }); +}); + describe('API Compatibility Tests', () => { describe('GET /', () => { it('should return system info matching OpenAPI spec', async () => { diff --git a/dstack/kms/auth-eth-bun/index.ts b/dstack/kms/auth-eth-bun/index.ts index 3ea279327c..4df31df56b 100644 --- a/dstack/kms/auth-eth-bun/index.ts +++ b/dstack/kms/auth-eth-bun/index.ts @@ -333,7 +333,11 @@ app.post('/bootAuth/kms', const port = parseInt(process.env.PORT || '3000'); console.log(`starting server on port ${port}`); +// Bun defaults idleTimeout to 10s and closes the socket while the handler is +// still awaiting eth_call. KMS's webhook timeout is 60s; stay above that so the +// client times out first. Bun's documented maximum is 255. export default { port, + idleTimeout: 255, fetch: app.fetch, }; diff --git a/dstack/kms/auth-mock/index.ts b/dstack/kms/auth-mock/index.ts index 83037c93c0..577cae583a 100644 --- a/dstack/kms/auth-mock/index.ts +++ b/dstack/kms/auth-mock/index.ts @@ -216,7 +216,10 @@ const port = parseInt(process.env.PORT || '3000'); const policy = getPolicy(); console.log(`starting mock auth server on port ${port} (policy: ${policy})`); +// Bun defaults idleTimeout to 10s and closes the socket while a handler is +// still awaiting work. Stay above the KMS webhook timeout (60s). Bun max: 255. export default { port, + idleTimeout: 255, fetch: app.fetch, }; diff --git a/dstack/kms/auth-simple/index.ts b/dstack/kms/auth-simple/index.ts index 7f9a7f036c..9da1490147 100644 --- a/dstack/kms/auth-simple/index.ts +++ b/dstack/kms/auth-simple/index.ts @@ -316,7 +316,10 @@ const defaultConfigPath = process.env.AUTH_CONFIG_PATH || './auth-config.json'; console.log(`starting auth-simple server on port ${port}`); console.log(`config path: ${defaultConfigPath}`); +// Bun defaults idleTimeout to 10s and closes the socket while a handler is +// still awaiting work. Stay above the KMS webhook timeout (60s). Bun max: 255. export default { port, + idleTimeout: 255, fetch: app.fetch, }; From 6c2c1cd513fdb8ee159900438aa727e1923a0894 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 6 Oct 2026 23:23:33 +0800 Subject: [PATCH 018/572] fix(kms): keep onboard ui finishable after repeat click Signed-off-by: Leechael Yim --- dstack/kms/src/www/onboard.html | 45 +++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/dstack/kms/src/www/onboard.html b/dstack/kms/src/www/onboard.html index a61d411fee..a98a558bd8 100644 --- a/dstack/kms/src/www/onboard.html +++ b/dstack/kms/src/www/onboard.html @@ -85,6 +85,23 @@ background-color: #0056b3; } + button:disabled { + background-color: #6c757d; + cursor: wait; + opacity: 0.7; + } + + button:disabled:hover { + background-color: #6c757d; + } + + fieldset { + border: none; + margin: 0; + padding: 0; + min-width: 0; + } + .error { color: #dc3545; margin-top: 10px; @@ -210,7 +227,7 @@

Chain Info

-
+
@@ -221,20 +238,24 @@

Chain Info

Bootstrap A New KMS Instance

+
- + +

Onboard from an Existing KMS Instance

+
Onboard from an Existing KMS Instance
- + +
@@ -267,7 +290,7 @@

Onboard from an Existing KMS Instance

- +
@@ -297,6 +320,7 @@

Onboard from an Existing KMS Instance

success: '', result: '', setupFinished: false, + busy: false, attestationInfo: null, attestationLoading: true, attestationError: '', @@ -323,6 +347,8 @@

Onboard from an Existing KMS Instance

}, methods: { async handleBootstrap() { + if (this.busy) return; + this.busy = true; try { const { ca_pubkey, k256_pubkey, attestation, error } = await rpcCall('Bootstrap', { domain: this.bootstrapDomain @@ -340,9 +366,13 @@

Onboard from an Existing KMS Instance

} catch (err) { this.error = err.message; this.success = ''; + } finally { + this.busy = false; } }, async handleOnboard() { + if (this.busy) return; + this.busy = true; try { const data = await rpcCall('Onboard', { source_url: this.sourceUrl + "/prpc", @@ -360,9 +390,13 @@

Onboard from an Existing KMS Instance

} catch (err) { this.error = err.message; this.success = ''; + } finally { + this.busy = false; } }, async handleFinish() { + if (this.busy) return; + this.busy = true; try { const response = await fetch("/finish"); if (!response.ok) throw new Error(response.statusText); @@ -372,7 +406,8 @@

Onboard from an Existing KMS Instance

this.setupFinished = true; } catch (err) { this.error = err.message; - this.success = ''; + } finally { + this.busy = false; } } } From 2a01a24a56df3e02081c3e4c141ff93f5fcf52bf Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 6 Oct 2026 23:52:17 +0800 Subject: [PATCH 019/572] feat(kms): add Onboard.GetSetupStatus Signed-off-by: Leechael Yim --- dstack/kms/rpc/proto/kms_rpc.proto | 11 ++++ dstack/kms/src/onboard_service.rs | 90 +++++++++++++++++++++++++++++- 2 files changed, 100 insertions(+), 1 deletion(-) diff --git a/dstack/kms/rpc/proto/kms_rpc.proto b/dstack/kms/rpc/proto/kms_rpc.proto index 36da0254fa..9474e277d7 100644 --- a/dstack/kms/rpc/proto/kms_rpc.proto +++ b/dstack/kms/rpc/proto/kms_rpc.proto @@ -185,6 +185,15 @@ message AttestationInfoResponse { bytes ppid = 8; } +// Public material already written by Bootstrap or Onboard, so the setup page +// can resume after a refresh without repeating those RPCs. +message SetupStatusResponse { + bool provisioned = 1; + bytes k256_pubkey = 2; + bytes ca_pubkey = 3; + bytes attestation = 4; +} + // The Onboard RPC service. service Onboard { // Bootstrap a new KMS @@ -193,6 +202,8 @@ service Onboard { rpc Onboard(OnboardRequest) returns (OnboardResponse); // Get attestation info for on-chain KMS authorization rpc GetAttestationInfo(google.protobuf.Empty) returns (AttestationInfoResponse); + // Public keys already stored for this KMS, if any + rpc GetSetupStatus(google.protobuf.Empty) returns (SetupStatusResponse); // Finish onboarding rpc Finish(google.protobuf.Empty) returns (google.protobuf.Empty); } diff --git a/dstack/kms/src/onboard_service.rs b/dstack/kms/src/onboard_service.rs index 0476e60de4..71733b7fdb 100644 --- a/dstack/kms/src/onboard_service.rs +++ b/dstack/kms/src/onboard_service.rs @@ -13,7 +13,7 @@ use dstack_kms_rpc::{ kms_client::KmsClient, onboard_server::{OnboardRpc, OnboardServer}, AttestationInfoResponse, BootstrapRequest, BootstrapResponse, GetKmsKeyRequest, KmsKeyResponse, - OnboardRequest, OnboardResponse, + OnboardRequest, OnboardResponse, SetupStatusResponse, }; use fs_err as fs; use k256::ecdsa::SigningKey; @@ -107,6 +107,42 @@ fn validate_onboarding_domain(domain: &str) -> Result<()> { Ok(()) } +fn stored_k256_pubkey(cfg: &KmsConfig) -> Result> { + let bytes = fs::read(cfg.k256_key()).context("failed to read k256 key")?; + let key = SigningKey::from_slice(&bytes).context("failed to parse k256 key")?; + Ok(key.verifying_key().to_sec1_bytes().to_vec()) +} + +fn setup_status(cfg: &KmsConfig) -> Result { + if !cfg.root_keys_exist() { + return Ok(SetupStatusResponse { + provisioned: false, + k256_pubkey: Vec::new(), + ca_pubkey: Vec::new(), + attestation: Vec::new(), + }); + } + let k256_pubkey = stored_k256_pubkey(cfg)?; + if !cfg.bootstrap_info().exists() { + return Ok(SetupStatusResponse { + provisioned: true, + k256_pubkey, + ca_pubkey: Vec::new(), + attestation: Vec::new(), + }); + } + let info: BootstrapResponse = serde_json::from_slice( + &fs::read(cfg.bootstrap_info()).context("failed to read bootstrap info")?, + ) + .context("failed to parse bootstrap info")?; + Ok(SetupStatusResponse { + provisioned: true, + k256_pubkey, + ca_pubkey: info.ca_pubkey, + attestation: info.attestation, + }) +} + impl OnboardRpc for OnboardHandler { async fn bootstrap(self, request: BootstrapRequest) -> Result { validate_onboarding_domain(&request.domain)?; @@ -216,6 +252,11 @@ impl OnboardRpc for OnboardHandler { ) } + async fn get_setup_status(self) -> Result { + let _bootstrap_guard = self.state.bootstrap_lock.lock().await; + setup_status(&self.state.config) + } + async fn finish(self) -> anyhow::Result<()> { let shutdown = self .state @@ -494,6 +535,53 @@ mod tests { assert_ne!(fs::read(cfg.root_ca_key()).unwrap(), b"stale"); } + #[test] + fn setup_status_is_empty_before_root_keys_exist() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let status = setup_status(&cfg).unwrap(); + assert!(!status.provisioned); + assert!(status.k256_pubkey.is_empty()); + assert!(status.ca_pubkey.is_empty()); + assert!(status.attestation.is_empty()); + } + + #[rocket::async_test] + async fn setup_status_returns_k256_pubkey_after_keys_are_stored() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let keys = Keys::generate("kms.example.com", false).await.unwrap(); + let expected = keys.k256_key.verifying_key().to_sec1_bytes().to_vec(); + keys.store(&cfg).unwrap(); + let status = setup_status(&cfg).unwrap(); + assert!(status.provisioned); + assert_eq!(status.k256_pubkey, expected); + assert!(status.ca_pubkey.is_empty()); + assert!(status.attestation.is_empty()); + } + + #[rocket::async_test] + async fn setup_status_includes_bootstrap_info_when_present() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let keys = Keys::generate("kms.example.com", false).await.unwrap(); + keys.store(&cfg).unwrap(); + let stored = BootstrapResponse { + ca_pubkey: vec![1, 2, 3], + k256_pubkey: vec![4, 5, 6], + attestation: vec![7, 8, 9], + }; + fs::write(cfg.bootstrap_info(), serde_json::to_vec(&stored).unwrap()).unwrap(); + let status = setup_status(&cfg).unwrap(); + assert!(status.provisioned); + assert_eq!(status.ca_pubkey, stored.ca_pubkey); + assert_eq!(status.attestation, stored.attestation); + assert_eq!( + status.k256_pubkey, + keys.k256_key.verifying_key().to_sec1_bytes().to_vec() + ); + } + #[test] fn ca_certificate_is_renewed_only_within_the_renewal_window() { let now = UNIX_EPOCH + Duration::from_secs(2_000_000_000); From 9b3a4a864c01c10fd2167088c8bc2e0e776b37f6 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 6 Oct 2026 23:52:17 +0800 Subject: [PATCH 020/572] fix(kms): resume onboard ui from stored setup status Signed-off-by: Leechael Yim --- dstack/kms/src/www/onboard.html | 38 +++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/dstack/kms/src/www/onboard.html b/dstack/kms/src/www/onboard.html index a98a558bd8..640bb381d6 100644 --- a/dstack/kms/src/www/onboard.html +++ b/dstack/kms/src/www/onboard.html @@ -329,16 +329,22 @@

Onboard from an Existing KMS Instance

}, async mounted() { try { - const data = await rpcCall('GetAttestationInfo', {}); - if (data.error) { - this.attestationError = data.error; + const [attestation, setup] = await Promise.all([ + rpcCall('GetAttestationInfo', {}), + rpcCall('GetSetupStatus', {}), + ]); + if (attestation.error) { + this.attestationError = attestation.error; } else { - this.attestationInfo = data; - if (data.site_name) { - this.siteName = data.site_name; - document.title = data.site_name; + this.attestationInfo = attestation; + if (attestation.site_name) { + this.siteName = attestation.site_name; + document.title = attestation.site_name; } } + if (setup && !setup.error && setup.provisioned) { + this.applySetupStatus(setup); + } } catch (err) { this.attestationError = err.message; } finally { @@ -346,6 +352,24 @@

Onboard from an Existing KMS Instance

} }, methods: { + applySetupStatus(data) { + if (data.attestation) { + this.success = 'Bootstrap successful!'; + this.result = JSON.stringify({ + caPubkey: '0x' + (data.ca_pubkey || ''), + k256Pubkey: '0x' + (data.k256_pubkey || ''), + attestation: '0x' + data.attestation + }, null, 2); + } else { + this.success = 'Onboarding successful!'; + this.result = data.k256_pubkey + ? JSON.stringify({ + k256Pubkey: '0x' + data.k256_pubkey, + }, null, 2) + : ''; + } + this.error = ''; + }, async handleBootstrap() { if (this.busy) return; this.busy = true; From 992c4c194d8a33f9b9f878d7bdaf66ef147de07b Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 6 Oct 2026 23:59:22 +0800 Subject: [PATCH 021/572] fix(kms): harden onboard setup status recovery Signed-off-by: Leechael Yim --- dstack/kms/rpc/proto/kms_rpc.proto | 2 + dstack/kms/src/onboard_service.rs | 59 +++++++++++++++++++++++++++--- dstack/kms/src/www/onboard.html | 59 +++++++++++++++--------------- 3 files changed, 86 insertions(+), 34 deletions(-) diff --git a/dstack/kms/rpc/proto/kms_rpc.proto b/dstack/kms/rpc/proto/kms_rpc.proto index 9474e277d7..e3a8502269 100644 --- a/dstack/kms/rpc/proto/kms_rpc.proto +++ b/dstack/kms/rpc/proto/kms_rpc.proto @@ -192,6 +192,8 @@ message SetupStatusResponse { bytes k256_pubkey = 2; bytes ca_pubkey = 3; bytes attestation = 4; + // All key and certificate files are present, so Finish can start the KMS. + bool ready = 5; } // The Onboard RPC service. diff --git a/dstack/kms/src/onboard_service.rs b/dstack/kms/src/onboard_service.rs index 71733b7fdb..1f308a7a0c 100644 --- a/dstack/kms/src/onboard_service.rs +++ b/dstack/kms/src/onboard_service.rs @@ -117,15 +117,18 @@ fn setup_status(cfg: &KmsConfig) -> Result { if !cfg.root_keys_exist() { return Ok(SetupStatusResponse { provisioned: false, + ready: false, k256_pubkey: Vec::new(), ca_pubkey: Vec::new(), attestation: Vec::new(), }); } let k256_pubkey = stored_k256_pubkey(cfg)?; + let ready = cfg.keys_exists(); if !cfg.bootstrap_info().exists() { return Ok(SetupStatusResponse { provisioned: true, + ready, k256_pubkey, ca_pubkey: Vec::new(), attestation: Vec::new(), @@ -135,8 +138,19 @@ fn setup_status(cfg: &KmsConfig) -> Result { &fs::read(cfg.bootstrap_info()).context("failed to read bootstrap info")?, ) .context("failed to parse bootstrap info")?; + if info.k256_pubkey != k256_pubkey { + tracing::warn!("ignoring bootstrap info whose k256 pubkey does not match the stored key"); + return Ok(SetupStatusResponse { + provisioned: true, + ready, + k256_pubkey, + ca_pubkey: Vec::new(), + attestation: Vec::new(), + }); + } Ok(SetupStatusResponse { provisioned: true, + ready, k256_pubkey, ca_pubkey: info.ca_pubkey, attestation: info.attestation, @@ -541,6 +555,7 @@ mod tests { let cfg = auto_bootstrap_config(cert_dir.path()); let status = setup_status(&cfg).unwrap(); assert!(!status.provisioned); + assert!(!status.ready); assert!(status.k256_pubkey.is_empty()); assert!(status.ca_pubkey.is_empty()); assert!(status.attestation.is_empty()); @@ -555,6 +570,7 @@ mod tests { keys.store(&cfg).unwrap(); let status = setup_status(&cfg).unwrap(); assert!(status.provisioned); + assert!(status.ready); assert_eq!(status.k256_pubkey, expected); assert!(status.ca_pubkey.is_empty()); assert!(status.attestation.is_empty()); @@ -566,20 +582,53 @@ mod tests { let cfg = auto_bootstrap_config(cert_dir.path()); let keys = Keys::generate("kms.example.com", false).await.unwrap(); keys.store(&cfg).unwrap(); + let expected_k256 = keys.k256_key.verifying_key().to_sec1_bytes().to_vec(); let stored = BootstrapResponse { ca_pubkey: vec![1, 2, 3], - k256_pubkey: vec![4, 5, 6], + k256_pubkey: expected_k256.clone(), attestation: vec![7, 8, 9], }; fs::write(cfg.bootstrap_info(), serde_json::to_vec(&stored).unwrap()).unwrap(); let status = setup_status(&cfg).unwrap(); assert!(status.provisioned); + assert!(status.ready); assert_eq!(status.ca_pubkey, stored.ca_pubkey); assert_eq!(status.attestation, stored.attestation); - assert_eq!( - status.k256_pubkey, - keys.k256_key.verifying_key().to_sec1_bytes().to_vec() - ); + assert_eq!(status.k256_pubkey, expected_k256); + } + + #[rocket::async_test] + async fn setup_status_drops_bootstrap_info_when_k256_mismatches() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let keys = Keys::generate("kms.example.com", false).await.unwrap(); + let expected_k256 = keys.k256_key.verifying_key().to_sec1_bytes().to_vec(); + keys.store(&cfg).unwrap(); + let stored = BootstrapResponse { + ca_pubkey: vec![1, 2, 3], + k256_pubkey: vec![4, 5, 6], + attestation: vec![7, 8, 9], + }; + fs::write(cfg.bootstrap_info(), serde_json::to_vec(&stored).unwrap()).unwrap(); + let status = setup_status(&cfg).unwrap(); + assert!(status.provisioned); + assert!(status.ready); + assert_eq!(status.k256_pubkey, expected_k256); + assert!(status.ca_pubkey.is_empty()); + assert!(status.attestation.is_empty()); + } + + #[rocket::async_test] + async fn setup_status_is_not_ready_when_certificates_are_missing() { + let cert_dir = tempfile::tempdir().unwrap(); + let cfg = auto_bootstrap_config(cert_dir.path()); + let keys = Keys::generate("kms.example.com", false).await.unwrap(); + keys.store(&cfg).unwrap(); + fs::remove_file(cfg.rpc_cert()).unwrap(); + let status = setup_status(&cfg).unwrap(); + assert!(status.provisioned); + assert!(!status.ready); + assert!(!status.k256_pubkey.is_empty()); } #[test] diff --git a/dstack/kms/src/www/onboard.html b/dstack/kms/src/www/onboard.html index 640bb381d6..03e609df70 100644 --- a/dstack/kms/src/www/onboard.html +++ b/dstack/kms/src/www/onboard.html @@ -227,10 +227,10 @@

Chain Info

-
+
- - + +
@@ -238,7 +238,7 @@

Chain Info

Bootstrap A New KMS Instance

-
+
Bootstrap A New KMS Instance

Onboard from an Existing KMS Instance

-
+
Onboard from an Existing KMS Instance result: '', setupFinished: false, busy: false, + statusLoading: true, + broken: false, attestationInfo: null, attestationLoading: true, attestationError: '', @@ -328,28 +330,29 @@

Onboard from an Existing KMS Instance

} }, async mounted() { - try { - const [attestation, setup] = await Promise.all([ - rpcCall('GetAttestationInfo', {}), - rpcCall('GetSetupStatus', {}), - ]); - if (attestation.error) { - this.attestationError = attestation.error; - } else { - this.attestationInfo = attestation; - if (attestation.site_name) { - this.siteName = attestation.site_name; - document.title = attestation.site_name; - } - } - if (setup && !setup.error && setup.provisioned) { - this.applySetupStatus(setup); + const [attestation, setup] = await Promise.all([ + rpcCall('GetAttestationInfo', {}).catch(err => ({ error: err.message })), + rpcCall('GetSetupStatus', {}).catch(err => ({ error: err.message })), + ]); + if (attestation.error) { + this.attestationError = attestation.error; + } else { + this.attestationInfo = attestation; + if (attestation.site_name) { + this.siteName = attestation.site_name; + document.title = attestation.site_name; } - } catch (err) { - this.attestationError = err.message; - } finally { - this.attestationLoading = false; } + if (setup.error) { + this.error = setup.error; + } else if (setup.provisioned && setup.ready) { + this.applySetupStatus(setup); + } else if (setup.provisioned) { + this.broken = true; + this.error = 'KMS setup is incomplete; root keys exist but required certificates are missing'; + } + this.attestationLoading = false; + this.statusLoading = false; }, methods: { applySetupStatus(data) { @@ -371,7 +374,7 @@

Onboard from an Existing KMS Instance

this.error = ''; }, async handleBootstrap() { - if (this.busy) return; + if (this.busy || this.statusLoading || this.success || this.broken) return; this.busy = true; try { const { ca_pubkey, k256_pubkey, attestation, error } = await rpcCall('Bootstrap', { @@ -389,13 +392,12 @@

Onboard from an Existing KMS Instance

this.error = ''; } catch (err) { this.error = err.message; - this.success = ''; } finally { this.busy = false; } }, async handleOnboard() { - if (this.busy) return; + if (this.busy || this.statusLoading || this.success || this.broken) return; this.busy = true; try { const data = await rpcCall('Onboard', { @@ -413,7 +415,6 @@

Onboard from an Existing KMS Instance

this.error = ''; } catch (err) { this.error = err.message; - this.success = ''; } finally { this.busy = false; } From dcaa7241a8741765d1842d0c5681f5b1bf664ec0 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Sun, 11 Oct 2026 21:07:37 +0800 Subject: [PATCH 022/572] fix(kms): tolerate invalid bootstrap display metadata Signed-off-by: Leechael Yim --- dstack/kms/rpc/proto/kms_rpc.proto | 1 + dstack/kms/src/onboard_service.rs | 99 ++++++++++-------------------- 2 files changed, 33 insertions(+), 67 deletions(-) diff --git a/dstack/kms/rpc/proto/kms_rpc.proto b/dstack/kms/rpc/proto/kms_rpc.proto index e3a8502269..9a17ddde49 100644 --- a/dstack/kms/rpc/proto/kms_rpc.proto +++ b/dstack/kms/rpc/proto/kms_rpc.proto @@ -193,6 +193,7 @@ message SetupStatusResponse { bytes ca_pubkey = 3; bytes attestation = 4; // All key and certificate files are present, so Finish can start the KMS. + // If ready is true, provisioned is also true. bool ready = 5; } diff --git a/dstack/kms/src/onboard_service.rs b/dstack/kms/src/onboard_service.rs index 1f308a7a0c..c16b67d4da 100644 --- a/dstack/kms/src/onboard_service.rs +++ b/dstack/kms/src/onboard_service.rs @@ -115,42 +115,17 @@ fn stored_k256_pubkey(cfg: &KmsConfig) -> Result> { fn setup_status(cfg: &KmsConfig) -> Result { if !cfg.root_keys_exist() { - return Ok(SetupStatusResponse { - provisioned: false, - ready: false, - k256_pubkey: Vec::new(), - ca_pubkey: Vec::new(), - attestation: Vec::new(), - }); + return Ok(SetupStatusResponse::default()); } let k256_pubkey = stored_k256_pubkey(cfg)?; - let ready = cfg.keys_exists(); - if !cfg.bootstrap_info().exists() { - return Ok(SetupStatusResponse { - provisioned: true, - ready, - k256_pubkey, - ca_pubkey: Vec::new(), - attestation: Vec::new(), - }); - } - let info: BootstrapResponse = serde_json::from_slice( - &fs::read(cfg.bootstrap_info()).context("failed to read bootstrap info")?, - ) - .context("failed to parse bootstrap info")?; - if info.k256_pubkey != k256_pubkey { - tracing::warn!("ignoring bootstrap info whose k256 pubkey does not match the stored key"); - return Ok(SetupStatusResponse { - provisioned: true, - ready, - k256_pubkey, - ca_pubkey: Vec::new(), - attestation: Vec::new(), - }); - } + let info = fs::read(cfg.bootstrap_info()) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()) + .filter(|info| info.k256_pubkey == k256_pubkey) + .unwrap_or_default(); Ok(SetupStatusResponse { provisioned: true, - ready, + ready: cfg.keys_exists(), k256_pubkey, ca_pubkey: info.ca_pubkey, attestation: info.attestation, @@ -561,21 +536,6 @@ mod tests { assert!(status.attestation.is_empty()); } - #[rocket::async_test] - async fn setup_status_returns_k256_pubkey_after_keys_are_stored() { - let cert_dir = tempfile::tempdir().unwrap(); - let cfg = auto_bootstrap_config(cert_dir.path()); - let keys = Keys::generate("kms.example.com", false).await.unwrap(); - let expected = keys.k256_key.verifying_key().to_sec1_bytes().to_vec(); - keys.store(&cfg).unwrap(); - let status = setup_status(&cfg).unwrap(); - assert!(status.provisioned); - assert!(status.ready); - assert_eq!(status.k256_pubkey, expected); - assert!(status.ca_pubkey.is_empty()); - assert!(status.attestation.is_empty()); - } - #[rocket::async_test] async fn setup_status_includes_bootstrap_info_when_present() { let cert_dir = tempfile::tempdir().unwrap(); @@ -598,7 +558,7 @@ mod tests { } #[rocket::async_test] - async fn setup_status_drops_bootstrap_info_when_k256_mismatches() { + async fn setup_status_ignores_absent_or_invalid_bootstrap_info() { let cert_dir = tempfile::tempdir().unwrap(); let cfg = auto_bootstrap_config(cert_dir.path()); let keys = Keys::generate("kms.example.com", false).await.unwrap(); @@ -609,26 +569,31 @@ mod tests { k256_pubkey: vec![4, 5, 6], attestation: vec![7, 8, 9], }; - fs::write(cfg.bootstrap_info(), serde_json::to_vec(&stored).unwrap()).unwrap(); - let status = setup_status(&cfg).unwrap(); - assert!(status.provisioned); - assert!(status.ready); - assert_eq!(status.k256_pubkey, expected_k256); - assert!(status.ca_pubkey.is_empty()); - assert!(status.attestation.is_empty()); - } + for ready in [true, false] { + if !ready { + fs::remove_file(cfg.rpc_cert()).unwrap(); + fs::remove_file(cfg.bootstrap_info()).unwrap(); + } + for info in [ + None, + Some(b"invalid json".to_vec()), + Some(serde_json::to_vec(&stored).unwrap()), + ] { + if let Some(info) = info { + fs::write(cfg.bootstrap_info(), info).unwrap(); + } + let status = setup_status(&cfg).unwrap(); + assert!(status.provisioned); + assert_eq!(status.ready, ready); + assert_eq!(status.k256_pubkey, expected_k256); + assert!(status.ca_pubkey.is_empty()); + assert!(status.attestation.is_empty()); + } + } - #[rocket::async_test] - async fn setup_status_is_not_ready_when_certificates_are_missing() { - let cert_dir = tempfile::tempdir().unwrap(); - let cfg = auto_bootstrap_config(cert_dir.path()); - let keys = Keys::generate("kms.example.com", false).await.unwrap(); - keys.store(&cfg).unwrap(); - fs::remove_file(cfg.rpc_cert()).unwrap(); - let status = setup_status(&cfg).unwrap(); - assert!(status.provisioned); - assert!(!status.ready); - assert!(!status.k256_pubkey.is_empty()); + fs::write(cfg.k256_key(), b"invalid key").unwrap(); + let err = setup_status(&cfg).unwrap_err(); + assert!(format!("{err:#}").contains("failed to parse k256 key")); } #[test] From 5c9e5ee412326b76f789c6bc1d1e940b953875df Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Sun, 11 Oct 2026 21:07:59 +0800 Subject: [PATCH 023/572] refactor(kms): simplify onboard page state and rendering Signed-off-by: Leechael Yim --- dstack/kms/src/www/onboard.html | 119 +++++++++++++------------------- 1 file changed, 49 insertions(+), 70 deletions(-) diff --git a/dstack/kms/src/www/onboard.html b/dstack/kms/src/www/onboard.html index 03e609df70..b59cbd294f 100644 --- a/dstack/kms/src/www/onboard.html +++ b/dstack/kms/src/www/onboard.html @@ -81,7 +81,7 @@ cursor: pointer; } - button:hover { + button:not(:disabled):hover { background-color: #0056b3; } @@ -91,10 +91,6 @@ opacity: 0.7; } - button:disabled:hover { - background-color: #6c757d; - } - fieldset { border: none; margin: 0; @@ -227,10 +223,10 @@

Chain Info

-
+
- - + +
@@ -238,45 +234,43 @@

Chain Info

Bootstrap A New KMS Instance

-
-
- - -
- +
+
+ + +
+ +
-

Onboard from an Existing KMS Instance

-
-
- - -
-
- - -
-
- - -
- +
+
+ + +
+
+ + +
+
+ + +
+ +
-
@@ -320,9 +314,7 @@

Onboard from an Existing KMS Instance

success: '', result: '', setupFinished: false, - busy: false, - statusLoading: true, - broken: false, + busy: true, attestationInfo: null, attestationLoading: true, attestationError: '', @@ -345,51 +337,44 @@

Onboard from an Existing KMS Instance

} if (setup.error) { this.error = setup.error; - } else if (setup.provisioned && setup.ready) { - this.applySetupStatus(setup); } else if (setup.provisioned) { - this.broken = true; - this.error = 'KMS setup is incomplete; root keys exist but required certificates are missing'; + this.applySetupStatus(setup); } this.attestationLoading = false; - this.statusLoading = false; + this.busy = false; }, methods: { applySetupStatus(data) { + if (data.provisioned && !data.ready) { + this.selectedOption = null; + this.error = 'KMS setup is incomplete; root keys exist but required certificates are missing'; + return; + } if (data.attestation) { this.success = 'Bootstrap successful!'; this.result = JSON.stringify({ - caPubkey: '0x' + (data.ca_pubkey || ''), - k256Pubkey: '0x' + (data.k256_pubkey || ''), + caPubkey: '0x' + data.ca_pubkey, + k256Pubkey: '0x' + data.k256_pubkey, attestation: '0x' + data.attestation }, null, 2); } else { this.success = 'Onboarding successful!'; - this.result = data.k256_pubkey - ? JSON.stringify({ - k256Pubkey: '0x' + data.k256_pubkey, - }, null, 2) - : ''; + this.result = JSON.stringify({ + k256Pubkey: '0x' + data.k256_pubkey, + }, null, 2); } this.error = ''; }, async handleBootstrap() { - if (this.busy || this.statusLoading || this.success || this.broken) return; this.busy = true; try { - const { ca_pubkey, k256_pubkey, attestation, error } = await rpcCall('Bootstrap', { + const data = await rpcCall('Bootstrap', { domain: this.bootstrapDomain }); - if (error) throw new Error(error); + if (data.error) throw new Error(data.error); - this.success = 'Bootstrap successful!'; - this.result = JSON.stringify({ - caPubkey: '0x' + ca_pubkey, - k256Pubkey: '0x' + k256_pubkey, - attestation: '0x' + attestation - }, null, 2); - this.error = ''; + this.applySetupStatus(data); } catch (err) { this.error = err.message; } finally { @@ -397,7 +382,6 @@

Onboard from an Existing KMS Instance

} }, async handleOnboard() { - if (this.busy || this.statusLoading || this.success || this.broken) return; this.busy = true; try { const data = await rpcCall('Onboard', { @@ -408,11 +392,7 @@

Onboard from an Existing KMS Instance

if (data.error) throw new Error(data.error); - this.success = 'Onboarding successful!'; - this.result = JSON.stringify({ - k256Pubkey: '0x' + data.k256_pubkey, - }, null, 2); - this.error = ''; + this.applySetupStatus(data); } catch (err) { this.error = err.message; } finally { @@ -420,7 +400,6 @@

Onboard from an Existing KMS Instance

} }, async handleFinish() { - if (this.busy) return; this.busy = true; try { const response = await fetch("/finish"); From 948010be08fec91e8640ff533117269400dd7b2f Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Sun, 11 Oct 2026 21:08:07 +0800 Subject: [PATCH 024/572] fix(kms): recover setup after lost provisioning responses Signed-off-by: Leechael Yim --- dstack/kms/src/www/onboard.html | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/dstack/kms/src/www/onboard.html b/dstack/kms/src/www/onboard.html index b59cbd294f..4794cf7247 100644 --- a/dstack/kms/src/www/onboard.html +++ b/dstack/kms/src/www/onboard.html @@ -322,25 +322,24 @@

Onboard from an Existing KMS Instance

} }, async mounted() { - const [attestation, setup] = await Promise.all([ - rpcCall('GetAttestationInfo', {}).catch(err => ({ error: err.message })), - rpcCall('GetSetupStatus', {}).catch(err => ({ error: err.message })), - ]); - if (attestation.error) { - this.attestationError = attestation.error; - } else { + rpcCall('GetAttestationInfo', {}).then(attestation => { + if (attestation.error) throw new Error(attestation.error); this.attestationInfo = attestation; if (attestation.site_name) { this.siteName = attestation.site_name; document.title = attestation.site_name; } - } + }).catch(err => { + this.attestationError = err.message; + }).finally(() => { + this.attestationLoading = false; + }); + const setup = await rpcCall('GetSetupStatus', {}).catch(err => ({ error: err.message })); if (setup.error) { this.error = setup.error; } else if (setup.provisioned) { this.applySetupStatus(setup); } - this.attestationLoading = false; this.busy = false; }, methods: { @@ -365,6 +364,11 @@

Onboard from an Existing KMS Instance

} this.error = ''; }, + async recoverSetupStatus(err) { + this.error = err.message; + const setup = await rpcCall('GetSetupStatus', {}).catch(() => ({})); + if (setup.provisioned) this.applySetupStatus(setup); + }, async handleBootstrap() { this.busy = true; try { @@ -376,7 +380,7 @@

Onboard from an Existing KMS Instance

this.applySetupStatus(data); } catch (err) { - this.error = err.message; + await this.recoverSetupStatus(err); } finally { this.busy = false; } @@ -394,7 +398,7 @@

Onboard from an Existing KMS Instance

this.applySetupStatus(data); } catch (err) { - this.error = err.message; + await this.recoverSetupStatus(err); } finally { this.busy = false; } From 89320386a5774a6e8b1e4723a51d12acb54d7c0f Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 07:25:45 +0800 Subject: [PATCH 025/572] fix(deps): bump rustls-webpki to 0.103.16 for the emSign CA compromise rustls-webpki 0.103.16 (RUSTSEC-2026-0383, CVE-2026-111943) rejects any chain that contains one of the compromised eMudhra/emSign intermediate CA keys, whatever the trust store holds. Before this change the workspace locked 0.103.13, and reqwest built like the workspace (rustls-platform-verifier, system trust store) accepted a certificate issued by one of those intermediates. Raise the workspace minimum to 0.103.16 and update Cargo.lock. Also move webpki-root-certs from 1.0.8 to 1.0.10; on Linux it is only pulled in for other targets, so this is for consistency. cargo also moves aws-lc-rs 1.17.0 -> 1.18.2 and aws-lc-sys 0.41.0 -> 0.46.0 (adds pkg-config), which rustls-webpki 0.103.16 requires. Rebuilt binaries change the gateway, KMS and verifier image digests and the guest OS image, so compose hashes and OS image hashes must be registered again in the on-chain and auth-config allowlists. Signed-off-by: Leechael Yim --- dstack/Cargo.lock | 23 +++++++++++++++-------- dstack/Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 31a97f3894..9d27c2c6b0 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -337,9 +337,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.17.0" +version = "1.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -348,14 +348,15 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.41.0" +version = "0.46.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" dependencies = [ "cc", "cmake", "dunce", "fs_extra", + "pkg-config", ] [[package]] @@ -5416,6 +5417,12 @@ dependencies = [ "spki", ] +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "pki-fetch" version = "0.6.1" @@ -6578,9 +6585,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "aws-lc-rs", "ring", @@ -8673,9 +8680,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.8" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" +checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" dependencies = [ "rustls-pki-types", ] diff --git a/dstack/Cargo.toml b/dstack/Cargo.toml index 8877f62967..031855f4e9 100644 --- a/dstack/Cargo.toml +++ b/dstack/Cargo.toml @@ -247,7 +247,7 @@ rsa = "0.9" ring = "0.17.14" rustls = "0.23.23" rustls-pki-types = "1.13.1" -rustls-webpki = "0.103.10" +rustls-webpki = "0.103.16" schnorrkel = "0.11.4" sha2 = { version = "0.10.8", default-features = false } sha3 = "0.10.8" From 83acd5ddb0f8e3249cf7b478cf9d0c706972e33b Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 08:08:48 +0800 Subject: [PATCH 026/572] fix(images): move gateway, KMS and verifier images to the fixed ca-certificates The gateway, KMS and verifier runtime images pinned ca-certificates=20230311+deb12u1 from the 20260317T000000Z snapshot. That trust store still holds emSign ECC Root CA - G3 and Comodo AAA Services root, and curl in an image built from those pins accepts a certificate issued by one of the compromised eMudhra/emSign intermediates. Advance the default Debian snapshot in pin-packages.sh to 20261021T000000Z, the first midnight snapshot whose debian-security archive carries ca-certificates 20250419~deb12u2 (bookworm) and 20250419+deb13u1 (trixie), and pin ca-certificates=20250419~deb12u2 in the three runtime lists and in the verifier builder list. The other pins are regenerated the way build-image.sh records them (dpkg -l of each stage after its apt step). Only packages whose pinned version is gone from the new snapshot move, all to Debian security updates: openssl/libssl3, curl/libcurl, krb5, nghttp2, jq, libcap2, protobuf, musl. A second pass with the regenerated lists produces the same lists. The gateway and KMS builder stages keep ca-certificates=20250419: they do not install ca-certificates, so the pin cannot move the copy that ships in the rust base image. The new images have new digests, so the compose hashes of the CVMs that run them must be registered again in the on-chain and auth-config allowlists. Signed-off-by: Leechael Yim --- dstack/build/shared/pin-packages.sh | 2 +- .../shared/builder-pinned-packages.txt | 24 ++++++++--------- .../builder/shared/pinned-packages.txt | 26 +++++++++---------- .../shared/builder-pinned-packages.txt | 24 ++++++++--------- .../builder/shared/pinned-packages.txt | 6 ++--- .../shared/builder-pinned-packages.txt | 18 ++++++------- .../builder/shared/pinned-packages.txt | 20 +++++++------- 7 files changed, 60 insertions(+), 60 deletions(-) diff --git a/dstack/build/shared/pin-packages.sh b/dstack/build/shared/pin-packages.sh index dbc036ad04..840c7b1af8 100755 --- a/dstack/build/shared/pin-packages.sh +++ b/dstack/build/shared/pin-packages.sh @@ -15,7 +15,7 @@ set -e PKG_LIST=$1 -SNAPSHOT_DATE=${SNAPSHOT_DATE:-20260317T000000Z} +SNAPSHOT_DATE=${SNAPSHOT_DATE:-20261021T000000Z} if [ -z "$PKG_LIST" ]; then echo "Usage: $0 " >&2 diff --git a/dstack/gateway/dstack-app/builder/shared/builder-pinned-packages.txt b/dstack/gateway/dstack-app/builder/shared/builder-pinned-packages.txt index e390e80bcc..568d740a48 100644 --- a/dstack/gateway/dstack-app/builder/shared/builder-pinned-packages.txt +++ b/dstack/gateway/dstack-app/builder/shared/builder-pinned-packages.txt @@ -309,10 +309,10 @@ libpng16-16t64:amd64=1.6.48-1 libpq-dev=17.6-0+deb13u1 libpq5:amd64=17.6-0+deb13u1 libproc2-0:amd64=2:4.0.4-9 -libprotobuf-dev:amd64=3.21.12-11 -libprotobuf-lite32t64:amd64=3.21.12-11 -libprotobuf32t64:amd64=3.21.12-11 -libprotoc32t64:amd64=3.21.12-11 +libprotobuf-dev:amd64=3.21.12-11+deb13u1 +libprotobuf-lite32t64:amd64=3.21.12-11+deb13u1 +libprotobuf32t64:amd64=3.21.12-11+deb13u1 +libprotoc32t64:amd64=3.21.12-11+deb13u1 libpsl-dev:amd64=0.21.2-1.1+b1 libpsl5t64:amd64=0.21.2-1.1+b1 libpython3-stdlib:amd64=3.13.5-1 @@ -347,8 +347,8 @@ libsqlite3-0:amd64=3.46.1-7 libsqlite3-dev:amd64=3.46.1-7 libssh2-1-dev:amd64=1.11.1-1 libssh2-1t64:amd64=1.11.1-1 -libssl-dev:amd64=3.5.5-1~deb13u1 -libssl3t64:amd64=3.5.5-1~deb13u1 +libssl-dev:amd64=3.5.7-1~deb13u3 +libssl3t64:amd64=3.5.7-1~deb13u3 libstdc++-14-dev:amd64=14.2.0-19 libstdc++6:amd64=14.2.0-19 libsvn1:amd64=1.14.5-3 @@ -424,9 +424,9 @@ media-types=13.0.0 mercurial-common=7.0.1-2 mercurial=7.0.1-2 mount=2.41-5 -musl-dev:amd64=1.2.5-3 -musl-tools=1.2.5-3 -musl:amd64=1.2.5-3 +musl-dev:amd64=1.2.5-3.1~deb13u1 +musl-tools=1.2.5-3.1~deb13u1 +musl:amd64=1.2.5-3.1~deb13u1 mysql-common=5.8+1.1.1 native-architecture=0.2.6 ncurses-base=6.5+20250216-2 @@ -434,8 +434,8 @@ ncurses-bin=6.5+20250216-2 netbase=6.5 nettle-dev:amd64=3.10.1-1 openssh-client=1:10.0p1-7 -openssl-provider-legacy=3.5.5-1~deb13u1 -openssl=3.5.5-1~deb13u1 +openssl-provider-legacy=3.5.7-1~deb13u3 +openssl=3.5.7-1~deb13u3 pango1.0-tools=1.56.3-1 passwd=1:4.17.4-2 patch=2.8-2 @@ -446,7 +446,7 @@ pinentry-curses=1.3.1-2 pkgconf-bin=1.8.1-4 pkgconf:amd64=1.8.1-4 procps=2:4.0.4-9 -protobuf-compiler=3.21.12-11 +protobuf-compiler=3.21.12-11+deb13u1 python3-minimal=3.13.5-1 python3-packaging=25.0-1 python3.13-minimal=3.13.5-2 diff --git a/dstack/gateway/dstack-app/builder/shared/pinned-packages.txt b/dstack/gateway/dstack-app/builder/shared/pinned-packages.txt index f45296ccd8..4efad8116c 100644 --- a/dstack/gateway/dstack-app/builder/shared/pinned-packages.txt +++ b/dstack/gateway/dstack-app/builder/shared/pinned-packages.txt @@ -4,7 +4,7 @@ base-files=12.4+deb12u11 base-passwd=3.6.1 bash=5.2.15-2+b8 bsdutils=1:2.38.1-5+deb12u3 -ca-certificates=20230311+deb12u1 +ca-certificates=20250419~deb12u2 coreutils=9.1-1 dash=0.5.12-2 debconf=1.5.82 @@ -23,7 +23,7 @@ gzip=1.12-1 hostname=3.23+nmu1 init-system-helpers=1.65.2 iproute2=6.1.0-3 -jq=1.6-2.1+deb12u1 +jq=1.6-2.1+deb12u3 libacl1:amd64=2.3.1-3 libapt-pkg6.0:amd64=2.6.1 libattr1:amd64=1:2.5.1-4 @@ -37,11 +37,11 @@ libbz2-1.0:amd64=1.0.8-5+b1 libc-bin=2.36-9+deb12u10 libc6:amd64=2.36-9+deb12u10 libcap-ng0:amd64=0.8.3-1+b3 -libcap2-bin=1:2.66-4+deb12u2+b2 -libcap2:amd64=1:2.66-4+deb12u2+b2 +libcap2-bin=1:2.66-4+deb12u3+b1 +libcap2:amd64=1:2.66-4+deb12u3+b1 libcom-err2:amd64=1.47.0-2 libcrypt1:amd64=1:4.4.33-2 -libcurl3-gnutls:amd64=7.88.1-10+deb12u14 +libcurl3-gnutls:amd64=7.88.1-10+deb12u15 libdb5.3:amd64=5.3.28+dfsg2-1 libdebconfclient0:amd64=0.270 libelf1:amd64=0.188-2.1 @@ -56,14 +56,14 @@ libgdbm6:amd64=1.23-3 libgmp10:amd64=2:6.2.1+dfsg1-1.1 libgnutls30:amd64=3.7.9-2+deb12u4 libgpg-error0:amd64=1.46-1 -libgssapi-krb5-2:amd64=1.20.1-2+deb12u4 +libgssapi-krb5-2:amd64=1.20.1-2+deb12u5 libhogweed6:amd64=3.8.1-2 libidn2-0:amd64=2.3.3-1+b1 -libjq1:amd64=1.6-2.1+deb12u1 -libk5crypto3:amd64=1.20.1-2+deb12u4 +libjq1:amd64=1.6-2.1+deb12u3 +libk5crypto3:amd64=1.20.1-2+deb12u5 libkeyutils1:amd64=1.6.3-2 -libkrb5-3:amd64=1.20.1-2+deb12u4 -libkrb5support0:amd64=1.20.1-2+deb12u4 +libkrb5-3:amd64=1.20.1-2+deb12u5 +libkrb5support0:amd64=1.20.1-2+deb12u5 libldap-2.5-0:amd64=2.5.13+dfsg-5 liblz4-1:amd64=1.9.4-1 liblzma5:amd64=5.4.1-1 @@ -71,7 +71,7 @@ libmd0:amd64=1.0.4-2 libmnl0:amd64=1.0.4-3 libmount1:amd64=2.38.1-5+deb12u3 libnettle8:amd64=3.8.1-2 -libnghttp2-14:amd64=1.52.0-1+deb12u2 +libnghttp2-14:amd64=1.52.0-1+deb12u3 libonig5:amd64=6.9.8-1 libp11-kit0:amd64=0.24.1-2 libpam-modules-bin=1.5.2-6+deb12u1 @@ -92,7 +92,7 @@ libsepol2:amd64=3.4-2.1 libsmartcols1:amd64=2.38.1-5+deb12u3 libss2:amd64=1.47.0-2 libssh2-1:amd64=1.10.0-3+b1 -libssl3:amd64=3.0.18-1~deb12u2 +libssl3:amd64=3.0.22-1~deb12u1 libstdc++6:amd64=12.2.0-14+deb12u1 libsystemd0:amd64=252.38-1~deb12u1 libtasn1-6:amd64=4.19.0-2+deb12u1 @@ -111,7 +111,7 @@ mawk=1.3.4.20200120-3.1 mount=2.38.1-5+deb12u3 ncurses-base=6.4-4 ncurses-bin=6.4-4 -openssl=3.0.18-1~deb12u2 +openssl=3.0.22-1~deb12u1 passwd=1:4.13+dfsg1-1+deb12u1 perl-base=5.36.0-7+deb12u3 perl-modules-5.36=5.36.0-7+deb12u3 diff --git a/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt b/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt index e390e80bcc..568d740a48 100644 --- a/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt +++ b/dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt @@ -309,10 +309,10 @@ libpng16-16t64:amd64=1.6.48-1 libpq-dev=17.6-0+deb13u1 libpq5:amd64=17.6-0+deb13u1 libproc2-0:amd64=2:4.0.4-9 -libprotobuf-dev:amd64=3.21.12-11 -libprotobuf-lite32t64:amd64=3.21.12-11 -libprotobuf32t64:amd64=3.21.12-11 -libprotoc32t64:amd64=3.21.12-11 +libprotobuf-dev:amd64=3.21.12-11+deb13u1 +libprotobuf-lite32t64:amd64=3.21.12-11+deb13u1 +libprotobuf32t64:amd64=3.21.12-11+deb13u1 +libprotoc32t64:amd64=3.21.12-11+deb13u1 libpsl-dev:amd64=0.21.2-1.1+b1 libpsl5t64:amd64=0.21.2-1.1+b1 libpython3-stdlib:amd64=3.13.5-1 @@ -347,8 +347,8 @@ libsqlite3-0:amd64=3.46.1-7 libsqlite3-dev:amd64=3.46.1-7 libssh2-1-dev:amd64=1.11.1-1 libssh2-1t64:amd64=1.11.1-1 -libssl-dev:amd64=3.5.5-1~deb13u1 -libssl3t64:amd64=3.5.5-1~deb13u1 +libssl-dev:amd64=3.5.7-1~deb13u3 +libssl3t64:amd64=3.5.7-1~deb13u3 libstdc++-14-dev:amd64=14.2.0-19 libstdc++6:amd64=14.2.0-19 libsvn1:amd64=1.14.5-3 @@ -424,9 +424,9 @@ media-types=13.0.0 mercurial-common=7.0.1-2 mercurial=7.0.1-2 mount=2.41-5 -musl-dev:amd64=1.2.5-3 -musl-tools=1.2.5-3 -musl:amd64=1.2.5-3 +musl-dev:amd64=1.2.5-3.1~deb13u1 +musl-tools=1.2.5-3.1~deb13u1 +musl:amd64=1.2.5-3.1~deb13u1 mysql-common=5.8+1.1.1 native-architecture=0.2.6 ncurses-base=6.5+20250216-2 @@ -434,8 +434,8 @@ ncurses-bin=6.5+20250216-2 netbase=6.5 nettle-dev:amd64=3.10.1-1 openssh-client=1:10.0p1-7 -openssl-provider-legacy=3.5.5-1~deb13u1 -openssl=3.5.5-1~deb13u1 +openssl-provider-legacy=3.5.7-1~deb13u3 +openssl=3.5.7-1~deb13u3 pango1.0-tools=1.56.3-1 passwd=1:4.17.4-2 patch=2.8-2 @@ -446,7 +446,7 @@ pinentry-curses=1.3.1-2 pkgconf-bin=1.8.1-4 pkgconf:amd64=1.8.1-4 procps=2:4.0.4-9 -protobuf-compiler=3.21.12-11 +protobuf-compiler=3.21.12-11+deb13u1 python3-minimal=3.13.5-1 python3-packaging=25.0-1 python3.13-minimal=3.13.5-2 diff --git a/dstack/kms/dstack-app/builder/shared/pinned-packages.txt b/dstack/kms/dstack-app/builder/shared/pinned-packages.txt index e966045f90..34659193c2 100644 --- a/dstack/kms/dstack-app/builder/shared/pinned-packages.txt +++ b/dstack/kms/dstack-app/builder/shared/pinned-packages.txt @@ -4,7 +4,7 @@ base-files=12.4+deb12u11 base-passwd=3.6.1 bash=5.2.15-2+b8 bsdutils=1:2.38.1-5+deb12u3 -ca-certificates=20230311+deb12u1 +ca-certificates=20250419~deb12u2 coreutils=9.1-1 dash=0.5.12-2 debconf=1.5.82 @@ -62,7 +62,7 @@ libsemanage2:amd64=3.4-1+b5 libsepol2:amd64=3.4-2.1 libsmartcols1:amd64=2.38.1-5+deb12u3 libss2:amd64=1.47.0-2 -libssl3:amd64=3.0.18-1~deb12u2 +libssl3:amd64=3.0.22-1~deb12u1 libstdc++6:amd64=12.2.0-14+deb12u1 libsystemd0:amd64=252.38-1~deb12u1 libtasn1-6:amd64=4.19.0-2+deb12u1 @@ -78,7 +78,7 @@ mawk=1.3.4.20200120-3.1 mount=2.38.1-5+deb12u3 ncurses-base=6.4-4 ncurses-bin=6.4-4 -openssl=3.0.18-1~deb12u2 +openssl=3.0.22-1~deb12u1 passwd=1:4.13+dfsg1-1+deb12u1 perl-base=5.36.0-7+deb12u2 sed=4.9-1 diff --git a/dstack/verifier/builder/shared/builder-pinned-packages.txt b/dstack/verifier/builder/shared/builder-pinned-packages.txt index 75a2bc37d6..8717df157d 100644 --- a/dstack/verifier/builder/shared/builder-pinned-packages.txt +++ b/dstack/verifier/builder/shared/builder-pinned-packages.txt @@ -12,7 +12,7 @@ binutils=2.40-2 bsdutils=1:2.38.1-5+deb12u3 build-essential=12.9 bzip2=1.0.8-5+b1 -ca-certificates=20230311+deb12u1 +ca-certificates=20250419~deb12u2 clang-14=1:14.0.6-12 clang=1:14.0-55.7~deb12u1 comerr-dev:amd64=2.1-1.47.0-2+b2 @@ -277,10 +277,10 @@ libpng16-16:amd64=1.6.39-2+deb12u1 libpq-dev=15.15-0+deb12u1 libpq5:amd64=15.15-0+deb12u1 libproc2-0:amd64=2:4.0.2-3 -libprotobuf-dev:amd64=3.21.12-3 -libprotobuf-lite32:amd64=3.21.12-3 -libprotobuf32:amd64=3.21.12-3 -libprotoc32:amd64=3.21.12-3 +libprotobuf-dev:amd64=3.21.12-3+deb12u1 +libprotobuf-lite32:amd64=3.21.12-3+deb12u1 +libprotobuf32:amd64=3.21.12-3+deb12u1 +libprotoc32:amd64=3.21.12-3+deb12u1 libpsl5:amd64=0.21.2-1 libpthread-stubs0-dev:amd64=0.4-1 libpython3-stdlib:amd64=3.11.2-1+b1 @@ -310,8 +310,8 @@ libsqlite3-0:amd64=3.40.1-2+deb12u2 libsqlite3-dev:amd64=3.40.1-2+deb12u2 libss2:amd64=1.47.0-2+b2 libssh2-1:amd64=1.10.0-3+b1 -libssl-dev:amd64=3.0.18-1~deb12u2 -libssl3:amd64=3.0.18-1~deb12u2 +libssl-dev:amd64=3.0.22-1~deb12u1 +libssl3:amd64=3.0.22-1~deb12u1 libstdc++-12-dev:amd64=12.2.0-14+deb12u1 libstdc++6:amd64=12.2.0-14+deb12u1 libsvn1:amd64=1.14.2-4+deb12u1 @@ -390,7 +390,7 @@ ncurses-base=6.4-4 ncurses-bin=6.4-4 netbase=6.4 openssh-client=1:9.2p1-2+deb12u7 -openssl=3.0.18-1~deb12u2 +openssl=3.0.22-1~deb12u1 passwd=1:4.13+dfsg1-1+deb12u2 patch=2.7.6-7 perl-base=5.36.0-7+deb12u3 @@ -401,7 +401,7 @@ pkg-config:amd64=1.8.1-1 pkgconf-bin=1.8.1-1 pkgconf:amd64=1.8.1-1 procps=2:4.0.2-3 -protobuf-compiler=3.21.12-3 +protobuf-compiler=3.21.12-3+deb12u1 python3-distutils=3.11.2-3 python3-lib2to3=3.11.2-3 python3-minimal=3.11.2-1+b1 diff --git a/dstack/verifier/builder/shared/pinned-packages.txt b/dstack/verifier/builder/shared/pinned-packages.txt index a99c0061bd..efd5dfac5f 100644 --- a/dstack/verifier/builder/shared/pinned-packages.txt +++ b/dstack/verifier/builder/shared/pinned-packages.txt @@ -4,9 +4,9 @@ base-files=12.4+deb12u11 base-passwd=3.6.1 bash=5.2.15-2+b8 bsdutils=1:2.38.1-5+deb12u3 -ca-certificates=20230311+deb12u1 +ca-certificates=20250419~deb12u2 coreutils=9.1-1 -curl=7.88.1-10+deb12u14 +curl=7.88.1-10+deb12u15 dash=0.5.12-2 debconf=1.5.82 debian-archive-keyring=2023.3+deb12u2 @@ -35,7 +35,7 @@ libcap-ng0:amd64=0.8.3-1+b3 libcap2:amd64=1:2.66-4+deb12u1 libcom-err2:amd64=1.47.0-2 libcrypt1:amd64=1:4.4.33-2 -libcurl4:amd64=7.88.1-10+deb12u14 +libcurl4:amd64=7.88.1-10+deb12u15 libdb5.3:amd64=5.3.28+dfsg2-1 libdebconfclient0:amd64=0.270 libext2fs2:amd64=1.47.0-2 @@ -45,20 +45,20 @@ libgcrypt20:amd64=1.10.1-3 libgmp10:amd64=2:6.2.1+dfsg1-1.1 libgnutls30:amd64=3.7.9-2+deb12u4 libgpg-error0:amd64=1.46-1 -libgssapi-krb5-2:amd64=1.20.1-2+deb12u4 +libgssapi-krb5-2:amd64=1.20.1-2+deb12u5 libhogweed6:amd64=3.8.1-2 libidn2-0:amd64=2.3.3-1+b1 -libk5crypto3:amd64=1.20.1-2+deb12u4 +libk5crypto3:amd64=1.20.1-2+deb12u5 libkeyutils1:amd64=1.6.3-2 -libkrb5-3:amd64=1.20.1-2+deb12u4 -libkrb5support0:amd64=1.20.1-2+deb12u4 +libkrb5-3:amd64=1.20.1-2+deb12u5 +libkrb5support0:amd64=1.20.1-2+deb12u5 libldap-2.5-0:amd64=2.5.13+dfsg-5 liblz4-1:amd64=1.9.4-1 liblzma5:amd64=5.4.1-1 libmd0:amd64=1.0.4-2 libmount1:amd64=2.38.1-5+deb12u3 libnettle8:amd64=3.8.1-2 -libnghttp2-14:amd64=1.52.0-1+deb12u2 +libnghttp2-14:amd64=1.52.0-1+deb12u3 libp11-kit0:amd64=0.24.1-2 libpam-modules-bin=1.5.2-6+deb12u1 libpam-modules:amd64=1.5.2-6+deb12u1 @@ -77,7 +77,7 @@ libsepol2:amd64=3.4-2.1 libsmartcols1:amd64=2.38.1-5+deb12u3 libss2:amd64=1.47.0-2 libssh2-1:amd64=1.10.0-3+b1 -libssl3:amd64=3.0.18-1~deb12u2 +libssl3:amd64=3.0.22-1~deb12u1 libstdc++6:amd64=12.2.0-14+deb12u1 libsystemd0:amd64=252.38-1~deb12u1 libtasn1-6:amd64=4.19.0-2+deb12u1 @@ -93,7 +93,7 @@ mawk=1.3.4.20200120-3.1 mount=2.38.1-5+deb12u3 ncurses-base=6.4-4 ncurses-bin=6.4-4 -openssl=3.0.18-1~deb12u2 +openssl=3.0.22-1~deb12u1 passwd=1:4.13+dfsg1-1+deb12u1 perl-base=5.36.0-7+deb12u2 sed=4.9-1 From aa063309f4a7838d950f7b1149f01477460d9a15 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 08:11:27 +0800 Subject: [PATCH 027/572] fix(os): move the mkosi guest OS to a post-emSign snapshot and Go 1.26.10 The mkosi guest OS used the Debian 20260721T000000Z snapshot. Its trixie ca-certificates (20250419) still trusts emSign ECC Root CA - G3 and Comodo AAA Services root, so docker, containerd, curl and every other client in the guest that reads the system trust store accepts a certificate from one of the compromised eMudhra/emSign intermediates. Advance Snapshot in mkosi.conf and mkosi.tools.conf, and DEBIAN_SNAPSHOT in versions.env, to 20261021T000000Z. mkosi also adds the debian-security archive at the same timestamp, and that snapshot carries ca-certificates 20250419+deb13u1. The rest of the trixie package set moves forward to that date as well. Move the toolchain used for the Go components (sysbox and others) from 1.26.2 to 1.26.10, which carries the CVE-2026-111943 fix: crypto/x509 rejects chains with the compromised intermediate CA keys. Update the acceptance assertions for both values. This puts the mkosi Go ahead of the Go that oe-core pins for the Yocto backend. The upstream nerdctl 2.3.5 and stargz 0.18.2 binaries stay as they are: their newest releases (nerdctl 2.4.1, stargz 0.19.0) predate the Go fix. The rootfs changes, so the OS image hash and the measurements change, and the OS image allowlists in the auth configs and on chain must be updated. Signed-off-by: Leechael Yim --- os/mkosi/mkosi.conf | 2 +- os/mkosi/mkosi.tools.conf | 2 +- os/mkosi/tests/acceptance.sh | 11 ++++++----- os/mkosi/versions.env | 6 +++--- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/os/mkosi/mkosi.conf b/os/mkosi/mkosi.conf index 185087377b..54835a0e9e 100644 --- a/os/mkosi/mkosi.conf +++ b/os/mkosi/mkosi.conf @@ -6,7 +6,7 @@ MinimumVersion=26 Distribution=debian Release=trixie Architecture=x86-64 -Snapshot=20260721T000000Z +Snapshot=20261021T000000Z Repositories=main,contrib,non-free-firmware [Output] diff --git a/os/mkosi/mkosi.tools.conf b/os/mkosi/mkosi.tools.conf index c83a700e35..be614b18f5 100644 --- a/os/mkosi/mkosi.tools.conf +++ b/os/mkosi/mkosi.tools.conf @@ -1,4 +1,4 @@ # SPDX-License-Identifier: Apache-2.0 [Distribution] -Snapshot=20260721T000000Z +Snapshot=20261021T000000Z Repositories=main diff --git a/os/mkosi/tests/acceptance.sh b/os/mkosi/tests/acceptance.sh index 0f34d11ce3..aeee04a4f9 100755 --- a/os/mkosi/tests/acceptance.sh +++ b/os/mkosi/tests/acceptance.sh @@ -268,16 +268,17 @@ grep -q 'scripts/build-components.sh' "$D/mkosi.build" grep -q '^BuildPackages=' "$D/mkosi.conf" grep -q '^ToolsTree=yes$' "$D/mkosi.conf" grep -q '^ToolsTreeProfiles=misc$' "$D/mkosi.conf" -grep -q '^Snapshot=20260721T000000Z$' "$D/mkosi.tools.conf" +grep -q '^Snapshot=20261021T000000Z$' "$D/mkosi.tools.conf" grep -q 'clean -f' "$D/build.sh" grep -q 'install-toolchains.sh' "$D/mkosi.build" grep -q '^RUST_TOOLCHAIN_VERSION=1.92.0$' "$D/versions.env" -# Tracks the Go that oe-core pins for the production Yocto backend, so both -# backends compile the same Go components with the same toolchain. It must also -# stay >= the highest 'go' directive among them (nvidia-container-toolkit +# Go 1.26.10 carries the CVE-2026-111943 fix (crypto/x509 rejects chains with +# the compromised eMudhra/emSign intermediate CA keys), so this is ahead of the +# Go that oe-core pins for the production Yocto backend. It must also stay >= +# the highest 'go' directive among the Go components (nvidia-container-toolkit # currently declares go 1.25.0); GOTOOLCHAIN=local turns a violation into a # build failure rather than a silent download. -grep -q '^GO_TOOLCHAIN_VERSION=1.26.2$' "$D/versions.env" +grep -q '^GO_TOOLCHAIN_VERSION=1.26.10$' "$D/versions.env" for component in dstack-rust image-tools container-stack sysbox nvattest kernel nvidia zfs ovmf; do definition="$D/components/$component/$component.sh" grep -q "^COMPONENT_NAME=$component$" "$definition" diff --git a/os/mkosi/versions.env b/os/mkosi/versions.env index fcebc7b159..ff7f0a3e40 100644 --- a/os/mkosi/versions.env +++ b/os/mkosi/versions.env @@ -3,7 +3,7 @@ KERNEL_VERSION=6.18.40 KERNEL_SHA256=3712fc1ec839e4daac981176c8518912e8f452650aaedfe4381da4419613a431 DEBIAN_RELEASE=trixie -DEBIAN_SNAPSHOT=20260721T000000Z +DEBIAN_SNAPSHOT=20261021T000000Z # Base of the kernel module builder image. It must predate DEBIAN_SNAPSHOT: # apt pinned to the snapshot cannot downgrade packages the base already ships. DEBIAN_BASE_IMAGE=debian:trixie-20260713-slim@sha256:020c0d20b9880058cbe785a9db107156c3c75c2ac944a6aa7ab59f2add76a7bd @@ -17,8 +17,8 @@ RUST_TOOLCHAIN_VERSION=1.92.0 RUSTC_TOOLCHAIN_SHA256=78b2dd9c6b1fcd2621fa81c611cf5e2d6950690775038b585c64f364422886e0 CARGO_TOOLCHAIN_SHA256=e5e12be2c7126a7036c8adf573078a28b92611f5767cc9bd0a6f7c83081df103 RUST_STD_TOOLCHAIN_SHA256=5f106805ed86ebf8df287039e53a45cf974391ef4d088c2760776b05b8e48b5d -GO_TOOLCHAIN_VERSION=1.26.2 -GO_TOOLCHAIN_SHA256=990e6b4bbba816dc3ee129eaeaf4b42f17c2800b88a2166c265ac1a200262282 +GO_TOOLCHAIN_VERSION=1.26.10 +GO_TOOLCHAIN_SHA256=ccfe7ae822d2c2f41f4fe7c956199967a4dac22d0ee0d2b2bfdb440aab3b20c5 NITRO_TPM_TOOLS_REVISION=d76d6eeebd4169b00a3c3af9858852d48f40e748 DSTACK_VERSION=0.6.1 DSTACK_CODENAME=trixie From 6684cb02bdcc54ebee949c448b6b2d28145e38e3 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 08:14:01 +0800 Subject: [PATCH 028/572] fix(kms): run auth-api on Node 22.23.4 and pin the auth-mock Bun image auth-api ran on node:20-bookworm-slim (Node 20.20.2). Node 20 is end of life and has no release that handles the eMudhra/emSign intermediate CA compromise; fetch() in that image accepts a certificate from one of the compromised intermediates. Node 22.23.4 updates the bundled roots and rejects such chains (CERT_REVOKED). Move docker-compose.yaml and compose-dev.yaml to node:22.23.4-bookworm-slim, pinned by digest. auth-mock built from the floating oven/bun:1-alpine tag. Pin it to oven/bun:1.4.3-alpine by digest (the same image the floating tag resolves to today), so the build input is fixed. Bun 1.4.3 still accepts the compromised chains, and no Bun release with a fix was found; bump it when one ships. The auth-api image is part of the KMS compose, so the KMS compose hash changes and must be registered again in the allowlists. Signed-off-by: Leechael Yim --- dstack/kms/auth-mock/Dockerfile | 2 +- dstack/kms/dstack-app/compose-dev.yaml | 2 +- dstack/kms/dstack-app/docker-compose.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dstack/kms/auth-mock/Dockerfile b/dstack/kms/auth-mock/Dockerfile index 75207418ae..d0d36e5958 100644 --- a/dstack/kms/auth-mock/Dockerfile +++ b/dstack/kms/auth-mock/Dockerfile @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Apache-2.0 -FROM oven/bun:1-alpine +FROM oven/bun:1.4.3-alpine@sha256:629e17411f1f129dbec3af78d5af9c9f2a937435c80349437206c6b0b7422373 WORKDIR /app ARG DSTACK_REV diff --git a/dstack/kms/dstack-app/compose-dev.yaml b/dstack/kms/dstack-app/compose-dev.yaml index a642b32187..02e17c4b59 100644 --- a/dstack/kms/dstack-app/compose-dev.yaml +++ b/dstack/kms/dstack-app/compose-dev.yaml @@ -8,7 +8,7 @@ services: build: context: . dockerfile_inline: | - FROM node:20-bookworm-slim@sha256:2cf067cfed83d5ea958367df9f966191a942351a2df77d6f0193e162b5febfc0 + FROM node:22.23.4-bookworm-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* diff --git a/dstack/kms/dstack-app/docker-compose.yaml b/dstack/kms/dstack-app/docker-compose.yaml index a83d5f3342..4fb1b603fa 100644 --- a/dstack/kms/dstack-app/docker-compose.yaml +++ b/dstack/kms/dstack-app/docker-compose.yaml @@ -32,7 +32,7 @@ services: build: context: . dockerfile_inline: | - FROM node:20-bookworm-slim@sha256:2cf067cfed83d5ea958367df9f966191a942351a2df77d6f0193e162b5febfc0 + FROM node:22.23.4-bookworm-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d WORKDIR /app RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* From 7d8f2260ffacad8a9dd81a4c4395306758fc6662 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 08:16:24 +0800 Subject: [PATCH 029/572] fix(sdk): pick up the emSign CA fixes in the Rust and Python SDK locks Rust SDK: reqwest 0.12 with rustls-tls uses the roots compiled in from webpki-roots. The lock had webpki-roots 1.0.8 and rustls-webpki 0.103.15, and that combination accepts a certificate issued by one of the compromised eMudhra/emSign intermediate CAs. Move rustls-webpki to 0.103.16 (RUSTSEC-2026-0383, CVE-2026-111943), which rejects chains with those keys, and webpki-roots to 1.0.10. Python SDK: httpx uses certifi by default. The lock had certifi 2025.8.3, which still holds emSign ECC Root CA - G3. Move it to 2026.10.19 and add certifi>=2026.10.19 to the dependencies, so installs outside the lock also get a fixed bundle. pdm 2.29 rewrote lock_version from 4.5.0 to 4.5.1. Both SDKs are libraries: applications that depend on them resolve their own versions, so they need to update their locks too. Signed-off-by: Leechael Yim --- sdk/python/pdm.lock | 10 +++++----- sdk/python/pyproject.toml | 1 + sdk/rust/Cargo.lock | 8 ++++---- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/sdk/python/pdm.lock b/sdk/python/pdm.lock index 3ffaff90c1..325940f429 100644 --- a/sdk/python/pdm.lock +++ b/sdk/python/pdm.lock @@ -4,8 +4,8 @@ [metadata] groups = ["default", "dev", "ethereum", "lint", "solana"] strategy = ["inherit_metadata"] -lock_version = "4.5.0" -content_hash = "sha256:9f51ba70b678858ab30777d25d4596d2ad8101438269cd2a4be5b2325eaa6c9b" +lock_version = "4.5.1" +content_hash = "sha256:1385af9667052c21cb40fd49db74325b2cb096680c162be549795a89e44c64c0" [[metadata.targets]] requires_python = ">=3.10" @@ -137,13 +137,13 @@ files = [ [[package]] name = "certifi" -version = "2025.8.3" +version = "2026.10.19" requires_python = ">=3.7" summary = "Python package for providing Mozilla's CA Bundle." groups = ["default"] files = [ - {file = "certifi-2025.8.3-py3-none-any.whl", hash = "sha256:f6c12493cfb1b06ba2ff328595af9350c65d6644968e5d3a2ffd78699af217a5"}, - {file = "certifi-2025.8.3.tar.gz", hash = "sha256:e564105f78ded564e3ae7c923924435e1daa7463faeab5bb932bc53ffae63407"}, + {file = "certifi-2026.10.19-py3-none-any.whl", hash = "sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b"}, + {file = "certifi-2026.10.19.tar.gz", hash = "sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae"}, ] [[package]] diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml index d67994ef75..05d209568c 100644 --- a/sdk/python/pyproject.toml +++ b/sdk/python/pyproject.toml @@ -12,6 +12,7 @@ authors = [ ] dependencies = [ "httpx>=0.27.2", + "certifi>=2026.10.19", "asyncio>=3.4.3", "pydantic>=2.9.2", "cryptography>=43.0.0", diff --git a/sdk/rust/Cargo.lock b/sdk/rust/Cargo.lock index 093f375481..76e77079b8 100644 --- a/sdk/rust/Cargo.lock +++ b/sdk/rust/Cargo.lock @@ -3438,9 +3438,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.15" +version = "0.103.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" dependencies = [ "ring", "rustls-pki-types", @@ -4391,9 +4391,9 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "1.0.8" +version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" dependencies = [ "rustls-pki-types", ] From a736f5c3e9a11a7e3b08bea0ef0eebb1d45d9feb Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 10:03:26 +0800 Subject: [PATCH 030/572] test(ra-rpc): accept connection-canceled as handshake refusal rustls-webpki 0.103.16 pulls aws-lc-rs 1.18, which sometimes closes the TCP connection instead of sending HandshakeFailure. reqwest then reports Canceled / connection was not ready. The cert is still refused. Signed-off-by: Leechael Yim --- dstack/ra-rpc/tests/ratls_client_auth.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/dstack/ra-rpc/tests/ratls_client_auth.rs b/dstack/ra-rpc/tests/ratls_client_auth.rs index 9719c508c2..3e60d10a1b 100644 --- a/dstack/ra-rpc/tests/ratls_client_auth.rs +++ b/dstack/ra-rpc/tests/ratls_client_auth.rs @@ -181,9 +181,14 @@ async fn client_certs_are_authenticated_by_attestation_not_issuer() { let err = probe(port, Some(&no_attestation)) .await .expect_err("cert without attestation must be rejected"); + let err_text = format!("{err:#}"); + // rustls usually surfaces HandshakeFailure. Under aws-lc-rs 1.18 the server + // may close the TCP connection instead, and reqwest then reports Canceled. assert!( - format!("{err:#}").contains("HandshakeFailure"), - "expected the handshake to be refused, got: {err:#}" + err_text.contains("HandshakeFailure") + || err_text.contains("Canceled") + || err_text.contains("connection was not ready"), + "expected the handshake to be refused, got: {err_text}" ); // Anonymous connections still work, so unauthenticated RPCs stay reachable. From 9271cd59b9fa6b3c420d9c59b40c970d43fd43a2 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 21 Oct 2026 02:18:39 -0700 Subject: [PATCH 031/572] feat: add requirements.ephemeral_data_disk Signed-off-by: Kevin Wang --- CHANGELOG.md | 3 +++ docs/security/cvm-boundaries.md | 1 + dstack/dstack-types/src/lib.rs | 11 +++++++++++ dstack/dstack-util/src/system_setup.rs | 11 ++++++++--- 4 files changed, 23 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5bbc05aef5..4f5c18bc87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- guest: `requirements.ephemeral_data_disk` in `app-compose.json` starts every boot with an empty data disk. The guest formats the data disk before any app code runs (#1461) + ### Fixed - guest: a fresh CVM with a verity volume could take the volume for its data disk and try to LUKS-format it: volumes labelled their data partition `dstack-data`, the data disk's label. `dstack verity` now labels it `dstack-volume-data`, and the guest skips disks that carry a `dstack-volume` partition, so volumes built by older releases are safe too diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 8c4380c230..df369899b8 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -44,6 +44,7 @@ This is the main configuration file for the application in JSON format: | init_script | 0.5.5 (string), 0.6.0 (string[]) | string or string[] | Up to 5 Bash scripts executed in order prior to dockerd startup, so they always complete before any container starts, on every boot; a string is treated as a one-element array. Multiple scripts require string `manifest_version: "3"` so older guests fail closed. MrConfigV3 binds the hashes only for manifest v3. | | storage_fs | 0.5.5 | string | Filesystem type for the data disk of the CVM. Supported values: "zfs", "ext4". default to "zfs". **ZFS:** Checksums every block, so a modified block fails the read. **ext4:** Lower overhead and faster I/O for database workloads; checksums metadata but not file data, so a modified block is not detected. | | storage_discard | 0.6.0 | boolean | Return unused data-disk blocks to the host. Defaults to `true` so encrypted sparse images track live data instead of historical writes. Set to `false` if revealing filesystem allocation and deletion patterns to the host is unacceptable. | +| requirements.ephemeral_data_disk | 0.6.2 | boolean | Start every boot with an empty data disk. The guest formats the data disk before any app code runs, so app code sees nothing an earlier boot wrote. With storage encryption on (the default), each format generates a fresh LUKS volume key, so earlier ciphertext, including a disk image the host rolled back, can no longer be decrypted. With encryption off, old blocks may remain readable on the raw device. Images and container layers live on the data disk, so every boot pulls them again. Defaults to `false`. Requires string `manifest_version: "3"`. | | swap_size | 0.5.5 | string/integer | The linux swap size. default to 0. Can be in byte or human-readable format (e.g., "1G", "256M"). | | key_provider | 0.5.6 | string | Key provider type. Supported values: "none", "kms", "local", "tpm". GCP vTPM and AWS EC2 NitroTPM are part of their platform trust models. The Dstack platform can use VMM-managed swtpm for seal/unseal and restart persistence, but it offers no protection against the host and is intentionally not accepted by remote verifiers. | diff --git a/dstack/dstack-types/src/lib.rs b/dstack/dstack-types/src/lib.rs index 0e52e878ea..a0ce437e21 100644 --- a/dstack/dstack-types/src/lib.rs +++ b/dstack/dstack-types/src/lib.rs @@ -533,6 +533,10 @@ pub struct Requirements { /// on chain. #[serde(default, skip_serializing_if = "Option::is_none")] pub health_status_file: Option, + /// Start every boot with an empty data disk. The guest formats the data + /// disk before any app code runs, discarding what earlier boots left on it. + #[serde(default, skip_serializing_if = "is_false")] + pub ephemeral_data_disk: bool, } impl Requirements { @@ -543,6 +547,7 @@ impl Requirements { && self.gpu_policy.is_default() && !self.health_check && self.health_status_file.is_none() + && !self.ephemeral_data_disk } } @@ -801,6 +806,12 @@ impl AppCompose { self.key_provider().is_kms() } + pub fn ephemeral_data_disk(&self) -> bool { + self.requirements + .as_ref() + .is_some_and(|requirements| requirements.ephemeral_data_disk) + } + pub fn key_provider(&self) -> KeyProviderKind { match self.key_provider { Some(p) => p, diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 2aa9df286f..114e8d37e2 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -2648,7 +2648,11 @@ impl<'a> Stage0<'a> { cmd!(mkdir -p $mount_point).context("Failed to create mount point")?; - let disk_initialized = self.is_disk_initialized(opts); + let ephemeral = self.shared.app_compose.ephemeral_data_disk(); + if ephemeral { + info!("discarding previous data disk contents (requirements.ephemeral_data_disk)"); + } + let disk_initialized = !ephemeral && self.is_disk_initialized(opts); let has_filesystem = if opts.storage_encrypted && disk_initialized { info!("Mounting encrypted data disk"); @@ -2677,8 +2681,9 @@ impl<'a> Stage0<'a> { match opts.storage_fs { FsType::Zfs => { info!("Creating ZFS filesystem"); - if disk_initialized { - // The interrupted attempt may have left a pool label behind. + if disk_initialized || ephemeral { + // An interrupted attempt or a previous boot may have + // left a pool label behind. cmd!(zpool labelclear -f $fs_dev).ok(); } let autotrim = if opts.storage_discard { "on" } else { "off" }; From 01637c387e4099bc09f2a8a702733a17ce4c5235 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 21 Oct 2026 02:18:39 -0700 Subject: [PATCH 032/572] feat(sdk): add ephemeral_data_disk to compose requirements Signed-off-by: Kevin Wang --- sdk/go/dstack/compose_hash.go | 4 ++++ sdk/go/dstack/compose_hash_ephemeral_test.go | 22 +++++++++++++++++++ sdk/js/src/get-compose-hash.ts | 2 ++ sdk/python/src/dstack_sdk/get_compose_hash.py | 4 ++++ sdk/python/tests/test_get_compose_hash.py | 15 +++++++++++++ 5 files changed, 47 insertions(+) create mode 100644 sdk/go/dstack/compose_hash_ephemeral_test.go diff --git a/sdk/go/dstack/compose_hash.go b/sdk/go/dstack/compose_hash.go index 712f212bcb..9f27f3a0e0 100644 --- a/sdk/go/dstack/compose_hash.go +++ b/sdk/go/dstack/compose_hash.go @@ -70,6 +70,10 @@ type Requirements struct { // pointer for the same reason. HealthStatusFile *string `json:"health_status_file,omitempty"` + // EphemeralDataDisk formats the data disk on every boot. Like HealthCheck, + // a false value must stay out of the manifest. + EphemeralDataDisk bool `json:"ephemeral_data_disk,omitempty"` + GpuPolicy *GpuPolicy `json:"gpu_policy,omitempty"` // Extra carries fields this SDK does not know; see AppCompose.Extra. diff --git a/sdk/go/dstack/compose_hash_ephemeral_test.go b/sdk/go/dstack/compose_hash_ephemeral_test.go new file mode 100644 index 0000000000..7719c59d3f --- /dev/null +++ b/sdk/go/dstack/compose_hash_ephemeral_test.go @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: © 2025 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +package dstack + +import "testing" + +func TestDisabledEphemeralDataDiskHashesAsAbsent(t *testing.T) { + disabled := AppCompose{ + Runner: "docker-compose", + Requirements: &Requirements{LaunchTokenHash: "ff00", EphemeralDataDisk: false}, + } + got, err := GetComposeHash(disabled) + if err != nil { + t.Fatal(err) + } + want := hashOfRawJSON(t, `{"runner":"docker-compose","requirements":{"launch_token_hash":"ff00"}}`) + if got != want { + t.Fatalf("a false ephemeral_data_disk must not appear in the manifest.\n got=%s\nwant=%s", got, want) + } +} diff --git a/sdk/js/src/get-compose-hash.ts b/sdk/js/src/get-compose-hash.ts index ba3e9fe1b3..4148433bab 100644 --- a/sdk/js/src/get-compose-hash.ts +++ b/sdk/js/src/get-compose-hash.ts @@ -71,6 +71,8 @@ export interface Requirements extends SortableObject { * different app composes and hash differently, in every SDK. */ health_status_file?: string; + /** Format the data disk on every boot. Leave it out rather than passing `false`. */ + ephemeral_data_disk?: boolean; gpu_policy?: GpuPolicy; } diff --git a/sdk/python/src/dstack_sdk/get_compose_hash.py b/sdk/python/src/dstack_sdk/get_compose_hash.py index 9499c30513..2a33e17764 100644 --- a/sdk/python/src/dstack_sdk/get_compose_hash.py +++ b/sdk/python/src/dstack_sdk/get_compose_hash.py @@ -60,6 +60,7 @@ def __init__( health_check: bool = False, health_status_file: Optional[str] = None, gpu_policy: Optional[Dict[str, Any]] = None, + ephemeral_data_disk: bool = False, **kwargs: Any, ) -> None: """Initialize a new ``Requirements`` instance.""" @@ -69,6 +70,7 @@ def __init__( self.health_check = health_check self.health_status_file = health_status_file self.gpu_policy = gpu_policy + self.ephemeral_data_disk = ephemeral_data_disk self._extra = dict(kwargs) def to_dict(self) -> Dict[str, Any]: @@ -89,6 +91,8 @@ def to_dict(self) -> Dict[str, Any]: # composes, so they must be different hashes in every SDK. if self.health_status_file is not None: result["health_status_file"] = self.health_status_file + if self.ephemeral_data_disk: + result["ephemeral_data_disk"] = True if self.gpu_policy is not None: result["gpu_policy"] = self.gpu_policy result.update(self._extra) diff --git a/sdk/python/tests/test_get_compose_hash.py b/sdk/python/tests/test_get_compose_hash.py index b73e26f90b..fcb6c54297 100644 --- a/sdk/python/tests/test_get_compose_hash.py +++ b/sdk/python/tests/test_get_compose_hash.py @@ -289,6 +289,21 @@ def test_health_check_off_hashes_as_if_it_were_absent(): assert get_compose_hash(absent) == get_compose_hash(disabled) +def test_ephemeral_data_disk_off_hashes_as_if_it_were_absent(): + """The guest's Rust types skip a false `ephemeral_data_disk`.""" + from dstack_sdk.get_compose_hash import Requirements + + absent = AppCompose( + runner="docker-compose", requirements=Requirements(launch_token_hash="ff00") + ) + disabled = AppCompose( + runner="docker-compose", + requirements=Requirements(launch_token_hash="ff00", ephemeral_data_disk=False), + ) + + assert get_compose_hash(absent) == get_compose_hash(disabled) + + def test_health_status_file_is_part_of_the_hash(): """`health_status_file` selects the verdict source, so it is not cosmetic.""" from dstack_sdk.get_compose_hash import Requirements From 247104772a3de98d818a8feac101ff0f355cefae Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 13 Oct 2026 19:33:01 +0800 Subject: [PATCH 033/572] build(deps): upgrade auth-eth-bun dependencies bun audit reported 10 advisories (6 high), among them: - hono < 4.13.7: unescaped strings in hono/jsx boundary components (GHSA-hxh3-vqpv-xpqv). This backend does not render JSX, but the pinned version still carried the advisory. - ws < 8.20.1 through viem > isows: memory disclosure and fragment DoS (GHSA-58qx-3vcg-4xpx, GHSA-96hv-2xvq-fx4p). - braces, flatted, fflate, picomatch: dev-only, mostly through the unused @vitest/ui. Runtime: hono 4.13.13, @hono/zod-validator 0.9.1, viem 2.57.5. zod stays on 3.25.76, which carries no advisory; moving to zod 4 is a separate API change. Dev: drop @vitest/ui and openapi-types, which nothing imports; vitest 5.0.4, oxlint 1.88.0, typescript 5.9.3, @types/bun 1.4.2. Override source-map-js to 1.2.2 (GHSA-68fv-2mgg-jv7q via vite). bun audit is now clean. oxlint 1.x rejects the 0.9 config format, so .oxlintrc.json moves to `plugins` and `ignorePatterns`, and the two catch clauses that never read their error drop the binding. Signed-off-by: Leechael Yim --- dstack/kms/auth-eth-bun/.oxlintrc.json | 16 +- dstack/kms/auth-eth-bun/bun.lock | 218 ++++++++----------------- dstack/kms/auth-eth-bun/index.ts | 4 +- dstack/kms/auth-eth-bun/package.json | 25 +-- 4 files changed, 86 insertions(+), 177 deletions(-) diff --git a/dstack/kms/auth-eth-bun/.oxlintrc.json b/dstack/kms/auth-eth-bun/.oxlintrc.json index f7d7b8e35e..640a8f158e 100644 --- a/dstack/kms/auth-eth-bun/.oxlintrc.json +++ b/dstack/kms/auth-eth-bun/.oxlintrc.json @@ -1,21 +1,11 @@ { - "$schema": "https://raw.githubusercontent.com/oxc-project/oxc/main/crates/oxc_linter/src/config/schema.json", - "rules": { - "typescript": "warn", - "unicorn": "warn", - "react": "off", - "jsx-a11y": "off", - "nextjs": "off" - }, + "$schema": "./node_modules/oxlint/configuration_schema.json", + "plugins": ["typescript", "unicorn"], "env": { "node": true, "es2022": true }, - "globals": { - "globalThis": "readonly", - "console": "readonly" - }, - "ignore_patterns": [ + "ignorePatterns": [ "node_modules/**", "dist/**", "build/**", diff --git a/dstack/kms/auth-eth-bun/bun.lock b/dstack/kms/auth-eth-bun/bun.lock index a471f6bc8d..bdd9d761fd 100644 --- a/dstack/kms/auth-eth-bun/bun.lock +++ b/dstack/kms/auth-eth-bun/bun.lock @@ -1,65 +1,83 @@ { "lockfileVersion": 1, + "configVersion": 0, "workspaces": { "": { "name": "auth-eth-bun", "dependencies": { - "@hono/zod-validator": "0.2.2", - "hono": "4.13.5", - "viem": "2.31.7", + "@hono/zod-validator": "0.9.1", + "hono": "4.13.13", + "viem": "2.57.5", "zod": "3.25.76", }, "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "^24.0.14", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "4.1.11", + "@types/bun": "1.4.2", + "@types/node": "24.19.2", + "oxlint": "1.88.0", + "typescript": "5.9.3", + "vitest": "5.0.4", }, }, }, + "overrides": { + "source-map-js": "1.2.2", + }, "packages": { "@adraffy/ens-normalize": ["@adraffy/ens-normalize@1.11.0", "", {}, "sha512-/3DDPKHqqIqxUULp8yP4zODUY1i+2xvVWsv8A79xGWdCAG+8sb0hRh0Rk2QyOJUnnbyPUAZYcpBuRe3nS2OIUg=="], - "@hono/zod-validator": ["@hono/zod-validator@0.2.2", "", { "peerDependencies": { "hono": ">=3.9.0", "zod": "^3.19.1" } }, "sha512-dSDxaPV70Py8wuIU2QNpoVEIOSzSXZ/6/B/h4xA7eOMz7+AarKTSGV8E6QwrdcCbBLkpqfJ4Q2TmBO0eP1tCBQ=="], + "@hono/zod-validator": ["@hono/zod-validator@0.9.1", "", { "peerDependencies": { "hono": ">=4.11.2", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-iiv6w0qrIc0arfvCtUqBWsvl4fXjzaTcQcCJTTtCnkawF9HHGE+KjEl0ox3gQJ6rKZEgE3mLExlQCF72M+mNuw=="], - "@jest/schemas": ["@jest/schemas@29.6.3", "", { "dependencies": { "@sinclair/typebox": "^0.27.8" } }, "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA=="], + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.6.0", "", {}, "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw=="], + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@noble/ciphers": ["@noble/ciphers@1.3.0", "", {}, "sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw=="], - "@noble/curves": ["@noble/curves@1.9.2", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-HxngEd2XUcg9xi20JkwlLCtYwfoFw4JGkuZpT+WlsPD4gB/cxkvTD8fSsoAnphGZhFdZYKeQIPCuFlWPm1uE0g=="], + "@noble/curves": ["@noble/curves@1.9.1", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-k11yZxZg+t+gWvBbIswW0yoJlu8cHOC7dhunwOzoWH/mXGBiYyR4YY6hAEK/3EUs4UpB8la1RfdRpeGsFHkWsA=="], "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], + "@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="], - "@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="], + "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.88.0", "", { "os": "android", "cpu": "arm" }, "sha512-k6Fgkf86ubfeH4GvqYsRolfuVAp0pfYVZvifSlXNHPdMaWUOfxUrmLEeDD7hF6U2oJuhsVxhSWq86/xCJ+9MmA=="], - "@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="], + "@oxlint/binding-android-arm64": ["@oxlint/binding-android-arm64@1.88.0", "", { "os": "android", "cpu": "arm64" }, "sha512-AsIyhl9o1ejwtac7NMbhKpMdSml6NWR0ljKjZERxC8OHYDAW8o/Om9n1QHVLi4VCEUo42Zte2/Op9kyoGpJZMg=="], - "@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="], + "@oxlint/binding-darwin-arm64": ["@oxlint/binding-darwin-arm64@1.88.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-qgBjB7eEKcCB4RqjXGuoSZq74g0wD09fWFJ+HWcCJcKaga8TeUHtb+BY0SsxdleSLBgx4RZ7qmgo0EzqEq7JoQ=="], + + "@oxlint/binding-darwin-x64": ["@oxlint/binding-darwin-x64@1.88.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-sCz3X5Mw/xdzEzn4fsCt1Iq8NKJnGNfhR+b9B5k+4DysYAHsmIhYoocnBPiQ9kvY3+pUun2A0Z8Vtun/Nv6YoQ=="], + + "@oxlint/binding-freebsd-x64": ["@oxlint/binding-freebsd-x64@1.88.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-xTOdYOIqCufgIj0knvxu86FBfovP6QBiD7ngNva01gb8xPQCD5gXkE5APGczH35zStim1O3zqvFbLQmY85xXRg=="], + + "@oxlint/binding-linux-arm-gnueabihf": ["@oxlint/binding-linux-arm-gnueabihf@1.88.0", "", { "os": "linux", "cpu": "arm" }, "sha512-BLadtw88NdYJBrAtC1dYzrPfSP2d5zgx6iuZycdD0YmZBJ2Nqbit9Z4PSaIb6gxK25dweArGMPbOmq/0ugwUPg=="], + + "@oxlint/binding-linux-arm-musleabihf": ["@oxlint/binding-linux-arm-musleabihf@1.88.0", "", { "os": "linux", "cpu": "arm" }, "sha512-wILSczl/DaZsCcf7j7tvNbssp8hxEHIJxrv4j7+JjI3TAL1U/JTWbeUtoJJC/vo8+2hkTmHLYoKJjmiNbijdXw=="], - "@oxlint/darwin-arm64": ["@oxlint/darwin-arm64@0.9.10", "", { "os": "darwin", "cpu": "arm64" }, "sha512-eOXKZYq5bnCSgDefgM5bzAg+4Fc//Rc4yjgKN8iDWUARweCaChiQXb6TXX8MfEfs6qayEMy6yVj0pqoFz0B1aw=="], + "@oxlint/binding-linux-arm64-gnu": ["@oxlint/binding-linux-arm64-gnu@1.88.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-jutT2Hy8JCuZuMwIFHo2HtyxfOfBJHyQxlBHBK1SL9W2f8n/WhjAP0FnDMz9d/mjhv9+QA0mx5AdQ9fDjsrFFg=="], - "@oxlint/darwin-x64": ["@oxlint/darwin-x64@0.9.10", "", { "os": "darwin", "cpu": "x64" }, "sha512-UeYICDvLUaUOcY+0ugZUEmBMRLP+x8iTgL7TeY6BlpGw2ahbtUOTbyIIRWtr/0O++TnjZ+v8TzhJ9crw6Ij6dg=="], + "@oxlint/binding-linux-arm64-musl": ["@oxlint/binding-linux-arm64-musl@1.88.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-8N8iGV9hh4Lkeuq7QsEkjoXNRRflqR1G2qyoGYXcA0k5qllrdqmfylKEXyHIVERxqNDyMO4StqDQ0uLxXcBQAg=="], - "@oxlint/linux-arm64-gnu": ["@oxlint/linux-arm64-gnu@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-0Zn+vqHhrZyufFBfq9WOgiIool0gCR14BLsdS+0Dwd9o+kNxPGA5q7erQFkiC4rpkxtfBHeD3iIKMMt7d29Kyw=="], + "@oxlint/binding-linux-ppc64-gnu": ["@oxlint/binding-linux-ppc64-gnu@1.88.0", "", { "os": "linux", "cpu": "ppc64" }, "sha512-5ydcQt3znNQ/rGEWYRvpS2cK9+T18P2VYgnyJ+eloEAwi9YUmsXy5VGrRqNWIK6qzWwHGnEE3ojVqqQNo+f0hA=="], - "@oxlint/linux-arm64-musl": ["@oxlint/linux-arm64-musl@0.9.10", "", { "os": "linux", "cpu": "arm64" }, "sha512-tkQcWpYwF42bA/uRaV2iMFePHkBjTTgomOgeEaiw6XOSJX4nBEqGIIboqqLBWT4JnKCf/L+IG3y/e1MflhKByw=="], + "@oxlint/binding-linux-riscv64-gnu": ["@oxlint/binding-linux-riscv64-gnu@1.88.0", "", { "os": "linux", "cpu": "none" }, "sha512-iGx0uvFT54b/5DPJdEBCxYIrVB3v0uTy+JhRh3CyEp8/22BXDkG8rffkFwREdLsdj9mOrPbJYVOZw8ipcBuzjw=="], - "@oxlint/linux-x64-gnu": ["@oxlint/linux-x64-gnu@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-JHbkMUnibqaSMBvLHyqTL5cWxcGW+jw+Ppt2baLISpvo34a6fBR+PI7v/A92sEDWe0W1rPhypzCwA8mKpkQ3DA=="], + "@oxlint/binding-linux-riscv64-musl": ["@oxlint/binding-linux-riscv64-musl@1.88.0", "", { "os": "linux", "cpu": "none" }, "sha512-Wt47mKMWelVjRjuR7BCFxXkB0m79K1sTEbqMHRWciKUgo5iv7sWsF4RXSOyFYHD9zerNrkRZblnN273rhwOA1Q=="], - "@oxlint/linux-x64-musl": ["@oxlint/linux-x64-musl@0.9.10", "", { "os": "linux", "cpu": "x64" }, "sha512-aBBwN7bQzidwHwEXr7BAdVvMTLWstCy5gikerjLnGDeCSXX9r+o6+yUzTOqZvOo66E+XBgOJaVbY8rsL1MLE0g=="], + "@oxlint/binding-linux-s390x-gnu": ["@oxlint/binding-linux-s390x-gnu@1.88.0", "", { "os": "linux", "cpu": "s390x" }, "sha512-g3L12KCS4+1gtUt3RbJ4F+Yxx4LNmmZLEPfhd8rAHEJjJk2lAgNfnjGoP/phJyhG5WS6VbNYbJtadJelNfvTMA=="], - "@oxlint/win32-arm64": ["@oxlint/win32-arm64@0.9.10", "", { "os": "win32", "cpu": "arm64" }, "sha512-LXDnk7vKHT3IY6G1jq0O7+XMhtcHOYuxLGIx4KP+4xS6vKgBY+Bsq4xV3AtmtKlvnXkP5FxHpfLmcEtm5AWysA=="], + "@oxlint/binding-linux-x64-gnu": ["@oxlint/binding-linux-x64-gnu@1.88.0", "", { "os": "linux", "cpu": "x64" }, "sha512-og/XHVDOD9ZJgRiZkT9DgzQd4sr+JZW7e4l17Q/jVMZiIbeEd4uIu9iAoUbTF1gIvVZoRc4QDOxyVUvQGp4WHg=="], - "@oxlint/win32-x64": ["@oxlint/win32-x64@0.9.10", "", { "os": "win32", "cpu": "x64" }, "sha512-w5XRAV4bhgwenjjpGYZGglqzG9Wv/sI+cjQWJBQsvfDXsr2w4vOBXzt1j3/Z3EcSqf4KtkCa/IIuAhQyeShUbA=="], + "@oxlint/binding-linux-x64-musl": ["@oxlint/binding-linux-x64-musl@1.88.0", "", { "os": "linux", "cpu": "x64" }, "sha512-EmhBsp+xuKb6YbZNEMLBo80Xw71AZOIm18do8ni/GLX/Lw1XzNhVYpbxO1KasYtoAvrGtCOdCPULRlIE0bPbTQ=="], - "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], + "@oxlint/binding-openharmony-arm64": ["@oxlint/binding-openharmony-arm64@1.88.0", "", { "os": "none", "cpu": "arm64" }, "sha512-DBUcx/KwYdg1DAz+G01P/GFv512J04EsZadbHptx2FTpWT/MWRg21ZToNHt9pnsfQRBQ3et/g+vqzbvrdAVbuA=="], + + "@oxlint/binding-win32-arm64-msvc": ["@oxlint/binding-win32-arm64-msvc@1.88.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-xeVd0n4XG5HvynxfYvXi6uB+JvZbVZataowPS8cYpMbYg9mwE4sSyElFQd4LVJFifq8bRLDSR18XgEildmcXAg=="], + + "@oxlint/binding-win32-ia32-msvc": ["@oxlint/binding-win32-ia32-msvc@1.88.0", "", { "os": "win32", "cpu": "ia32" }, "sha512-MA6iOw//amleaz2mVMsZrA7NHlEexjTrhIxSMFCXQi6IUuQO+3Od00GZhr2iCYw6RFzMW36jkKK/WHBXMsoQAw=="], + + "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.88.0", "", { "os": "win32", "cpu": "x64" }, "sha512-3Sz6rVWe8Dy+ufsXurFN1GX2dX43F/lQMSLelK9gFjiba7nHvLlqlhR5cHlWVnCpSqUY1hN9pyCX9XToe6ve6g=="], "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.9", "", { "os": "android", "cpu": "arm" }, "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw=="], @@ -99,11 +117,7 @@ "@scure/bip39": ["@scure/bip39@1.6.0", "", { "dependencies": { "@noble/hashes": "~1.8.0", "@scure/base": "~1.2.5" } }, "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A=="], - "@sinclair/typebox": ["@sinclair/typebox@0.27.8", "", {}, "sha512-+Fj43pSMwJs4KRrH/938Uf+uAELIgVBmQzg/q1YG10djyfA3TnrU8N8XzqCh/okZdszqBQTZf96idMfE5lnwTA=="], - - "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], - - "@types/bun": ["@types/bun@1.2.18", "", { "dependencies": { "bun-types": "1.2.18" } }, "sha512-Xf6RaWVheyemaThV0kUfaAUvCNokFr+bH8Jxp+tTZfx7dAPA8z9ePnP9S9+Vspzuxxx9JRAXhnyccRj3GyCMdQ=="], + "@types/bun": ["@types/bun@1.4.2", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="], "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], @@ -111,46 +125,22 @@ "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], - "@types/node": ["@types/node@24.0.14", "", { "dependencies": { "undici-types": "~7.8.0" } }, "sha512-4zXMWD91vBLGRtHK3YbIoFMia+1nqEz72coM42C5ETjnNCa/heoj7NT1G67iAfOqMmcfhuCZ4uNpyz8EjlAejw=="], - - "@types/react": ["@types/react@19.1.8", "", { "dependencies": { "csstype": "^3.0.2" } }, "sha512-AwAfQ2Wa5bCx9WP8nZL2uMZWod7J7/JSplxbTmBQ5ms6QpqNYm672H0Vu9ZVKVngQ+ii4R/byguVEUZQyeg44g=="], - - "@vitest/expect": ["@vitest/expect@4.1.11", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" } }, "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw=="], - - "@vitest/mocker": ["@vitest/mocker@4.1.11", "", { "dependencies": { "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, "peerDependencies": { "msw": "^2.4.9", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ=="], + "@types/node": ["@types/node@24.19.2", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ=="], - "@vitest/pretty-format": ["@vitest/pretty-format@4.1.11", "", { "dependencies": { "tinyrainbow": "^3.1.0" } }, "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw=="], + "@vitest/mocker": ["@vitest/mocker@5.0.4", "", { "dependencies": { "@jridgewell/trace-mapping": "0.3.31", "@vitest/spy": "5.0.4", "estree-walker": "^3.0.3", "magic-string": "^1.4.3" }, "peerDependencies": { "msw": "^2.4.9 || ^3.0.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["msw", "vite"] }, "sha512-tqAlrYWce4iUxhr3ncNohejtCTOcHeE8XWrSNZY3OhPoDn01yeGv+gnaBy64ATp7o6pb03eIbBAjzmibpc9vIQ=="], - "@vitest/runner": ["@vitest/runner@4.1.11", "", { "dependencies": { "@vitest/utils": "4.1.11", "pathe": "^2.0.3" } }, "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw=="], + "@vitest/spy": ["@vitest/spy@5.0.4", "", {}, "sha512-MZKk/gSkm2q+ICobMxCpH1mA+cCAWm8WV7UhxlqGjq/sJ3AGc1BqFOs5CRVXxH78wQtme9q/NAAgBquj4AcyMw=="], - "@vitest/snapshot": ["@vitest/snapshot@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" } }, "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog=="], - - "@vitest/spy": ["@vitest/spy@4.1.11", "", {}, "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA=="], - - "@vitest/ui": ["@vitest/ui@1.6.1", "", { "dependencies": { "@vitest/utils": "1.6.1", "fast-glob": "^3.3.2", "fflate": "^0.8.1", "flatted": "^3.2.9", "pathe": "^1.1.1", "picocolors": "^1.0.0", "sirv": "^2.0.4" }, "peerDependencies": { "vitest": "1.6.1" } }, "sha512-xa57bCPGuzEFqGjPs3vVLyqareG8DX0uMkr5U/v5vLv5/ZUrBrPL7gzxzTJedEyZxFMfsozwTIbbYfEQVo3kgg=="], - - "@vitest/utils": ["@vitest/utils@1.6.1", "", { "dependencies": { "diff-sequences": "^29.6.3", "estree-walker": "^3.0.3", "loupe": "^2.3.7", "pretty-format": "^29.7.0" } }, "sha512-jOrrUvXM4Av9ZWiG1EajNto0u96kWAhJ1LmPmJhXXQx/32MecEKd10pOLYgS2BQx1TgkGhloPU1ArDW2vvaY6g=="], - - "abitype": ["abitype@1.0.8", "", { "peerDependencies": { "typescript": ">=5.0.4", "zod": "^3 >=3.22.0" }, "optionalPeers": ["typescript", "zod"] }, "sha512-ZeiI6h3GnW06uYDLx0etQtX/p8E24UaHHBj57RSjK7YBFe7iuVn07EDpOeP451D06sF27VOz9JJPlIKJmXgkEg=="], - - "ansi-styles": ["ansi-styles@5.2.0", "", {}, "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA=="], + "abitype": ["abitype@1.2.3", "", { "peerDependencies": { "typescript": ">=5.0.4", "zod": "^3.22.0 || ^4.0.0" }, "optionalPeers": ["typescript", "zod"] }, "sha512-Ofer5QUnuUdTFsBRwARMoWKOH1ND5ehwYhJ3OJ/BQO+StkwQjHw0XyVh4vDttzHB7QOFhPHa/o413PJ82gU/Tg=="], "assertion-error": ["assertion-error@2.0.1", "", {}, "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA=="], - "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], - - "bun-types": ["bun-types@1.2.18", "", { "dependencies": { "@types/node": "*" }, "peerDependencies": { "@types/react": "^19" } }, "sha512-04+Eha5NP7Z0A9YgDAzMk5PHR16ZuLVa83b26kH5+cp1qZW4F6FmAURngE7INf4tKOvCE69vYvDEwoNl1tGiWw=="], - - "chai": ["chai@6.2.2", "", {}, "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg=="], - - "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="], - "csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="], + "chai": ["chai@6.3.0", "", {}, "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg=="], "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], - "diff-sequences": ["diff-sequences@29.6.3", "", {}, "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q=="], - "es-module-lexer": ["es-module-lexer@2.3.2", "", {}, "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw=="], "estree-walker": ["estree-walker@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.0" } }, "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g=="], @@ -159,31 +149,11 @@ "expect-type": ["expect-type@1.4.0", "", {}, "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA=="], - "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], - - "fastq": ["fastq@1.19.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ=="], - "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - "fflate": ["fflate@0.8.2", "", {}, "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A=="], - - "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], - - "flatted": ["flatted@3.3.3", "", {}, "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg=="], - "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], - "get-func-name": ["get-func-name@2.0.2", "", {}, "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ=="], - - "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], - - "hono": ["hono@4.13.5", "", {}, "sha512-O6+/eCYRkzzzy0rPWwKLiGBR1nFuUPZynnwjxN1MBA62NNqbT0wQEzQyK2gSO5yDIDB336sXQleAhOHrzlYyKw=="], - - "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], - - "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], - - "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], + "hono": ["hono@4.13.13", "", {}, "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA=="], "isows": ["isows@1.0.7", "", { "peerDependencies": { "ws": "*" } }, "sha512-I1fSfDCZL5P0v33sVqeTDSpcstAg/N+wF5HS033mogOVIp4B+oHC7oOCsA3axAbBSGTJ8QubbNmnIRN/h8U7hg=="], @@ -211,104 +181,52 @@ "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.33.0", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="], - "loupe": ["loupe@2.3.7", "", { "dependencies": { "get-func-name": "^2.0.1" } }, "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA=="], - - "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], - - "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], - - "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], - - "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], + "magic-string": ["magic-string@1.4.3", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.6.0" } }, "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ=="], "nanoid": ["nanoid@3.3.19", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug=="], - "obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], + "obug": ["obug@3.0.0", "", {}, "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw=="], - "openapi-types": ["openapi-types@12.1.3", "", {}, "sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw=="], + "ox": ["ox@0.14.56", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.2.3", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-Feinlj+deWEam6RIwurRE+eHZ2N3hoUb3AAjQ10BmxRCYIymfqNkv0eZ+4ln4GkgDmSGLD2rGtTMqsFYSVDC6w=="], - "ox": ["ox@0.8.1", "", { "dependencies": { "@adraffy/ens-normalize": "^1.11.0", "@noble/ciphers": "^1.3.0", "@noble/curves": "^1.9.1", "@noble/hashes": "^1.8.0", "@scure/bip32": "^1.7.0", "@scure/bip39": "^1.6.0", "abitype": "^1.0.8", "eventemitter3": "5.0.1" }, "peerDependencies": { "typescript": ">=5.4.0" }, "optionalPeers": ["typescript"] }, "sha512-e+z5epnzV+Zuz91YYujecW8cF01mzmrUtWotJ0oEPym/G82uccs7q0WDHTYL3eiONbTUEvcZrptAKLgTBD3u2A=="], - - "oxlint": ["oxlint@0.9.10", "", { "optionalDependencies": { "@oxlint/darwin-arm64": "0.9.10", "@oxlint/darwin-x64": "0.9.10", "@oxlint/linux-arm64-gnu": "0.9.10", "@oxlint/linux-arm64-musl": "0.9.10", "@oxlint/linux-x64-gnu": "0.9.10", "@oxlint/linux-x64-musl": "0.9.10", "@oxlint/win32-arm64": "0.9.10", "@oxlint/win32-x64": "0.9.10" }, "bin": { "oxlint": "bin/oxlint", "oxc_language_server": "bin/oxc_language_server" } }, "sha512-bKiiFN7Hnoaist/rditTRBXz+GXKYuLd53/NB7Q6zHB/bifELJarSoRLkAUGElIJKl4PSr3lTh1g6zehh+rX0g=="], - - "pathe": ["pathe@1.1.2", "", {}, "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ=="], + "oxlint": ["oxlint@1.88.0", "", { "optionalDependencies": { "@oxlint/binding-android-arm-eabi": "1.88.0", "@oxlint/binding-android-arm64": "1.88.0", "@oxlint/binding-darwin-arm64": "1.88.0", "@oxlint/binding-darwin-x64": "1.88.0", "@oxlint/binding-freebsd-x64": "1.88.0", "@oxlint/binding-linux-arm-gnueabihf": "1.88.0", "@oxlint/binding-linux-arm-musleabihf": "1.88.0", "@oxlint/binding-linux-arm64-gnu": "1.88.0", "@oxlint/binding-linux-arm64-musl": "1.88.0", "@oxlint/binding-linux-ppc64-gnu": "1.88.0", "@oxlint/binding-linux-riscv64-gnu": "1.88.0", "@oxlint/binding-linux-riscv64-musl": "1.88.0", "@oxlint/binding-linux-s390x-gnu": "1.88.0", "@oxlint/binding-linux-x64-gnu": "1.88.0", "@oxlint/binding-linux-x64-musl": "1.88.0", "@oxlint/binding-openharmony-arm64": "1.88.0", "@oxlint/binding-win32-arm64-msvc": "1.88.0", "@oxlint/binding-win32-ia32-msvc": "1.88.0", "@oxlint/binding-win32-x64-msvc": "1.88.0" }, "peerDependencies": { "oxlint-tsgolint": ">=7.0.2003", "vite-plus": "*" }, "optionalPeers": ["oxlint-tsgolint", "vite-plus"], "bin": { "oxlint": "bin/oxlint" } }, "sha512-uIcFgw8BmqvFRGzH5+r7d2zJMEexwNSrEmM6WQNnGh3VkO0XYTEFoyxyNE6tjKMUib9Cue4XJA2DoWruO5D6aw=="], "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], - "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + "picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], "postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="], - "pretty-format": ["pretty-format@29.7.0", "", { "dependencies": { "@jest/schemas": "^29.6.3", "ansi-styles": "^5.0.0", "react-is": "^18.0.0" } }, "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ=="], - - "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], - - "react-is": ["react-is@18.3.1", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="], - - "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], - "rolldown": ["rolldown@1.2.9", "", { "dependencies": { "@oxc-project/types": "=0.150.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.9", "@rolldown/binding-android-arm64": "1.2.9", "@rolldown/binding-darwin-arm64": "1.2.9", "@rolldown/binding-darwin-x64": "1.2.9", "@rolldown/binding-freebsd-x64": "1.2.9", "@rolldown/binding-linux-arm-gnueabihf": "1.2.9", "@rolldown/binding-linux-arm64-gnu": "1.2.9", "@rolldown/binding-linux-arm64-musl": "1.2.9", "@rolldown/binding-linux-ppc64-gnu": "1.2.9", "@rolldown/binding-linux-s390x-gnu": "1.2.9", "@rolldown/binding-linux-x64-gnu": "1.2.9", "@rolldown/binding-linux-x64-musl": "1.2.9", "@rolldown/binding-openharmony-arm64": "1.2.9", "@rolldown/binding-win32-arm64-msvc": "1.2.9", "@rolldown/binding-win32-x64-msvc": "1.2.9" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg=="], - "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], - - "siginfo": ["siginfo@2.0.0", "", {}, "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g=="], + "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], - "sirv": ["sirv@2.0.4", "", { "dependencies": { "@polka/url": "^1.0.0-next.24", "mrmime": "^2.0.0", "totalist": "^3.0.0" } }, "sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ=="], + "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], - "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], - - "stackback": ["stackback@0.0.2", "", {}, "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw=="], - - "std-env": ["std-env@4.2.0", "", {}, "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw=="], - - "tinybench": ["tinybench@2.9.0", "", {}, "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg=="], + "tinybench": ["tinybench@6.2.2", "", {}, "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA=="], "tinyexec": ["tinyexec@1.3.1", "", {}, "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="], "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], - "tinyrainbow": ["tinyrainbow@3.1.1", "", {}, "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw=="], - - "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], - "totalist": ["totalist@3.0.1", "", {}, "sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ=="], + "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], - "typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="], - - "undici-types": ["undici-types@7.8.0", "", {}, "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw=="], - - "viem": ["viem@2.31.7", "", { "dependencies": { "@noble/curves": "1.9.2", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.0.8", "isows": "1.0.7", "ox": "0.8.1", "ws": "8.18.2" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-mpB8Hp6xK77E/b/yJmpAIQcxcOfpbrwWNItjnXaIA8lxZYt4JS433Pge2gg6Hp3PwyFtaUMh01j5L8EXnLTjQQ=="], + "viem": ["viem@2.57.5", "", { "dependencies": { "@noble/curves": "1.9.1", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.2.3", "isows": "1.0.7", "ox": "0.14.56", "ws": "8.21.0" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-BaUdS5lJJTxr6hJX17K0AjHbgUhsolsqH8CCbTq1WMunW/I/Siwc9VrTwccCcNPppgqa/gY4TqK8Zl8LLmlTlw=="], "vite": ["vite@8.3.0", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.6", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ=="], - "vitest": ["vitest@4.1.11", "", { "dependencies": { "@vitest/expect": "4.1.11", "@vitest/mocker": "4.1.11", "@vitest/pretty-format": "4.1.11", "@vitest/runner": "4.1.11", "@vitest/snapshot": "4.1.11", "@vitest/spy": "4.1.11", "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", "obug": "^2.1.1", "pathe": "^2.0.3", "picomatch": "^4.0.3", "std-env": "^4.0.0-rc.1", "tinybench": "^2.9.0", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tinyrainbow": "^3.1.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", "why-is-node-running": "^2.3.0" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "4.1.11", "@vitest/browser-preview": "4.1.11", "@vitest/browser-webdriverio": "4.1.11", "@vitest/coverage-istanbul": "4.1.11", "@vitest/coverage-v8": "4.1.11", "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw=="], + "vitest": ["vitest@5.0.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.4", "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.4.3", "obug": "^3.0.0", "picomatch": "^4.0.7", "std-env": "^4.3.0", "tinybench": "^6.2.2", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "why-is-node-running": "3.2.1" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.0.4", "@vitest/browser-preview": "5.0.4", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.0.4", "@vitest/coverage-v8": "5.0.4", "@vitest/ui": "5.0.4", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-z0WxZRV2Sg48wF0FSgMq3TFG8JS38/Qr96vZVZdX6+Em9raQTvnXQvdTFJe2m3rfyJnEHeHQ/snceIdi8D1pVg=="], - "why-is-node-running": ["why-is-node-running@2.3.0", "", { "dependencies": { "siginfo": "^2.0.0", "stackback": "0.0.2" }, "bin": { "why-is-node-running": "cli.js" } }, "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w=="], + "why-is-node-running": ["why-is-node-running@3.2.1", "", { "bin": { "why-is-node-running": "cli.js" } }, "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ=="], - "ws": ["ws@8.18.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ=="], + "ws": ["ws@8.21.0", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="], "zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], - "@vitest/expect/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/runner/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/runner/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "@vitest/snapshot/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "@vitest/snapshot/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], - - "bun-types/@types/node": ["@types/node@22.7.5", "", { "dependencies": { "undici-types": "~6.19.2" } }, "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ=="], - - "micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], - - "vite/picomatch": ["picomatch@4.0.7", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="], - - "vitest/@vitest/utils": ["@vitest/utils@4.1.11", "", { "dependencies": { "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ=="], - - "vitest/pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + "@scure/bip32/@noble/curves": ["@noble/curves@1.9.2", "", { "dependencies": { "@noble/hashes": "1.8.0" } }, "sha512-HxngEd2XUcg9xi20JkwlLCtYwfoFw4JGkuZpT+WlsPD4gB/cxkvTD8fSsoAnphGZhFdZYKeQIPCuFlWPm1uE0g=="], - "bun-types/@types/node/undici-types": ["undici-types@6.19.8", "", {}, "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw=="], + "tinyglobby/picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], } } diff --git a/dstack/kms/auth-eth-bun/index.ts b/dstack/kms/auth-eth-bun/index.ts index 3ea279327c..4cb06a2da1 100644 --- a/dstack/kms/auth-eth-bun/index.ts +++ b/dstack/kms/auth-eth-bun/index.ts @@ -275,7 +275,7 @@ app.get('/', async (c) => { appAuthImplementation: batch[2], // NOTE: for backward compatibility appImplementation: batch[2], }); - } catch (error) { + } catch { console.error('authorization backend health check failed'); return c.json({ status: 'error', @@ -294,7 +294,7 @@ app.post('/bootAuth/app', const bootInfo = c.req.valid('json'); const result = await ethereum.checkBoot(bootInfo, false); return c.json(result); - } catch (error) { + } catch { console.error('application authorization backend failed'); return c.json({ isAllowed: false, diff --git a/dstack/kms/auth-eth-bun/package.json b/dstack/kms/auth-eth-bun/package.json index 1957b4a1d6..aeae71abdd 100644 --- a/dstack/kms/auth-eth-bun/package.json +++ b/dstack/kms/auth-eth-bun/package.json @@ -15,19 +15,20 @@ "check": "bun run lint && bun run test:run" }, "dependencies": { - "hono": "4.13.5", - "@hono/zod-validator": "0.2.2", - "zod": "3.25.76", - "viem": "2.31.7" + "@hono/zod-validator": "0.9.1", + "hono": "4.13.13", + "viem": "2.57.5", + "zod": "3.25.76" }, "devDependencies": { - "@types/bun": "1.2.18", - "@types/node": "^24.0.14", - "@vitest/ui": "1.6.1", - "openapi-types": "12.1.3", - "oxlint": "0.9.10", - "typescript": "5.8.3", - "vitest": "4.1.11" + "@types/bun": "1.4.2", + "@types/node": "24.19.2", + "oxlint": "1.88.0", + "typescript": "5.9.3", + "vitest": "5.0.4" }, - "type": "module" + "type": "module", + "overrides": { + "source-map-js": "1.2.2" + } } From 4daab7b5ef769c8645162b99a1cfb5b50cd3c9db Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 13 Oct 2026 19:33:08 +0800 Subject: [PATCH 034/572] test(kms): pin the dstack-kms 0.6 bootAuth payload in auth-eth-bun dstack-kms 0.6 posts `dstack_verifier::PolicyBootInfo` to the webhook: unprefixed hex bytes plus `teeVariant` and `keyProviderInfo`, which the contract does not take. The existing tests only used 0x-prefixed payloads without those fields. The new tests post that exact shape to both routes and assert every policy field reaches isKmsAllowed/isAppAllowed padded and prefixed, an empty instanceId becomes the zero address, and a non-UpToDate TCB status is passed through for the contract to judge. Making the schema strict fails all four. Signed-off-by: Leechael Yim --- dstack/kms/auth-eth-bun/README.md | 8 +++ dstack/kms/auth-eth-bun/index.test.ts | 74 +++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) diff --git a/dstack/kms/auth-eth-bun/README.md b/dstack/kms/auth-eth-bun/README.md index 9fc755b6c7..7152a0e75f 100644 --- a/dstack/kms/auth-eth-bun/README.md +++ b/dstack/kms/auth-eth-bun/README.md @@ -112,6 +112,14 @@ this implementation is fully compatible with the original fastify + ethers versi - **comprehensive testing**: vitest test suite validates compatibility - **backward compatibility**: supports both minimal and full BootInfo formats +### dstack-kms 0.6 + +dstack-kms 0.6 posts `dstack_verifier::PolicyBootInfo`: bytes as unprefixed +hex, plus `teeVariant` and `keyProviderInfo`, which the contract does not take +and this backend drops. the KMS checks `appId`, `composeHash` and `instanceId` +widths itself before calling the webhook. the `dstack-kms 0.6 bootAuth payload` +tests pin this contract. + ### OpenAPI specification the complete API specification is available in `openapi.json` and includes: diff --git a/dstack/kms/auth-eth-bun/index.test.ts b/dstack/kms/auth-eth-bun/index.test.ts index fd97ffdb63..26826fde2a 100644 --- a/dstack/kms/auth-eth-bun/index.test.ts +++ b/dstack/kms/auth-eth-bun/index.test.ts @@ -565,3 +565,77 @@ describe('Ethereum finalized snapshot authorization', () => { expect(await recovered.json()).toMatchObject({ isAllowed: true, reason: 'recovered' }); }); }); + +// The body dstack-kms 0.6.x posts: `dstack_verifier::PolicyBootInfo`, camelCase, +// bytes as unprefixed lowercase hex, plus fields this backend does not read. +describe('dstack-kms 0.6 bootAuth payload', () => { + const kmsPayload = (overrides: Record = {}) => ({ + teeVariant: 'dstack-tdx', + mrAggregated: '11'.repeat(32), + osImageHash: 'ec43cb8c5e04b6bb6c53b33b16076a01d83d01f7f4b703f2f78a0d947d6247e6', + mrSystem: '22'.repeat(32), + appId: '33'.repeat(20), + composeHash: '44'.repeat(32), + instanceId: '55'.repeat(20), + deviceId: '66'.repeat(32), + keyProviderInfo: '7b226e616d65223a226b6d73227d'.repeat(40), + tcbStatus: 'UpToDate', + advisoryIds: ['INTEL-SA-00837'], + ...overrides, + }); + + const post = (path: string, body: unknown) => + appFetch(new Request(`http://localhost:3001${path}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + })); + + const bootInfoArg = (functionName: string) => + mockReadContract.mock.calls.map(([params]) => params) + .find((params) => params.functionName === functionName).args[0]; + + beforeEach(() => { + mockReadContract.mockImplementation((params) => { + if (params.functionName === 'isKmsAllowed' || params.functionName === 'isAppAllowed') { + return [true, '']; + } + if (params.functionName === 'gatewayAppId') return 'gateway-app'; + throw new Error(`unexpected function ${params.functionName}`); + }); + }); + + it.each([ + ['/bootAuth/kms', 'isKmsAllowed'], + ['/bootAuth/app', 'isAppAllowed'], + ])('%s forwards every policy field to %s', async (path, functionName) => { + const response = await post(path, kmsPayload()); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ isAllowed: true, reason: '', gatewayAppId: 'gateway-app' }); + expect(bootInfoArg(functionName)).toEqual({ + appId: `0x${'33'.repeat(20)}`, + composeHash: `0x${'44'.repeat(32)}`, + instanceId: `0x${'55'.repeat(20)}`, + deviceId: `0x${'66'.repeat(32)}`, + mrAggregated: `0x${'11'.repeat(32)}`, + mrSystem: `0x${'22'.repeat(32)}`, + osImageHash: '0xec43cb8c5e04b6bb6c53b33b16076a01d83d01f7f4b703f2f78a0d947d6247e6', + tcbStatus: 'UpToDate', + advisoryIds: ['INTEL-SA-00837'], + }); + }); + + it('maps the empty instance ID of an instance-less app to the zero address', async () => { + const response = await post('/bootAuth/app', kmsPayload({ instanceId: '' })); + + expect(await response.json()).toMatchObject({ isAllowed: true }); + expect(bootInfoArg('isAppAllowed').instanceId).toBe(`0x${'00'.repeat(20)}`); + }); + + it('passes a non-UpToDate TCB status through for the contract to judge', async () => { + await post('/bootAuth/kms', kmsPayload({ tcbStatus: 'OutOfDate' })); + + expect(bootInfoArg('isKmsAllowed').tcbStatus).toBe('OutOfDate'); + }); +}); From f2527b7a6c44f2e03c00201ff77681c7bcb8c812 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 13 Oct 2026 19:33:15 +0800 Subject: [PATCH 035/572] fix(kms): bound auth-eth-bun request bodies and set security headers The bootAuth routes buffered and parsed any body before validation rejected it: a 50 MB JSON body was accepted (200) and grew the process to ~187 MB RSS. Anyone who can reach the port could repeat that. Cap /bootAuth/* at 128 KiB and answer 413 with the usual invalid request body. A valid BootInfo stays far below that; the schema's own bounds peak around 32 KiB of advisoryIds. Add hono's secureHeaders so responses carry nosniff and SAMEORIGIN framing. Every response is JSON or a fixed text/plain 404, so there is no reflected content to exploit; the headers are defense in depth for a browser that reaches the port. The tests also pin the existing CSRF posture: a cross-origin text/plain or form POST is rejected with 400 before any contract read, and no CORS header is ever sent. There are no cookies or state-changing routes, so no token is needed. Signed-off-by: Leechael Yim --- dstack/kms/auth-eth-bun/index.test.ts | 51 +++++++++++++++++++++++++++ dstack/kms/auth-eth-bun/index.ts | 15 ++++++++ 2 files changed, 66 insertions(+) diff --git a/dstack/kms/auth-eth-bun/index.test.ts b/dstack/kms/auth-eth-bun/index.test.ts index 26826fde2a..16ac920db8 100644 --- a/dstack/kms/auth-eth-bun/index.test.ts +++ b/dstack/kms/auth-eth-bun/index.test.ts @@ -639,3 +639,54 @@ describe('dstack-kms 0.6 bootAuth payload', () => { expect(bootInfoArg('isKmsAllowed').tcbStatus).toBe('OutOfDate'); }); }); + +describe('request hardening', () => { + const bootInfo = { + mrAggregated: '11'.repeat(32), + osImageHash: '22'.repeat(32), + appId: '33'.repeat(20), + composeHash: '44'.repeat(32), + instanceId: '55'.repeat(20), + deviceId: '66'.repeat(32), + }; + + const post = (body: string, contentType: string) => + appFetch(new Request('http://localhost:3001/bootAuth/app', { + method: 'POST', + headers: { 'Content-Type': contentType, Origin: 'https://evil.example' }, + body, + })); + + it.each(['text/plain', 'application/x-www-form-urlencoded'])( + 'rejects a cross-origin simple request sent as %s without reading the contract', + async (contentType) => { + const response = await post(JSON.stringify(bootInfo), contentType); + + expect(response.status).toBe(400); + expect(response.headers.get('access-control-allow-origin')).toBeNull(); + expect(mockReadContract).not.toHaveBeenCalled(); + }, + ); + + it('rejects an oversized body before parsing it', async () => { + const response = await post( + JSON.stringify({ ...bootInfo, padding: 'a'.repeat(256 * 1024) }), + 'application/json', + ); + + expect(response.status).toBe(413); + expect(await response.json()).toEqual({ + isAllowed: false, + reason: 'invalid authorization request', + gatewayAppId: '', + }); + expect(mockReadContract).not.toHaveBeenCalled(); + }); + + it('marks JSON responses as not sniffable and not frameable', async () => { + const response = await appFetch(new Request('http://localhost:3001/no-such-route')); + + expect(response.headers.get('x-content-type-options')).toBe('nosniff'); + expect(response.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + }); +}); diff --git a/dstack/kms/auth-eth-bun/index.ts b/dstack/kms/auth-eth-bun/index.ts index 4cb06a2da1..7e6fff7b56 100644 --- a/dstack/kms/auth-eth-bun/index.ts +++ b/dstack/kms/auth-eth-bun/index.ts @@ -3,6 +3,8 @@ // SPDX-License-Identifier: Apache-2.0 import { Hono } from 'hono'; +import { bodyLimit } from 'hono/body-limit'; +import { secureHeaders } from 'hono/secure-headers'; import { zValidator } from '@hono/zod-validator'; import { z } from 'zod'; import { createPublicClient, http, type Address, type Hex } from 'viem'; @@ -256,6 +258,19 @@ const publicRpcEndpoint = (value: string): string => { const backendUnavailable = 'authorization backend unavailable'; const invalidRequest = { isAllowed: false, reason: 'invalid authorization request', gatewayAppId: '' }; +// The schema caps a valid BootInfo well under this (advisoryIds alone at +// 128 x 256 chars is 32 KiB); the limit stops an oversized body from being +// buffered and parsed before validation rejects it. +const MAX_BOOT_INFO_BYTES = 128 * 1024; + +// Every response is JSON for the KMS, never a page; the headers keep a browser +// that reaches this port from sniffing or framing one. +app.use('*', secureHeaders()); +app.use('/bootAuth/*', bodyLimit({ + maxSize: MAX_BOOT_INFO_BYTES, + onError: (c) => c.json(invalidRequest, 413), +})); + // health check and info endpoint app.get('/', async (c) => { try { From 3dc4b263613973b3ffc8e3dd32e8480bc04bdd78 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 13 Oct 2026 19:33:25 +0800 Subject: [PATCH 036/572] build(kms): add a Dockerfile for auth-eth-bun The deployed auth-api image was built by hand from a Dockerfile that cloned a fixed commit at build time, on oven/bun:1.2.18. Build from the checked-out directory instead, so the image carries exactly the source and lockfile under review. - base oven/bun:1.4.2-alpine, pinned by digest - production dependencies only, installed from the frozen lockfile with lifecycle scripts disabled - runs as the image's unprivileged `bun` user - PORT defaults to 8000, matching the KMS webhook default http://auth-api:8000; NODE_ENV=production - .dockerignore admits only package.json, bun.lock and index.ts Signed-off-by: Leechael Yim --- dstack/kms/auth-eth-bun/.dockerignore | 8 ++++++++ dstack/kms/auth-eth-bun/Dockerfile | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 dstack/kms/auth-eth-bun/.dockerignore create mode 100644 dstack/kms/auth-eth-bun/Dockerfile diff --git a/dstack/kms/auth-eth-bun/.dockerignore b/dstack/kms/auth-eth-bun/.dockerignore new file mode 100644 index 0000000000..ee1f9e2c2f --- /dev/null +++ b/dstack/kms/auth-eth-bun/.dockerignore @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +* +!package.json +!bun.lock +!index.ts diff --git a/dstack/kms/auth-eth-bun/Dockerfile b/dstack/kms/auth-eth-bun/Dockerfile new file mode 100644 index 0000000000..b39c94c757 --- /dev/null +++ b/dstack/kms/auth-eth-bun/Dockerfile @@ -0,0 +1,23 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +# Built from this directory, so the image carries exactly the checked-out +# source and lockfile rather than a clone fetched at build time. +FROM oven/bun:1.4.2-alpine@sha256:d888c0ae6c86d7866ff10c5aafdd9077b36aee6455b33dd270fb93c0dd5cef6f AS deps +WORKDIR /app +COPY package.json bun.lock ./ +RUN bun install --frozen-lockfile --production --ignore-scripts + +FROM oven/bun:1.4.2-alpine@sha256:d888c0ae6c86d7866ff10c5aafdd9077b36aee6455b33dd270fb93c0dd5cef6f +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY package.json index.ts ./ +ARG GIT_REV=unknown +LABEL org.opencontainers.image.revision="${GIT_REV}" +ENV NODE_ENV=production +# The KMS webhook default (`kms.toml`) is http://auth-api:8000. +ENV PORT=8000 +EXPOSE 8000 +USER bun +CMD ["bun", "index.ts"] From 72b8093f8637a405631e64ae55f8c0793d544af2 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Tue, 13 Oct 2026 19:33:25 +0800 Subject: [PATCH 037/572] ci: build and publish the auth-eth-bun image There was no CI build of the auth webhook image; deployments pinned a hand-pushed Docker Hub image. Add a workflow independent of the KMS release: - pull requests and pushes touching dstack/kms/auth-eth-bun run bun audit, lint and tests, then build the image without pushing - a `kms-auth-eth-bun-v` tag (or a manual run naming an existing one) publishes ghcr.io/dstack-tee/dstack-kms-auth-eth-bun:, checks anonymous pull access, attaches build provenance and writes the digest-pinned reference to the job summary Actions are pinned by commit, checkouts do not persist credentials and setup-bun runs without its cache, per zizmor. The README documents the image and how to deploy it by digest. Signed-off-by: Leechael Yim --- .github/workflows/kms-auth-eth-bun.yml | 175 +++++++++++++++++++++++++ dstack/kms/auth-eth-bun/README.md | 27 ++++ 2 files changed, 202 insertions(+) create mode 100644 .github/workflows/kms-auth-eth-bun.yml diff --git a/.github/workflows/kms-auth-eth-bun.yml b/.github/workflows/kms-auth-eth-bun.yml new file mode 100644 index 0000000000..41049365e2 --- /dev/null +++ b/.github/workflows/kms-auth-eth-bun.yml @@ -0,0 +1,175 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: KMS auth-eth-bun + +# The auth-eth-bun webhook ships on its own cadence, separate from the KMS +# image: a `kms-auth-eth-bun-v*` tag publishes +# ghcr.io/dstack-tee/dstack-kms-auth-eth-bun:. Pull requests and +# pushes that touch the backend run the checks and build the image without +# pushing it. +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the kms-auth-eth-bun-v prefix + required: true + type: string + push: + branches: [ next, 'release/**' ] + tags: + - 'kms-auth-eth-bun-v*' + paths: + - 'dstack/kms/auth-eth-bun/**' + - '.github/workflows/kms-auth-eth-bun.yml' + pull_request: + branches: [ next, 'release/**' ] + paths: + - 'dstack/kms/auth-eth-bun/**' + - '.github/workflows/kms-auth-eth-bun.yml' + +permissions: + contents: read + +env: + IMAGE: ghcr.io/dstack-tee/dstack-kms-auth-eth-bun + BACKEND_DIR: dstack/kms/auth-eth-bun + +jobs: + check: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('kms-auth-eth-bun-v{0}', inputs.version) || github.sha }} + persist-credentials: false + + - name: Set up Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # Keep in step with the base image in the Dockerfile. + bun-version: 1.4.2 + # A release build must not restore a cache an untrusted run wrote. + no-cache: true + + - name: Install dependencies + working-directory: ${{ env.BACKEND_DIR }} + run: bun install --frozen-lockfile + + - name: Audit dependencies + working-directory: ${{ env.BACKEND_DIR }} + run: bun audit --audit-level=moderate + + - name: Lint + working-directory: ${{ env.BACKEND_DIR }} + run: bun run lint + + - name: Test + working-directory: ${{ env.BACKEND_DIR }} + run: bun run test:run + + image: + needs: check + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + attestations: write + id-token: write + steps: + - name: Decide whether to publish + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + VERSION= + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/kms-auth-eth-bun-v*) VERSION=${GITHUB_REF#refs/tags/kms-auth-eth-bun-v} ;; + esac + fi + if [ -n "$VERSION" ]; then + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "version must be a valid Docker tag" >&2 + exit 1 + fi + echo "PUBLISH=1" >> "$GITHUB_ENV" + echo "IMAGE_REF=$IMAGE:$VERSION" >> "$GITHUB_ENV" + else + echo "PUBLISH=" >> "$GITHUB_ENV" + echo "IMAGE_REF=$IMAGE:check" >> "$GITHUB_ENV" + fi + + # Manual runs rebuild an existing release tag, not the selected branch. + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('kms-auth-eth-bun-v{0}', inputs.version) || github.sha }} + persist-credentials: false + + - name: Resolve the revision to build + run: echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + - name: Log in to GitHub Container Registry + if: env.PUBLISH == '1' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Build and push Docker image + id: build + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: ${{ env.BACKEND_DIR }} + platforms: linux/amd64 + push: ${{ env.PUBLISH == '1' }} + provenance: false + tags: ${{ env.IMAGE_REF }} + build-args: | + GIT_REV=${{ env.GIT_REV }} + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.revision=${{ env.GIT_REV }} + org.opencontainers.image.description=dstack KMS auth webhook backed by the DstackKms contract + + - name: Verify anonymous pull access + if: env.PUBLISH == '1' + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + run: | + token=$(curl -fsSL \ + "https://ghcr.io/token?scope=repository:dstack-tee/dstack-kms-auth-eth-bun:pull" \ + | jq -er .token) + curl -fsSL -o /dev/null \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json" \ + "https://ghcr.io/v2/dstack-tee/dstack-kms-auth-eth-bun/manifests/$IMAGE_DIGEST" + + - name: Generate artifact attestation + if: env.PUBLISH == '1' + uses: actions/attest-build-provenance@92c65d2898f1f53cfdc910b962cecff86e7f8fcc # v1 + with: + subject-name: ${{ env.IMAGE }} + subject-digest: ${{ steps.build.outputs.digest }} + push-to-registry: true + + - name: Summarize + if: env.PUBLISH == '1' + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + run: | + { + echo "**Image**: \`$IMAGE_REF\`" + echo + echo "**Pinned**: \`$IMAGE@$IMAGE_DIGEST\`" + echo + echo "**Revision**: \`$GIT_REV\`" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/dstack/kms/auth-eth-bun/README.md b/dstack/kms/auth-eth-bun/README.md index 7152a0e75f..38dbd599a9 100644 --- a/dstack/kms/auth-eth-bun/README.md +++ b/dstack/kms/auth-eth-bun/README.md @@ -66,6 +66,33 @@ bun run check - `ETH_CHAIN_ID` - reject every decision if the RPC reports a different chain ID (default: unset, no check) - `ETH_FINALITY_CONFIRMATIONS` - read policy this many blocks behind the RPC head (default: 0, the head) +## container image + +tagged releases are published by the `KMS auth-eth-bun` workflow +(`.github/workflows/kms-auth-eth-bun.yml`): pushing the tag +`kms-auth-eth-bun-v` builds this directory and publishes +`ghcr.io/dstack-tee/dstack-kms-auth-eth-bun:` with a build provenance +attestation. pull requests that touch this directory run the audit, lint and +tests and build the image without pushing it. + +the image listens on port 8000, which matches the KMS webhook default +`http://auth-api:8000`. deploy it by digest: + +```yaml +auth-api: + image: ghcr.io/dstack-tee/dstack-kms-auth-eth-bun:@sha256: + environment: + - ETH_RPC_URL=https://... + - KMS_CONTRACT_ADDR=0x... + - ETH_CHAIN_ID=8453 +``` + +to build it locally: + +```bash +docker build -t dstack-kms-auth-eth-bun . +``` + ## API endpoints ### GET / From 0ce3d0346e3cd6ef5b15067c72e21989ed922644 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 09:07:34 +0800 Subject: [PATCH 038/572] fix(ci): pin patched Vite release Signed-off-by: Leechael Yim --- dstack/kms/auth-eth-bun/bun.lock | 37 ++++++++++++++-------------- dstack/kms/auth-eth-bun/package.json | 1 + 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/dstack/kms/auth-eth-bun/bun.lock b/dstack/kms/auth-eth-bun/bun.lock index bdd9d761fd..384ccff361 100644 --- a/dstack/kms/auth-eth-bun/bun.lock +++ b/dstack/kms/auth-eth-bun/bun.lock @@ -15,6 +15,7 @@ "@types/node": "24.19.2", "oxlint": "1.88.0", "typescript": "5.9.3", + "vite": "8.3.3", "vitest": "5.0.4", }, }, @@ -39,7 +40,7 @@ "@noble/hashes": ["@noble/hashes@1.8.0", "", {}, "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A=="], - "@oxc-project/types": ["@oxc-project/types@0.150.0", "", {}, "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw=="], + "@oxc-project/types": ["@oxc-project/types@0.155.0", "", {}, "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q=="], "@oxlint/binding-android-arm-eabi": ["@oxlint/binding-android-arm-eabi@1.88.0", "", { "os": "android", "cpu": "arm" }, "sha512-k6Fgkf86ubfeH4GvqYsRolfuVAp0pfYVZvifSlXNHPdMaWUOfxUrmLEeDD7hF6U2oJuhsVxhSWq86/xCJ+9MmA=="], @@ -79,35 +80,35 @@ "@oxlint/binding-win32-x64-msvc": ["@oxlint/binding-win32-x64-msvc@1.88.0", "", { "os": "win32", "cpu": "x64" }, "sha512-3Sz6rVWe8Dy+ufsXurFN1GX2dX43F/lQMSLelK9gFjiba7nHvLlqlhR5cHlWVnCpSqUY1hN9pyCX9XToe6ve6g=="], - "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.9", "", { "os": "android", "cpu": "arm" }, "sha512-tNISae1QEf/vkb3xkRcjV5SEdzPE97We5IVaa2Z8jSszQPZ8U60B/YCYpw4QI7VidYsBtKavczXf+DyDs9WGxw=="], + "@rolldown/binding-android-arm-eabi": ["@rolldown/binding-android-arm-eabi@1.2.15", "", { "os": "android", "cpu": "arm" }, "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw=="], - "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.9", "", { "os": "android", "cpu": "arm64" }, "sha512-YC8YsI30o606GTZi0VyzYlsDKFP8W61i/QzayHDkLbNEz/IShqAmTa+hsJRj13xTHA0H+6fk4b2UmGn+Q/cMlg=="], + "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.2.15", "", { "os": "android", "cpu": "arm64" }, "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg=="], - "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.9", "", { "os": "darwin", "cpu": "arm64" }, "sha512-IwhlH3qK5urrY8hZiEgGkHKEFN901p/p2bjxCxJlr4GyNnF7wYpUvK+Y43uaRYuC4hpfjzbR3SJC3arX1jGvmw=="], + "@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.2.15", "", { "os": "darwin", "cpu": "arm64" }, "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA=="], - "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.9", "", { "os": "darwin", "cpu": "x64" }, "sha512-XxpJfVzFh+jilRxIXUqcfYAYcunIc/XEzIizsOL1fcJee5Sf7H3mH8WlLmfHfluz5amqR88QQo9izKtmMlavAw=="], + "@rolldown/binding-darwin-x64": ["@rolldown/binding-darwin-x64@1.2.15", "", { "os": "darwin", "cpu": "x64" }, "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A=="], - "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.9", "", { "os": "freebsd", "cpu": "x64" }, "sha512-kSfvhmgeWyfkbT3p/1s5vSgboogoah2zkm9fX2zjg2hHxSV7T4KhMWRUUaRk4OXNqoD3QAUeRqLcs1aZOK4U1g=="], + "@rolldown/binding-freebsd-x64": ["@rolldown/binding-freebsd-x64@1.2.15", "", { "os": "freebsd", "cpu": "x64" }, "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ=="], - "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.9", "", { "os": "linux", "cpu": "arm" }, "sha512-1RVzG17pxqbTfYLC352JlLt6kKLG+6Hr30n8DlIJqsnV5luUDd2Qdx9Ayw1Cabfyb1K9k0jXEZ7evxkRoT+uiw=="], + "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/binding-linux-arm-gnueabihf@1.2.15", "", { "os": "linux", "cpu": "arm" }, "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ=="], - "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.9", "", { "os": "linux", "cpu": "arm64" }, "sha512-BXqPvZ2drqVD+/Z8UpKwcs4Mp7grM+eGFku4CAEKrEtcbAsUpzREphK1sogCRZGreVPiMkiiBtw0n3TPteuqvw=="], + "@rolldown/binding-linux-arm64-gnu": ["@rolldown/binding-linux-arm64-gnu@1.2.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw=="], - "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.9", "", { "os": "linux", "cpu": "arm64" }, "sha512-11vWvo8YDwLzukt27J3aYDWU+gg2P7J+ZOmiJ0hkF5BXZDW7pVya7r40MXDy6ya0i9KamoENSVKIugvJNgFXIA=="], + "@rolldown/binding-linux-arm64-musl": ["@rolldown/binding-linux-arm64-musl@1.2.15", "", { "os": "linux", "cpu": "arm64" }, "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ=="], - "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.9", "", { "os": "linux", "cpu": "ppc64" }, "sha512-a1tijMkdwsIARtc0F39ApURROkf3NwqinI6TOiSSWCTR7dT96dffNvMUtDHnq64wKNTIZOIlzKrFvvFUznJiyw=="], + "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/binding-linux-ppc64-gnu@1.2.15", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw=="], - "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.9", "", { "os": "linux", "cpu": "s390x" }, "sha512-x6SQNdAvv4c3hWqTMaWuawzMX9myaCs/yEmlGsxJzkdClnHW7FbrjQuSiRDhuSYzEYoEMhsaJy9qHG/XNemJPQ=="], + "@rolldown/binding-linux-s390x-gnu": ["@rolldown/binding-linux-s390x-gnu@1.2.15", "", { "os": "linux", "cpu": "s390x" }, "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA=="], - "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.9", "", { "os": "linux", "cpu": "x64" }, "sha512-9s0AZ8BFK5/n7B/TBoa2yJE3gI3KURrbXcPBlsAsvjU4VeJKgE90y1YtNxyEUIcHPQkg6/yfF3qihUrcM/Kf0Q=="], + "@rolldown/binding-linux-x64-gnu": ["@rolldown/binding-linux-x64-gnu@1.2.15", "", { "os": "linux", "cpu": "x64" }, "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw=="], - "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.9", "", { "os": "linux", "cpu": "x64" }, "sha512-P7VWAmV+WdJluH7ovnRGoiv2i8To7GAZ+kGzfGup635cyL7SyYl3lSUaA3Gp5THf0n/Co5EyEqb2zbqq+nMOHQ=="], + "@rolldown/binding-linux-x64-musl": ["@rolldown/binding-linux-x64-musl@1.2.15", "", { "os": "linux", "cpu": "x64" }, "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ=="], - "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.9", "", { "os": "none", "cpu": "arm64" }, "sha512-1qixtsE4BK8h+yS3BfmZ09UhA7O/N4IACva6YBr7EBvCJraByTuRcgOTaiA62Tm0vey3UcKXLOaoGHtYmNGEVg=="], + "@rolldown/binding-openharmony-arm64": ["@rolldown/binding-openharmony-arm64@1.2.15", "", { "os": "none", "cpu": "arm64" }, "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w=="], - "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.9", "", { "os": "win32", "cpu": "arm64" }, "sha512-ok8IQjcEPs1AKZfuEUznVBrJw+gK4soq+bx8b1X2XoMqVClarc1q5JDmVtWXY1xfr6ZuHTAsPXHTgTrqKTZeww=="], + "@rolldown/binding-win32-arm64-msvc": ["@rolldown/binding-win32-arm64-msvc@1.2.15", "", { "os": "win32", "cpu": "arm64" }, "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg=="], - "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.9", "", { "os": "win32", "cpu": "x64" }, "sha512-Ip2mXoU0hM0boq3Rf+ekuT653OROSo6aSYcPT1VHE4q52KvyxgFkQgrgb/IEsxOuvQ2fZZbs8khJAyCEPM24/g=="], + "@rolldown/binding-win32-x64-msvc": ["@rolldown/binding-win32-x64-msvc@1.2.15", "", { "os": "win32", "cpu": "x64" }, "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ=="], "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.1", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="], @@ -197,7 +198,7 @@ "postcss": ["postcss@8.5.28", "", { "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A=="], - "rolldown": ["rolldown@1.2.9", "", { "dependencies": { "@oxc-project/types": "=0.150.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.9", "@rolldown/binding-android-arm64": "1.2.9", "@rolldown/binding-darwin-arm64": "1.2.9", "@rolldown/binding-darwin-x64": "1.2.9", "@rolldown/binding-freebsd-x64": "1.2.9", "@rolldown/binding-linux-arm-gnueabihf": "1.2.9", "@rolldown/binding-linux-arm64-gnu": "1.2.9", "@rolldown/binding-linux-arm64-musl": "1.2.9", "@rolldown/binding-linux-ppc64-gnu": "1.2.9", "@rolldown/binding-linux-s390x-gnu": "1.2.9", "@rolldown/binding-linux-x64-gnu": "1.2.9", "@rolldown/binding-linux-x64-musl": "1.2.9", "@rolldown/binding-openharmony-arm64": "1.2.9", "@rolldown/binding-win32-arm64-msvc": "1.2.9", "@rolldown/binding-win32-x64-msvc": "1.2.9" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg=="], + "rolldown": ["rolldown@1.2.15", "", { "dependencies": { "@oxc-project/types": "=0.155.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.15", "@rolldown/binding-android-arm64": "1.2.15", "@rolldown/binding-darwin-arm64": "1.2.15", "@rolldown/binding-darwin-x64": "1.2.15", "@rolldown/binding-freebsd-x64": "1.2.15", "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", "@rolldown/binding-linux-arm64-gnu": "1.2.15", "@rolldown/binding-linux-arm64-musl": "1.2.15", "@rolldown/binding-linux-ppc64-gnu": "1.2.15", "@rolldown/binding-linux-s390x-gnu": "1.2.15", "@rolldown/binding-linux-x64-gnu": "1.2.15", "@rolldown/binding-linux-x64-musl": "1.2.15", "@rolldown/binding-openharmony-arm64": "1.2.15", "@rolldown/binding-win32-arm64-msvc": "1.2.15", "@rolldown/binding-win32-x64-msvc": "1.2.15" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g=="], "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], @@ -215,7 +216,7 @@ "viem": ["viem@2.57.5", "", { "dependencies": { "@noble/curves": "1.9.1", "@noble/hashes": "1.8.0", "@scure/bip32": "1.7.0", "@scure/bip39": "1.6.0", "abitype": "1.2.3", "isows": "1.0.7", "ox": "0.14.56", "ws": "8.21.0" }, "peerDependencies": { "typescript": ">=5.0.4" }, "optionalPeers": ["typescript"] }, "sha512-BaUdS5lJJTxr6hJX17K0AjHbgUhsolsqH8CCbTq1WMunW/I/Siwc9VrTwccCcNPppgqa/gY4TqK8Zl8LLmlTlw=="], - "vite": ["vite@8.3.0", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.6", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-lhZBVvEHefgE+HQZC9O7EBJgCU/nVzFNl7vkS4RE0APtWLP02/8QVIkQtzBxPquh7lq5/78NHipTj7ODQ6XuyQ=="], + "vite": ["vite@8.3.3", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.11", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg=="], "vitest": ["vitest@5.0.4", "", { "dependencies": { "@types/chai": "^5.2.2", "@vitest/mocker": "5.0.4", "chai": "^6.3.0", "es-module-lexer": "^2.3.2", "expect-type": "^1.4.0", "magic-string": "^1.4.3", "obug": "^3.0.0", "picomatch": "^4.0.7", "std-env": "^4.3.0", "tinybench": "^6.2.2", "tinyexec": "^1.3.1", "tinyglobby": "^0.2.17", "why-is-node-running": "3.2.1" }, "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^22.0.0 || >=24.0.0", "@vitest/browser-playwright": "5.0.4", "@vitest/browser-preview": "5.0.4", "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", "@vitest/coverage-istanbul": "5.0.4", "@vitest/coverage-v8": "5.0.4", "@vitest/ui": "5.0.4", "happy-dom": "*", "jsdom": "*", "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["@edge-runtime/vm", "@opentelemetry/api", "@types/node", "@vitest/browser-playwright", "@vitest/browser-preview", "@vitest/browser-webdriverio", "@vitest/coverage-istanbul", "@vitest/coverage-v8", "@vitest/ui", "happy-dom", "jsdom"], "bin": { "vitest": "./vitest.mjs" } }, "sha512-z0WxZRV2Sg48wF0FSgMq3TFG8JS38/Qr96vZVZdX6+Em9raQTvnXQvdTFJe2m3rfyJnEHeHQ/snceIdi8D1pVg=="], diff --git a/dstack/kms/auth-eth-bun/package.json b/dstack/kms/auth-eth-bun/package.json index aeae71abdd..4f5260825f 100644 --- a/dstack/kms/auth-eth-bun/package.json +++ b/dstack/kms/auth-eth-bun/package.json @@ -25,6 +25,7 @@ "@types/node": "24.19.2", "oxlint": "1.88.0", "typescript": "5.9.3", + "vite": "8.3.3", "vitest": "5.0.4" }, "type": "module", From 4279903a7c2462739f4a604eb3ccba5871b0e531 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 21 Oct 2026 23:34:27 -0700 Subject: [PATCH 039/572] guest-agent: scope-gated external API The external listener answered anyone who could route to the CVM. It now requires a scope per route, granted by an Ed25519 JWT or by the host's `guest_agent_api` sys-config. Nothing is anonymous by default. This is an exposure control, not a confidentiality one: `public_logs`, `public_sysinfo` and `public_tcbinfo` still decide what may leave the TEE and are still measured. A scope can only narrow what they allow. - `dstack-api-auth::jwt`: a fixed-algorithm subset of JWT. The header is a constant, so `none`, HMAC and key-carrying headers cannot be expressed. Tokens are bound to the app id and capped at an hour. - The gateway's token is minted inside the CVM from the app root key and carried on `RegisterCvmRequest`, so registration needs no new distribution channel. - Paths are checked after percent-decoding and segment normalisation, since the router matches on that rather than on the raw string. - The dashboard is filtered block by block: identity, sysinfo, containers, logs and TCB each need their own scope. - The systemd watchdog probes the internal socket, which cannot depend on anonymous access being configured. Upgrade order matters: an old gateway sees 401s from a new guest and drops it from rotation after `failure_threshold` polls. See docs/guest-api-auth.md. Signed-off-by: Kevin Wang --- CHANGELOG.md | 1 + README.md | 1 + docs/guest-api-auth.md | 144 +++++++ docs/guest-api-v1.md | 5 + docs/security/cvm-boundaries.md | 11 +- docs/security/security-best-practices.md | 2 +- docs/usage.md | 2 +- dstack/Cargo.lock | 7 +- dstack/crates/api-auth/Cargo.toml | 3 + dstack/crates/api-auth/src/jwt.rs | 388 ++++++++++++++++++ dstack/crates/api-auth/src/lib.rs | 43 +- dstack/dstack-types/src/lib.rs | 34 ++ dstack/dstack-util/Cargo.toml | 1 + dstack/dstack-util/src/system_setup.rs | 55 +++ dstack/gateway/rpc/proto/gateway_rpc.proto | 10 + dstack/gateway/src/kv/import.rs | 1 + dstack/gateway/src/kv/mod.rs | 15 + dstack/gateway/src/main_service.rs | 18 + ...ateway__main_service__tests__config-2.snap | 3 +- ..._gateway__main_service__tests__config.snap | 1 + dstack/gateway/src/main_service/tests.rs | 13 + dstack/gateway/src/models.rs | 10 + dstack/gateway/src/proxy/health_check.rs | 39 +- dstack/gateway/src/proxy/port_policy.rs | 23 +- dstack/guest-agent/Cargo.toml | 3 +- dstack/guest-agent/src/api_auth.rs | 335 +++++++++++++++ dstack/guest-agent/src/config.rs | 13 +- dstack/guest-agent/src/http_routes.rs | 37 +- dstack/guest-agent/src/lib.rs | 1 + dstack/guest-agent/src/models.rs | 36 +- dstack/guest-agent/src/rpc_service.rs | 26 +- dstack/guest-agent/src/server.rs | 40 +- dstack/guest-agent/templates/dashboard.html | 18 +- dstack/vmm/src/app.rs | 5 + dstack/vmm/src/config.rs | 55 +++ dstack/vmm/vmm.toml | 12 + 36 files changed, 1337 insertions(+), 74 deletions(-) create mode 100644 docs/guest-api-auth.md create mode 100644 dstack/crates/api-auth/src/jwt.rs create mode 100644 dstack/guest-agent/src/api_auth.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f5c18bc87..3b2a077738 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - guest: a fresh CVM with a verity volume could take the volume for its data disk and try to LUKS-format it: volumes labelled their data partition `dstack-data`, the data disk's label. `dstack verity` now labels it `dstack-volume-data`, and the guest skips disks that carry a `dstack-volume` partition, so volumes built by older releases are safe too ### Changed +- guest-agent: the external listener (port 8090) is no longer anonymous. Every route needs a scope, granted by a signed Ed25519 JWT or by `[cvm.guest_agent_api].anonymous_scopes` in sys-config; the gateway gets its token minted inside the CVM from the app root key. `public_logs` / `public_sysinfo` / `public_tcbinfo` are unchanged and still decide what may leave the TEE. The dashboard is filtered block by block by scope. See `docs/guest-api-auth.md`. An old gateway sees 401s and drops new guests from rotation until it is upgraded - vmm: `qmp_socket` now defaults to `true`. Each CVM's QEMU exposes `qmp.sock` in its work dir, so the host can change disk options or compact a bloated `hda.img` (`blockdev-mirror`) without stopping the CVM. Applies to CVMs started after the change; set `qmp_socket = false` to opt out ## [0.6.1] - 2026-10-12 diff --git a/README.md b/README.md index 27b55eedf4..3c4bbfbfeb 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,7 @@ Apps communicate with the guest agent via HTTP over `/var/run/dstack.sock`. Use **Reference** - [Guest Agent API v1](./docs/guest-api-v1.md) - Key derivation, signature chains, and the versioned guest API - [Guest Agent API v0](./docs/guest-api-v0.md) - The frozen legacy surface, for clients that still speak the unversioned API +- [Guest Agent API access control](./docs/guest-api-auth.md) - Scopes, tokens, and anonymous access on port 8090 - [App Compose Format](./docs/normalized-app-compose.md) - Compose file specification - [Intel TDX Attestation](./docs/attestation-tdx.md) - Measurement and runtime-event verification - [Native TEE Interfaces](./docs/native-tee-interfaces.md) - Advanced compatibility with Linux TEE devices and configfs-tsm diff --git a/docs/guest-api-auth.md b/docs/guest-api-auth.md new file mode 100644 index 0000000000..2ec51495ba --- /dev/null +++ b/docs/guest-api-auth.md @@ -0,0 +1,144 @@ +# Guest Agent API access control + +The guest agent's external listener (port 8090) is reachable by anyone who can +route to the CVM. It refuses callers it cannot identify: every request names a +scope, and a scope is granted either by a signed token or by the host's +configuration. + +This is an exposure control, not a confidentiality one. It decides who may +*ask*. Whether the answer may leave the TEE is decided by the app's measured +`public_logs` / `public_sysinfo` / `public_tcbinfo` switches, and a token can +only narrow what those allow. See +[the two gates](#the-two-gates) below. + +## Scopes + +| Scope | Grants | +|---|---| +| `guest:version` | `Worker.Version` on either pRPC surface | +| `guest:health` | `Worker.Health` (`/prpc/v1`) | +| `guest:info` | `Worker.Info` on either surface, and the identity block on the dashboard | +| `guest:attest-app-key` | the frozen `Worker.GetAttestationForAppKey` | +| `guest:dashboard` | the dashboard page itself | +| `guest:containers` | the container table on the dashboard | +| `guest:logs` | `/logs/`, when the app sets `public_logs` | +| `guest:metrics` | `/metrics`, and the sysinfo block on the dashboard | + +`/prpc`, `/prpc/v0` and `/prpc/v1` are matched after percent-decoding and +segment normalisation, so `/prpc/Worker.Info`, `/prpc/v0/Info` and +`/%70rpc/Info` all need `guest:info`. There is no spelling that reaches a +handler with a weaker check. + +A route the vocabulary does not name needs no scope: nothing is mounted there, +and the router's 404 is the answer. + +## Default: nothing anonymous + +With no configuration, every scope above requires a token. The gateway still +works, because it is issued one internally; the dashboard, `/metrics` and the +log views stop answering to the public. + +The app's own SDKs are unaffected: they use the internal Unix socket, which is +unauthenticated and reachable only by the application. + +## Configuring anonymous access + +Anonymous access is a host decision, made in sys-config. The VMM writes it from +`[cvm.guest_agent_api]`: + +```toml +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health"] +``` + +The same block in the guest's `/dstack/.host-shared/.sys-config.json`: + +```json +{ + "guest_agent_api": { + "anonymous_scopes": ["guest:dashboard", "guest:version", "guest:health"] + } +} +``` + +Listing `guest:dashboard` without `guest:containers`, `guest:info`, `guest:logs` +or `guest:metrics` gives an anonymous visitor the page with every block hidden. +Scopes are independent: each one adds exactly its own block. + +An unknown name is a boot error rather than a permission that silently never +matches. + +## External issuers + +Other than its own token, the agent accepts tokens from issuers the host names: + +```toml +[[cvm.guest_agent_api.external_issuers]] +name = "ops" +public_keys = ["2f8d...c1"] # hex Ed25519 public keys, 32 bytes each +``` + +`name` is the exact `iss` claim a token must carry; `public_keys` is a list so a +key can be rotated by publishing the new one beside the old, waiting out the +longest token lifetime (one hour), then dropping the old one. + +Tokens must be Ed25519. `alg: none`, HMAC, and headers carrying key material +(`jku`, `x5u`, `jwk`) are not rejected by policy -- the header is a constant, +so they cannot be expressed. + +### Where the internal issuer comes from + +The agent and the gateway both hold the app root key inside the TEE. The token +the gateway presents is minted in the guest's own setup (`dstack-util`) and +carried on registration, so it can be bound to the app id and expire: + +1. Both derive the same Ed25519 key: + `derive_app_key(app_root_key, "dstack:guest-api:issuer:v1", Ed25519)`. +2. `dstack-util` signs a token with `iss = "dstack:guest-api:"`, + `aud = `, a 10-minute lifetime, and the `guest:health`, `guest:info` + scopes. +3. Registration carries it to the gateway, which presents it on the v1 `Health` + poll and on the lazy `Info` fetch that fills in a port policy the CVM did not + report. + +Nothing else gets a token: the gateway has no business on the dashboard or in +the logs. + +The host cannot mint one: the signing key is derived from the app root key, which +is released to the guest by KMS only after the boot measurement is verified. + +## The two gates + +Two independent checks decide what a caller sees, and both must pass: + +| Gate | Source | Measured | Answers | +|---|---|---|---| +| `public_logs`, `public_sysinfo`, `public_tcbinfo` | app-compose | yes | may this data leave the TEE at all? | +| scopes | sys-config | no | may this caller ask? | + +They combine with `&&`. A token cannot reveal logs the app kept private -- with +`public_logs = false` the route is not even mounted -- and an anonymous caller +cannot see a block it was not granted, however public the app made it. + +Scope configuration is deliberately unmeasured. Host-supplied sys-config is not +part of the attestation, so a host could grant a caller more than the operator +intended. That grants nothing beyond what anonymous 8090 access already granted +before this change: the data is still gated by the measured switches, which a +host cannot alter without changing the app id. + +## Compatibility + +A guest with this change answers 401 to an old gateway that presents no token. The +gateway counts that as unreachable and drops the instance after +`failure_threshold` consecutive polls, so a mixed cluster rebalances away from +new guests until the gateway is upgraded. + +During the rollout, either upgrade the gateway first, or leave the host open: + +```toml +[cvm.guest_agent_api] +anonymous_scopes = ["guest:version", "guest:health", "guest:info"] +``` + +`guest:info` is needed by gateways that did not report a port policy and fetch +it lazily. diff --git a/docs/guest-api-v1.md b/docs/guest-api-v1.md index c870ae00b3..652b8fff5e 100644 --- a/docs/guest-api-v1.md +++ b/docs/guest-api-v1.md @@ -458,6 +458,11 @@ The v1 `Worker` has three methods, served at `/prpc/v1`. Nothing here returns key material, and no caller chooses what gets signed or attested. +Every method also needs a scope, granted by a signed token or by the host's +configuration. With no configuration the listener answers only token holders; +see [Guest Agent API access control](./guest-api-auth.md) for the vocabulary and +for how the gateway authenticates its health polls. + ### There is no v1 AttestAppKey The frozen surface has `Worker.GetAttestationForAppKey`, which attests a key the diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index df369899b8..7a8a02ce8b 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -180,7 +180,16 @@ Full specification: [host_api.proto](../../dstack/host-api/proto/host_api.proto) ### HTTP-based Public Guest API Service -The dstack-guest-agent runs an HTTP server on port 8090 inside the CVM. This port is publicly accessible, allowing external clients to view basic CVM information. +The dstack-guest-agent runs an HTTP server on port 8090 inside the CVM. By +default it refuses callers it cannot identify: every route needs a scope, granted +by a signed token or by the host's `guest_agent_api` sys-config. Anonymous access +is an explicit host choice. [guest-api-auth.md](../guest-api-auth.md) covers the +scope vocabulary and the token issuers. + +Anonymous access is an exposure decision, not a confidentiality one. Whether the +data may leave the TEE at all is still decided by the app's measured +`public_logs` / `public_sysinfo` / `public_tcbinfo` switches, which a scope +cannot widen. Since dstack 0.6.0 the listener serves two API surfaces, selected by URL path alone: the frozen v0.5.11 `Worker` service at `/prpc` (equivalently diff --git a/docs/security/security-best-practices.md b/docs/security/security-best-practices.md index 8fd9d28f91..093657198a 100644 --- a/docs/security/security-best-practices.md +++ b/docs/security/security-best-practices.md @@ -146,7 +146,7 @@ Example app-compose.json: ## Don't expose unexpected ports -In dstack CVM, dstack-guest-agent listens on port 8090, allowing public access to basic CVM information. +In dstack CVM, dstack-guest-agent listens on port 8090. It is not anonymous by default; see [guest-api-auth.md](../guest-api-auth.md) for what the host can grant anonymously. In docker-compose.yaml, all declared ports will be exposed to the public internet. Do not expose unnecessary ports. diff --git a/docs/usage.md b/docs/usage.md index 85702f2c98..46e962acf2 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -17,7 +17,7 @@ Open the dstack-vmm webpage [http://localhost:9080](http://localhost:9080) (chan After the container is deployed, it should take some time to start the CVM and the containers. Time would vary depending on your workload. - **[Logs]**: Click this button to view the CVM logs and monitor container startup progress -- **[Dashboard]**: Once the container is running, click this button to view container information and logs. (Note: This button is only visible when dstack-gateway is enabled. If disabled, you'll need to add a port mapping to port 8090 to access the CVM dashboard) +- **[Dashboard]**: Once the container is running, click this button to view container information and logs. (Note: This button is only visible when dstack-gateway is enabled. If disabled, you'll need to add a port mapping to port 8090 and allow the dashboard scopes in `[cvm.guest_agent_api]`; see [Guest Agent API access control](./guest-api-auth.md))
Guest Agent Dashboard diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 31a97f3894..fcfd0385a2 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -1825,7 +1825,10 @@ dependencies = [ "anyhow", "base64 0.22.1", "bcrypt", + "ed25519-dalek", "rocket", + "serde", + "serde_json", "sha2 0.10.9", "subtle", ] @@ -2024,6 +2027,7 @@ dependencies = [ "clap", "cmd_lib", "default-net", + "dstack-api-auth", "dstack-attest", "dstack-build-info", "dstack-guest-agent-rpc", @@ -2035,6 +2039,7 @@ dependencies = [ "guest-api", "hex", "host-api", + "http-client", "k256", "libc", "listenfd", @@ -2046,7 +2051,6 @@ dependencies = [ "ra-tls", "rand 0.8.6", "rcgen 0.13.2", - "reqwest", "ring", "rinja", "rocket", @@ -2313,6 +2317,7 @@ dependencies = [ "cmd_lib", "curve25519-dalek", "dcap-qvl", + "dstack-api-auth", "dstack-attest", "dstack-gateway-rpc", "dstack-kms-rpc", diff --git a/dstack/crates/api-auth/Cargo.toml b/dstack/crates/api-auth/Cargo.toml index c3df2919d0..47967d4f94 100644 --- a/dstack/crates/api-auth/Cargo.toml +++ b/dstack/crates/api-auth/Cargo.toml @@ -13,6 +13,9 @@ license.workspace = true anyhow.workspace = true base64.workspace = true bcrypt.workspace = true +ed25519-dalek.workspace = true rocket.workspace = true +serde.workspace = true +serde_json = { workspace = true, features = ["std"] } sha2.workspace = true subtle.workspace = true diff --git a/dstack/crates/api-auth/src/jwt.rs b/dstack/crates/api-auth/src/jwt.rs new file mode 100644 index 0000000000..361e868c82 --- /dev/null +++ b/dstack/crates/api-auth/src/jwt.rs @@ -0,0 +1,388 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Ed25519 JWT tokens for the guest agent's external API. +//! +//! Deliberately a small subset: one algorithm, a fixed claim set, and no +//! key-discovery header. Everything a general-purpose JWT library would let a +//! caller negotiate is something an attacker would like to negotiate too -- +//! `none`, an HMAC verified with a public key as the secret, or a `jku`/`x5u`/ +//! `jwk` header naming a key the verifier never configured. Here those are not +//! rejected by policy but impossible to express. + +use std::collections::BTreeSet; + +use anyhow::{bail, Context, Result}; +use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _}; +use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey}; +use serde::{Deserialize, Serialize}; + +/// Longest lifetime a token may claim between `iat` and `exp`. +/// +/// There is no revocation list: a token is trusted until it expires, so the +/// lifetime is the whole of the exposure control. The gateway re-registers +/// every three minutes and mints a fresh token each time, so this costs it +/// nothing. +pub const MAX_TOKEN_LIFETIME_SECS: u64 = 3600; + +/// Tolerance for clock skew in either direction. +pub const CLOCK_LEEWAY_SECS: u64 = 30; + +/// The base64url header every token carries. +/// +/// A constant, not a serialized struct: a header this module writes is a +/// header it can also verify exactly. +const HEADER: &str = "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9"; + +/// The scope names the guest agent understands. +/// +/// A vocabulary rather than free-form strings, so a typo in `anonymous_scopes` +/// is a startup error instead of a permission that silently never matches. +pub mod scope { + /// `Worker.Version` on either pRPC surface. + pub const VERSION: &str = "guest:version"; + /// `Worker.Health` on the v1 surface. + pub const HEALTH: &str = "guest:health"; + /// `Worker.Info` on either pRPC surface. + pub const INFO: &str = "guest:info"; + /// `Worker.GetAttestationForAppKey` on the frozen surface. + pub const ATTEST_APP_KEY: &str = "guest:attest-app-key"; + /// The HTML dashboard itself. + pub const DASHBOARD: &str = "guest:dashboard"; + /// The container table on the dashboard. + pub const CONTAINERS: &str = "guest:containers"; + /// `/logs/`. + pub const LOGS: &str = "guest:logs"; + /// `/metrics`, and the sysinfo block on the dashboard. + pub const METRICS: &str = "guest:metrics"; + + /// Every name above, in the order a dashboard shows them. + pub const ALL: &[&str] = &[ + VERSION, + HEALTH, + INFO, + ATTEST_APP_KEY, + DASHBOARD, + CONTAINERS, + LOGS, + METRICS, + ]; + + pub fn is_known(name: &str) -> bool { + ALL.contains(&name) + } +} + +/// A set of granted scopes. +/// +/// Space-separated on the wire, because that is what RFC 8693 and every +/// OAuth-adjacent tool produces, and a collection here because the only +/// operation is membership. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ScopeSet(BTreeSet); + +impl ScopeSet { + /// Parse the space-separated `scope` claim. + pub fn parse(scope: &str) -> Self { + Self(scope.split_whitespace().map(str::to_owned).collect()) + } + + pub fn from_names(names: impl IntoIterator>) -> Self { + Self(names.into_iter().map(Into::into).collect()) + } + + pub fn contains(&self, scope: &str) -> bool { + self.0.contains(scope) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Everything in both sets. Used to add the anonymous baseline to a + /// caller's own grants. + pub fn union(&self, other: &Self) -> Self { + Self(self.0.union(&other.0).cloned().collect()) + } +} + +/// The claims this module issues and accepts. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Claims { + /// Who minted the token. + pub iss: String, + /// Which application the token is for, hex-encoded. + pub aud: String, + pub iat: u64, + pub exp: u64, + /// Space-separated [`scope`] names. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub scope: String, +} + +impl Claims { + pub fn scopes(&self) -> ScopeSet { + ScopeSet::parse(&self.scope) + } +} + +/// The domain the internal issuer key is derived under. +/// +/// Part of the wire contract between the agent (which derives the public half +/// to verify with) and the application (which derives the private half to +/// sign with). Changing it invalidates every token in flight, and a host and +/// guest on either side of the change would stop trusting each other, so it +/// never changes. +pub const INTERNAL_ISSUER_DOMAIN: &str = "dstack:guest-api:issuer:v1"; + +/// The `iss` an internally minted token carries. +/// +/// Bound to the app id so a token minted for one application cannot be +/// replayed against another: `aud` alone would already stop that, but naming +/// the application in the issuer too keeps the two checks independent. +pub fn internal_issuer(app_id_hex: &str) -> String { + format!("dstack:guest-api:{app_id_hex}") +} + +/// Mint a token. `signing_key` is the raw 32-byte Ed25519 seed. +pub fn sign(signing_key: &[u8; 32], claims: &Claims) -> Result { + let payload = serde_json::to_vec(claims).context("failed to serialize claims")?; + let signing_input = format!("{HEADER}.{}", URL_SAFE_NO_PAD.encode(payload)); + let signature = SigningKey::from_bytes(signing_key).sign(signing_input.as_bytes()); + Ok(format!( + "{signing_input}.{}", + URL_SAFE_NO_PAD.encode(signature.to_bytes()) + )) +} + +/// The public keys one issuer may sign with. +/// +/// A list so a key can be rotated without a flag day: publish the new key +/// alongside the old, wait out [`MAX_TOKEN_LIFETIME_SECS`], drop the old one. +#[derive(Clone, Debug)] +pub struct IssuerKeys { + /// The exact `iss` this issuer's tokens must carry. + pub name: String, + pub keys: Vec, +} + +/// Verifies tokens and reports what they grant. +#[derive(Clone)] +pub struct Verifier { + internal: Option, + external: Vec, +} + +impl Verifier { + /// `internal` is absent only when the app root key could not produce one; + /// an agent in that state still verifies external issuers. + pub fn new(internal: Option, external: Vec) -> Self { + Self { internal, external } + } + + pub fn is_empty(&self) -> bool { + self.internal.is_none() && self.external.is_empty() + } + + /// Verify `token` for the application whose id is `app_id_hex`. + /// + /// `now` is seconds since the UNIX epoch, passed in rather than read here + /// so the expiry rules can be tested. + pub fn verify(&self, token: &str, app_id_hex: &str, now: u64) -> Result { + let mut parts = token.split('.'); + let (Some(header), Some(encoded_payload), Some(signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + bail!("token is not a JWT"); + }; + if header != HEADER { + // Covers `alg: none`, HMAC, and any header carrying key material. + bail!("unsupported JWT header"); + } + let payload = URL_SAFE_NO_PAD + .decode(encoded_payload) + .context("payload is not base64url")?; + let claims: Claims = serde_json::from_slice(&payload).context("malformed claims")?; + if claims.aud != app_id_hex { + bail!("token was issued for a different application"); + } + if claims.exp < now.saturating_sub(CLOCK_LEEWAY_SECS) { + bail!("token has expired"); + } + if claims.exp.saturating_sub(claims.iat) > MAX_TOKEN_LIFETIME_SECS { + bail!("token lifetime exceeds {MAX_TOKEN_LIFETIME_SECS}s"); + } + if claims.iat > now + CLOCK_LEEWAY_SECS { + bail!("token was issued in the future"); + } + let signature = URL_SAFE_NO_PAD + .decode(signature) + .context("signature is not base64url")?; + let signature = + Signature::from_slice(&signature).context("signature has the wrong length")?; + let signing_input = format!("{header}.{encoded_payload}"); + + let keys = self.keys_for(&claims.iss, app_id_hex); + if keys.is_empty() { + bail!("unknown token issuer"); + } + if !keys.iter().any(|key| { + key.verify_strict(signing_input.as_bytes(), &signature) + .is_ok() + }) { + bail!("token signature does not verify"); + } + Ok(claims.scopes()) + } + + fn keys_for(&self, iss: &str, app_id_hex: &str) -> Vec<&VerifyingKey> { + if iss == internal_issuer(app_id_hex) { + return self.internal.iter().collect(); + } + self.external + .iter() + .find(|issuer| issuer.name == iss) + .map(|issuer| issuer.keys.iter().collect()) + .unwrap_or_default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const APP_ID: &str = "00112233445566778899aabbccddeeff00112233"; + + fn signing_key(seed: u8) -> [u8; 32] { + [seed; 32] + } + + fn mint(seed: u8, iss: &str, aud: &str, iat: u64, exp: u64, scope: &str) -> String { + sign( + &signing_key(seed), + &Claims { + iss: iss.to_owned(), + aud: aud.to_owned(), + iat, + exp, + scope: scope.to_owned(), + }, + ) + .unwrap() + } + + fn verifier(seed: u8) -> Verifier { + Verifier::new( + Some(SigningKey::from_bytes(&signing_key(seed)).verifying_key()), + vec![], + ) + } + + #[test] + fn round_trips_scopes() { + let token = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info guest:logs", + ); + let scopes = verifier(1).verify(&token, APP_ID, 1100).unwrap(); + assert!(scopes.contains(scope::INFO)); + assert!(scopes.contains(scope::LOGS)); + assert!(!scopes.contains(scope::METRICS)); + } + + #[test] + fn rejects_a_token_for_another_application() { + let token = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ); + let other = "ffeeddccbbaa99887766554433221100ffeeddcc"; + assert!(verifier(1).verify(&token, other, 1100).is_err()); + } + + #[test] + fn rejects_alg_none_and_foreign_signatures() { + for token in [ + "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJ4In0.".to_owned(), + mint( + 2, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ), + ] { + assert!(verifier(1).verify(&token, APP_ID, 1100).is_err()); + } + } + + #[test] + fn rejects_expired_overlong_and_future_tokens() { + let expired = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1100, + "guest:info", + ); + assert!(verifier(1).verify(&expired, APP_ID, 1200).is_err()); + + let overlong = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1000 + 7200, + "guest:info", + ); + assert!(verifier(1).verify(&overlong, APP_ID, 1100).is_err()); + + let future = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 5000, + 5300, + "guest:info", + ); + assert!(verifier(1).verify(&future, APP_ID, 1000).is_err()); + } + + #[test] + fn accepts_an_external_issuer_by_name() { + let verifier = Verifier::new( + None, + vec![IssuerKeys { + name: "ops".into(), + keys: vec![SigningKey::from_bytes(&signing_key(9)).verifying_key()], + }], + ); + let token = mint(9, "ops", APP_ID, 1000, 1300, "guest:containers"); + assert!(verifier + .verify(&token, APP_ID, 1100) + .unwrap() + .contains(scope::CONTAINERS)); + + // The same key under the internal issuer name is not an internal token. + let impostor = mint( + 9, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ); + assert!(verifier.verify(&impostor, APP_ID, 1100).is_err()); + } +} diff --git a/dstack/crates/api-auth/src/lib.rs b/dstack/crates/api-auth/src/lib.rs index c52f7bcb39..3932de22ad 100644 --- a/dstack/crates/api-auth/src/lib.rs +++ b/dstack/crates/api-auth/src/lib.rs @@ -5,8 +5,10 @@ //! Shared HTTP API authentication for dstack services. //! //! Supports bearer/shared-secret tokens, HTTP Basic credentials backed by an -//! Apache htpasswd file, and an optional GET-only query token for compatibility -//! with browser dashboard links. +//! Apache htpasswd file, an optional GET-only query token for compatibility +//! with browser dashboard links, and Ed25519 JWT scope grants (see [`jwt`]). + +pub mod jwt; use std::{collections::HashMap, path::Path, sync::Arc}; @@ -21,7 +23,9 @@ use rocket::{ use sha2::{Digest, Sha256}; use subtle::{Choice, ConstantTimeEq}; -const UNAUTH_URI: &str = "/__dstack_api_auth_unauthorized"; +/// Where a denied request is rewritten to, so every refusal is answered by one +/// responder regardless of which route it was headed for. +pub const UNAUTHORIZED_PATH: &str = "/__dstack_api_auth_unauthorized"; #[derive(Debug)] struct Htpasswd { @@ -252,11 +256,11 @@ impl Fairing for HttpAuthFairing { async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) { req.local_cache(|| RequestRealm(self.config.realm.clone())); - if req.uri().path() == UNAUTH_URI { + if req.uri().path() == UNAUTHORIZED_PATH { return; } if !self.authorized(req) { - if let Ok(uri) = Origin::parse_owned(UNAUTH_URI.to_owned()) { + if let Ok(uri) = Origin::parse_owned(UNAUTHORIZED_PATH.to_owned()) { req.set_uri(uri); } } else if self.config.allow_get_query_token { @@ -267,22 +271,37 @@ impl Fairing for HttpAuthFairing { } } -struct Unauthorized; +/// What a 401 asks the caller for. +/// +/// A Basic challenge tells a bearer-token client to do something it cannot do, +/// so a fairing denying on a token denies with `Bearer` instead. +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub enum Challenge { + #[default] + Basic, + Bearer, +} + +/// The responder every denied request lands on. +pub struct Unauthorized; impl<'r> Responder<'r, 'static> for Unauthorized { fn respond_to(self, req: &'r Request<'_>) -> rocket::response::Result<'static> { - let realm = &req.local_cache(|| RequestRealm("dstack API".into())).0; + let value = match req.local_cache(Challenge::default) { + Challenge::Basic => { + let realm = &req.local_cache(|| RequestRealm("dstack API".into())).0; + format!("Basic realm=\"{realm}\"") + } + Challenge::Bearer => "Bearer".to_owned(), + }; Response::build() .status(Status::Unauthorized) - .header(Header::new( - "WWW-Authenticate", - format!("Basic realm=\"{realm}\""), - )) + .header(Header::new("WWW-Authenticate", value)) .ok() } } -struct RequestRealm(String); +pub(crate) struct RequestRealm(String); #[rocket::get("/__dstack_api_auth_unauthorized")] fn unauth_get() -> Unauthorized { diff --git a/dstack/dstack-types/src/lib.rs b/dstack/dstack-types/src/lib.rs index a0ce437e21..ccf2ed02f8 100644 --- a/dstack/dstack-types/src/lib.rs +++ b/dstack/dstack-types/src/lib.rs @@ -1254,10 +1254,44 @@ pub struct SysConfig { /// string. #[serde(default, skip_serializing_if = "Option::is_none")] pub mr_config: Option, + /// Access control for the guest agent's external listener. Absent means + /// the code defaults: nothing anonymous, no external issuers. + /// + /// Host-supplied, and deliberately not measured: it decides who may *ask* + /// the agent, never whether data may leave the TEE. Confidentiality stays + /// with the measured `public_logs`/`public_sysinfo`/`public_tcbinfo` + /// switches in app-compose, which a token here cannot widen. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub guest_agent_api: Option, // JSON serialized VmConfig pub vm_config: String, } +#[derive(Deserialize, Serialize, Debug, Clone, Default, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct GuestAgentApiConfig { + /// Scopes granted to a caller that presents no token. + /// + /// Empty by default: an app that wants its dashboard on the internet has + /// to say so. This is an exposure choice, not a trust one -- the anonymous + /// caller is the same party a public 8090 already served. + #[serde(default)] + pub anonymous_scopes: Vec, + /// Issuers other than the app's own root key. + #[serde(default)] + pub external_issuers: Vec, +} + +#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct ExternalJwtIssuer { + /// The exact `iss` claim tokens from this issuer must carry. + pub name: String, + /// Hex-encoded Ed25519 public keys. More than one so a key can be rotated + /// without a flag day. + pub public_keys: Vec, +} + #[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)] #[serde(deny_unknown_fields)] pub struct GatewayClusterConfig { diff --git a/dstack/dstack-util/Cargo.toml b/dstack/dstack-util/Cargo.toml index a38f02f411..1f1f747a0e 100644 --- a/dstack/dstack-util/Cargo.toml +++ b/dstack/dstack-util/Cargo.toml @@ -47,6 +47,7 @@ cmd_lib.workspace = true toml.workspace = true dcap-qvl.workspace = true k256 = { workspace = true, features = ["ecdsa"] } +dstack-api-auth.workspace = true dstack-types.workspace = true rand.workspace = true regorus.workspace = true diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 114e8d37e2..bc2b227595 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -56,6 +56,7 @@ use crate::{ }; use cert_client::{validate_kms_rpc_cert, CertRequestClient}; use cmd_lib::run_fun as cmd; +use dstack_api_auth::jwt; use dstack_gateway_rpc::{ gateway_client::GatewayClient, PortAttrs as RpcPortAttrs, PortPolicy as RpcPortPolicy, RegisterCvmRequest, RegisterCvmResponse, WireGuardPeer, @@ -493,6 +494,50 @@ struct GatewayContext<'a> { keys: &'a AppKeys, } +/// Scopes the gateway needs on the guest agent's external listener: the v1 +/// `Health` poll, and the frozen `Info` call that fills in a port policy the +/// CVM did not report. Nothing else -- the gateway has no business on the +/// dashboard or in the logs. +const GATEWAY_AGENT_SCOPES: &[&str] = &[jwt::scope::HEALTH, jwt::scope::INFO]; + +/// Mint the token the gateway presents to this CVM's guest agent. +/// +/// Derived from the app root key, so it needs no distribution: the agent holds +/// the public half, this holds the private one, and the gateway only carries +/// the result. `None` when either side is not ready yet -- an app id that only +/// the boot attestation can supply, or an app root key that does not parse -- +/// in which case registration carries no token and the agent answers +/// anonymously, exactly as it did before this existed. +/// +/// One token for both calls the gateway makes, because both are the gateway +/// doing its own job: the v1 `Health` poll, and the frozen `Info` that fills in +/// a port policy the CVM did not report. Scopes are still a whitelist -- the +/// gateway gets nothing on the dashboard or in the logs. +fn gateway_agent_token(app_id: &[u8], app_root_key: &[u8]) -> Option { + let secret = ra_tls::api_v1::derive_app_key( + app_root_key, + jwt::INTERNAL_ISSUER_DOMAIN, + ra_tls::api_v1::KeyAlgorithm::Ed25519, + ) + .ok()?; + let app_id = hex::encode(app_id); + // Long enough to survive a few failed refreshes: a token that expired + // during a gateway outage would turn "we could not re-register" into "we + // are locked out until the outage ends". + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .ok()? + .as_secs(); + let claims = jwt::Claims { + iss: jwt::internal_issuer(&app_id), + aud: app_id, + iat: now, + exp: now + 600, + scope: GATEWAY_AGENT_SCOPES.join(" "), + }; + jwt::sign(&secret, &claims).ok() +} + impl<'a> GatewayContext<'a> { fn new(shared: &'a HostShared, keys: &'a AppKeys) -> Self { Self { shared, keys } @@ -532,6 +577,14 @@ impl<'a> GatewayContext<'a> { key_store: &GatewayKeyStore, gateway_app_id: &str, ) -> Result { + let agent_token = + gateway_agent_token(&self.shared.instance_info.app_id, &self.keys.k256_key); + if agent_token.is_none() { + // Not fatal: the CVM registers without one and the agent answers + // however the host configured it. Say so once per registration + // rather than failing a boot over it. + info!("no guest agent token available; registering without one"); + } let port_policy = RpcPortPolicy { ports: self .shared @@ -558,6 +611,7 @@ impl<'a> GatewayContext<'a> { client_public_key: key_store.wg_pk.clone(), port_policy: Some(port_policy.clone()), health_check, + agent_token: agent_token.clone(), }) .await .context("Failed to register CVM"); @@ -581,6 +635,7 @@ impl<'a> GatewayContext<'a> { client_public_key: key_store.wg_pk.clone(), port_policy: Some(port_policy), health_check, + agent_token, }) .await .context("Failed to register CVM") diff --git a/dstack/gateway/rpc/proto/gateway_rpc.proto b/dstack/gateway/rpc/proto/gateway_rpc.proto index 6a23982ca9..6a889673fb 100644 --- a/dstack/gateway/rpc/proto/gateway_rpc.proto +++ b/dstack/gateway/rpc/proto/gateway_rpc.proto @@ -31,6 +31,16 @@ message RegisterCvmRequest { // gateway falls back to fetching app-compose via Info()) from "reported // empty" (new CVM with no special port behaviour). optional PortPolicy port_policy = 2; + // Ed25519 JWT the CVM minted for its own guest agent, so the gateway can + // call the agent's external listener now that it refuses anonymous callers + // by default. Bound to this CVM's app id and expiring within the hour; the + // CVM re-registers every three minutes, so a stale copy never outlives its + // usefulness. + // + // Empty from a CVM that predates the field, or one whose app identity is + // not known yet. The gateway then calls without a token and gets whatever + // the host left open -- possibly nothing, which is the intended default. + optional string agent_token = 4; } // PortPolicy carries the gateway-relevant per-port configuration declared by diff --git a/dstack/gateway/src/kv/import.rs b/dstack/gateway/src/kv/import.rs index 5937153796..f18d62bc25 100644 --- a/dstack/gateway/src/kv/import.rs +++ b/dstack/gateway/src/kv/import.rs @@ -282,6 +282,7 @@ mod tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, } } diff --git a/dstack/gateway/src/kv/mod.rs b/dstack/gateway/src/kv/mod.rs index 81486a8590..5238d36765 100644 --- a/dstack/gateway/src/kv/mod.rs +++ b/dstack/gateway/src/kv/mod.rs @@ -130,6 +130,16 @@ pub struct InstanceRecord { /// a rollback and forward again. #[serde(default)] pub health_check: Option, + /// Token this CVM minted for the gateway, so the agent's external listener + /// can answer an operator-run caller. `None` for a CVM that predates the + /// field, or one whose app id is not yet known. + /// + /// Per-instance rather than per-app: the token is bound to the instance's + /// app id and expires within the hour, and the CVM re-registers every + /// three minutes anyway. `Option` for the same reason as `health_check`: + /// a pre-field record has to read as "not known", not "empty token". + #[serde(default)] + pub agent_token: Option, } /// What an operator has said about an instance's ports, under @@ -193,6 +203,7 @@ impl From<&InstanceInfo> for InstanceRecord { // `Health` is this node's own observation, and a shared one would // outlive the instance that earned it. health_check: Some(info.health_check()), + agent_token: info.agent_token.clone(), } } } @@ -2729,6 +2740,7 @@ mod value_encoding_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("sync should succeed"); @@ -3003,6 +3015,7 @@ mod corruption_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("seed"); @@ -3473,6 +3486,7 @@ mod corruption_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("sync should succeed"); @@ -3659,6 +3673,7 @@ mod tombstone_gc_tests { port_policy: None, port_policy_hash: String::new(), health_check: None, + agent_token: None, }, ) .expect("seed"); diff --git a/dstack/gateway/src/main_service.rs b/dstack/gateway/src/main_service.rs index 70cd0cec26..5c77116c70 100644 --- a/dstack/gateway/src/main_service.rs +++ b/dstack/gateway/src/main_service.rs @@ -1053,6 +1053,7 @@ fn instance_info_from_record( // cached selection on a record that never claimed the app opted out. health: data.health_check.unwrap_or(known_gated).into(), connections: Default::default(), + agent_token: data.agent_token, }; (info, unreadable) } @@ -1968,6 +1969,7 @@ impl ProxyState { let ReportedCapabilities { port_policy, health_check, + agent_token, } = reported; if id.is_empty() { bail!("instance_id is empty (no_instance_id is set?)"); @@ -2064,6 +2066,11 @@ impl ProxyState { if port_policy.is_some() { existing.port_policy = port_policy.clone(); } + // Same rule: a registration that supplies no token must not erase + // one, and one that does replaces it wholesale. + if agent_token.is_some() { + existing.agent_token = agent_token.clone(); + } existing.clone() }); if let Some(existing) = edited { @@ -2115,6 +2122,7 @@ impl ProxyState { ready: None, health: health_check.unwrap_or(false).into(), connections: Default::default(), + agent_token, }, }; self.add_instance(host_info.clone()); @@ -2126,6 +2134,15 @@ impl ProxyState { self.state.instances.get(instance_id).map(|i| i.ip) } + /// The bearer token an instance's guest agent external listener accepts, + /// if the CVM supplied one at registration. + pub(crate) fn instance_agent_token(&self, instance_id: &str) -> Option { + self.state + .instances + .get(instance_id) + .and_then(|info| info.agent_token.clone()) + } + /// Lookup the effective port_policy for an instance: admin override wins, /// otherwise fall back to the instance-reported policy. `None` means /// neither is set — caller fails closed and may schedule a lazy fetch. @@ -2819,6 +2836,7 @@ impl GatewayRpc for RpcHandler { port_policy, // A real CVM always states its intent, either way. health_check: Some(request.health_check), + agent_token: request.agent_token.filter(|token| !token.is_empty()), }, ) .await diff --git a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap index f126f03ee8..eebb0353e5 100644 --- a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap +++ b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config-2.snap @@ -1,6 +1,6 @@ --- source: gateway/src/main_service/tests.rs -assertion_line: 71 +assertion_line: 86 expression: info1 --- InstanceInfo { @@ -20,5 +20,6 @@ InstanceInfo { gated: false, state: Ungated, }, + agent_token: None, connections: 0, } diff --git a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap index 221032272e..9aaa3dcd4e 100644 --- a/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap +++ b/dstack/gateway/src/main_service/snapshots/dstack_gateway__main_service__tests__config.snap @@ -20,5 +20,6 @@ InstanceInfo { gated: false, state: Ungated, }, + agent_token: None, connections: 0, } diff --git a/dstack/gateway/src/main_service/tests.rs b/dstack/gateway/src/main_service/tests.rs index d2f6efc5e8..e33fd0749c 100644 --- a/dstack/gateway/src/main_service/tests.rs +++ b/dstack/gateway/src/main_service/tests.rs @@ -535,6 +535,7 @@ fn register_instances(proxy: &mut ProxyState, app: &str, count: usize, health_ch ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(health_check), + agent_token: None, }, ) .unwrap(); @@ -556,6 +557,7 @@ fn observe(proxy: &mut ProxyState, instance_id: &str, state: HealthState) { id: info.id, ip: info.ip, public_key: info.public_key, + agent_token: info.agent_token, }, state, ); @@ -827,6 +829,7 @@ async fn a_published_record_carries_the_declaration_and_not_the_gate() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(true), + agent_token: None, }, ) .unwrap(); @@ -1051,6 +1054,7 @@ async fn both_operator_overrides_survive_the_ip_rebuild_path() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(false), + agent_token: None, }, ) .unwrap(); @@ -1189,6 +1193,7 @@ async fn a_capability_change_arriving_through_kv_invalidates_the_cached_selectio port_policy: existing.port_policy.clone(), port_policy_hash: existing.port_policy_hash.clone(), health_check: Some(true), + agent_token: None, } }; state @@ -1529,6 +1534,7 @@ fn re_register( ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(health_check), + agent_token: None, }, ) .unwrap(); @@ -1715,6 +1721,7 @@ async fn a_reboot_arriving_through_kv_resets_health_on_this_node_too() { port_policy: existing.port_policy.clone(), port_policy_hash: existing.port_policy_hash.clone(), health_check: Some(true), + agent_token: None, } }; state @@ -1761,6 +1768,7 @@ async fn a_record_written_without_the_capability_field_does_not_clear_it() { port_policy_hash: existing.port_policy_hash.clone(), // The older build does not know the field exists. health_check: None, + agent_token: None, } }; state @@ -1852,6 +1860,7 @@ async fn a_verdict_polled_before_a_reboot_is_not_applied_after_it() { id: "race-app-0".to_string(), ip: proxy.state.instances["race-app-0"].ip, public_key: proxy.state.instances["race-app-0"].public_key.clone(), + agent_token: None, }; // The CVM reboots and re-registers mid-round. @@ -1884,6 +1893,7 @@ async fn a_verdict_polled_from_a_stale_address_is_not_applied() { id: "addr-app-0".to_string(), ip: "10.99.99.99".parse().unwrap(), public_key: proxy.state.instances["addr-app-0"].public_key.clone(), + agent_token: None, }; observe_from(&mut proxy, &polled, HealthState::Healthy); @@ -1913,6 +1923,7 @@ async fn a_registration_that_reports_no_capability_leaves_it_alone() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: None, + agent_token: None, }, ) .unwrap(); @@ -1979,6 +1990,7 @@ async fn disabling_polling_keeps_both_old_and_new_instances_eligible() { ReportedCapabilities { port_policy: Some(policy(false, &[])), health_check: Some(has_endpoint), + agent_token: None, }, ) .unwrap(); @@ -2135,6 +2147,7 @@ fn sync_from_peer_at( port_policy: None, port_policy_hash: String::new(), health_check: Some(false), + agent_token: None, }, ) .unwrap(); diff --git a/dstack/gateway/src/models.rs b/dstack/gateway/src/models.rs index b41a7ba93a..abaa9663a8 100644 --- a/dstack/gateway/src/models.rs +++ b/dstack/gateway/src/models.rs @@ -72,6 +72,10 @@ pub struct InstanceInfo { /// [`Health`]'s own state is not, so there is no way to build one whose /// declaration and verdict disagree. pub(crate) health: Health, + /// Bearer token for the instance's guest agent external listener, minted + /// by the CVM at registration. Absent for a legacy CVM, which has no such + /// listener to authenticate against. + pub agent_token: Option, pub connections: Arc, } @@ -93,6 +97,11 @@ pub struct ReportedCapabilities { /// instance already declared in place. `Some(false)` is an app that did not /// opt in, or an image that predates the field; the gateway polls neither. pub health_check: Option, + /// Bearer token for the agent's external listener. `None` leaves whatever + /// the instance already carried in place, so a registration without one + /// (a legacy CVM, or one that could not mint one yet) does not erase a + /// token a previous registration supplied. + pub agent_token: Option, } impl From> for ReportedCapabilities { @@ -102,6 +111,7 @@ impl From> for ReportedCapabilities { Self { port_policy, health_check: None, + agent_token: None, } } } diff --git a/dstack/gateway/src/proxy/health_check.rs b/dstack/gateway/src/proxy/health_check.rs index c0ea83c7b3..754e3c50f8 100644 --- a/dstack/gateway/src/proxy/health_check.rs +++ b/dstack/gateway/src/proxy/health_check.rs @@ -95,6 +95,10 @@ pub(crate) struct Target { pub id: String, pub ip: Ipv4Addr, pub public_key: String, + /// The token the CVM supplied at registration. `None` for a CVM that + /// predates the field; the poll then carries no credentials and gets + /// whatever the host left anonymous. + pub agent_token: Option, } /// Start the polling loop. Called once at startup. @@ -161,7 +165,7 @@ async fn poll_round( let timeout = config.timeout; let mut polls = futures::stream::iter(targets) .map(|target| async move { - let result = poll_instance(target.ip, agent_port, timeout).await; + let result = poll_instance(&target, agent_port, timeout).await; (target, result) }) .buffer_unordered(config.concurrency.max(1)); @@ -243,6 +247,7 @@ pub(crate) fn select_targets(state: &Proxy) -> Vec { id: instance.id.clone(), ip: instance.ip, public_key: instance.public_key.clone(), + agent_token: instance.agent_token.clone(), }) .collect() } @@ -300,8 +305,8 @@ fn apply_hysteresis( /// A failure to get an answer comes back as [`PollResult::Unreachable`] rather /// than as a verdict; [`apply_hysteresis`] decides when enough of them in a row /// amount to one. -async fn poll_instance(ip: Ipv4Addr, agent_port: u16, timeout: Duration) -> PollResult { - let client = WorkerV1Client::new(prober_transport(ip, agent_port)); +async fn poll_instance(target: &Target, agent_port: u16, timeout: Duration) -> PollResult { + let client = WorkerV1Client::new(prober_transport(target, agent_port)); let response = match tokio::time::timeout(timeout, client.health(Default::default())).await { Err(_) => { return PollResult::unreachable(format!("health poll timed out after {timeout:?}")) @@ -331,7 +336,7 @@ async fn poll_instance(ip: Ipv4Addr, agent_port: u16, timeout: Duration) -> Poll /// one. A probe riding a pooled connection would report healthy for an instance /// no real request can reach. Only the connection is unshared; the client /// itself is process-wide. See `http_client::ConnectionReuse`. -fn prober_transport(ip: Ipv4Addr, agent_port: u16) -> http_client::prpc::PrpcClient { +fn prober_transport(target: &Target, agent_port: u16) -> http_client::prpc::PrpcClient { // `/prpc/v1`, not `/prpc`: `Health` is a v1 `Worker` method. // // No released agent is affected. `Health` never shipped in a release, and a @@ -345,8 +350,12 @@ fn prober_transport(ip: Ipv4Addr, agent_port: u16) -> http_client::prpc::PrpcCli // Instance-id routing keeps working and a restart on a current build fixes // it. Not worth a compatibility probe on every poll for a build nobody was // asked to run. - let url = format!("http://{ip}:{agent_port}/prpc/v1"); - super::guest_agent_client(url, ConnectionReuse::Fresh) + let url = format!("http://{}:{agent_port}/prpc/v1", target.ip); + let client = super::guest_agent_client(url, ConnectionReuse::Fresh); + match &target.agent_token { + Some(token) => client.with_bearer_token(token), + None => client, + } } /// Longest reason kept from an agent's answer. @@ -512,7 +521,7 @@ mod tests { let (tx, rx) = tokio::sync::oneshot::channel(); let port = fake_agent_capturing(Some(br#"{"healthy":true}"#.to_vec()), Some(tx)).await; - let _ = poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_secs(5)).await; + let _ = poll_instance(&local_target(), port, Duration::from_secs(5)).await; let request_line = rx.await.expect("the poller sent no request"); assert!( @@ -523,7 +532,7 @@ mod tests { async fn poll_fake(answer: Option>) -> PollResult { let port = fake_agent(answer).await; - poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_secs(5)).await + poll_instance(&local_target(), port, Duration::from_secs(5)).await } #[tokio::test] @@ -553,7 +562,7 @@ mod tests { #[tokio::test] async fn an_agent_that_accepts_and_then_says_nothing_times_out() { let port = fake_agent(None).await; - let result = poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_millis(100)).await; + let result = poll_instance(&local_target(), port, Duration::from_millis(100)).await; let PollResult::Unreachable(reason) = result else { panic!("a silent agent must not produce a verdict, got {result:?}"); }; @@ -569,7 +578,7 @@ mod tests { .expect("bind"); listener.local_addr().expect("addr").port() }; - let result = poll_instance(Ipv4Addr::LOCALHOST, port, Duration::from_secs(5)).await; + let result = poll_instance(&local_target(), port, Duration::from_secs(5)).await; assert!( matches!(result, PollResult::Unreachable(_)), "a refused connection must not read as an agent saying no, got {result:?}" @@ -635,7 +644,7 @@ mod tests { #[test] fn the_probe_does_not_ride_a_connection_someone_else_opened() { assert_eq!( - prober_transport(Ipv4Addr::new(10, 0, 0, 2), 8090).connection_reuse(), + prober_transport(&target(), 8090).connection_reuse(), ConnectionReuse::Fresh, "a probe over a pooled connection cannot see an agent that refuses new ones" ); @@ -656,6 +665,14 @@ mod tests { id: "inst-1".to_string(), ip: Ipv4Addr::new(10, 0, 0, 2), public_key: "key-1".to_string(), + agent_token: None, + } + } + + fn local_target() -> Target { + Target { + ip: Ipv4Addr::LOCALHOST, + ..target() } } diff --git a/dstack/gateway/src/proxy/port_policy.rs b/dstack/gateway/src/proxy/port_policy.rs index bc8ce05d1a..a8573afdbe 100644 --- a/dstack/gateway/src/proxy/port_policy.rs +++ b/dstack/gateway/src/proxy/port_policy.rs @@ -217,28 +217,41 @@ async fn fetch_with_retry(state: &Proxy, instance_id: &str) { } async fn fetch_and_store(state: &Proxy, instance_id: &str) -> Result<(), FetchError> { - let (ip, agent_port) = { + let (ip, agent_port, agent_token) = { let guard = state.lock(); let ip = guard .instance_ip(instance_id) // Instance was recycled — never coming back under this id. .ok_or_else(|| FetchError::Permanent(anyhow::anyhow!("unknown instance")))?; - (ip, guard.config.proxy.agent_port) + ( + ip, + guard.config.proxy.agent_port, + guard.instance_agent_token(instance_id), + ) }; - let policy = fetch_port_policy(ip, agent_port).await?; + let policy = fetch_port_policy(ip, agent_port, agent_token.as_deref()).await?; state .lock() .update_instance_port_policy(instance_id, policy); Ok(()) } -async fn fetch_port_policy(ip: Ipv4Addr, agent_port: u16) -> Result { +async fn fetch_port_policy( + ip: Ipv4Addr, + agent_port: u16, + agent_token: Option<&str>, +) -> Result { let url = format!("http://{ip}:{agent_port}/prpc"); // Same untrusted peer as the health poller; see `guest_agent_client`. // Pooled, unlike the poller: this fills a cache rather than deciding // anything, it fires once per instance instead of on a timer, and a // connection that died while idle costs one retry of a lazy fetch. - let client = DstackGuestClient::new(super::guest_agent_client(url, ConnectionReuse::Pooled)); + let transport = super::guest_agent_client(url, ConnectionReuse::Pooled); + let transport = match agent_token { + Some(token) => transport.with_bearer_token(token), + None => transport, + }; + let client = DstackGuestClient::new(transport); // Network/RPC errors here are transient: agent might still be coming up. let info = client .info() diff --git a/dstack/guest-agent/Cargo.toml b/dstack/guest-agent/Cargo.toml index 9b028a6cc4..c0cff94d21 100644 --- a/dstack/guest-agent/Cargo.toml +++ b/dstack/guest-agent/Cargo.toml @@ -40,11 +40,12 @@ sysinfo.workspace = true default-net.workspace = true rocket-vsock-listener.workspace = true sd-notify.workspace = true -reqwest.workspace = true cmd_lib.workspace = true figment = { workspace = true, features = ["json", "toml"] } load_config.workspace = true k256 = { workspace = true, features = ["ecdsa"] } +dstack-api-auth.workspace = true +http-client.workspace = true dstack-types.workspace = true sha3.workspace = true strip-ansi-escapes.workspace = true diff --git a/dstack/guest-agent/src/api_auth.rs b/dstack/guest-agent/src/api_auth.rs new file mode 100644 index 0000000000..8dc31db4ac --- /dev/null +++ b/dstack/guest-agent/src/api_auth.rs @@ -0,0 +1,335 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! Access control for the guest agent's external listener. +//! +//! Every request that reaches `[external]` names a scope, and the caller has +//! to be granted it: either by an Ed25519 JWT, or -- when the host configured +//! it -- by being anonymous. Nothing is granted by default. +//! +//! This is deliberately not a trust boundary. The measured `public_*` switches +//! in app-compose still decide whether confidential data (logs, sysinfo, TCB +//! info) may leave the TEE at all; a scope can only narrow that, never widen +//! it. What scopes decide is who may *ask* -- which the host configures, and +//! which therefore cannot be part of the measurement. + +use std::{ + sync::{Arc, OnceLock}, + time::{SystemTime, UNIX_EPOCH}, +}; + +use anyhow::{Context, Result}; +use dstack_api_auth::jwt::{self, IssuerKeys, ScopeSet, Verifier}; +use dstack_types::{GuestAgentApiConfig, SysConfig}; +use ed25519_dalek::VerifyingKey; +use rocket::{ + fairing::{Fairing, Info, Kind}, + http::uri::Origin, + request::{FromRequest, Outcome}, + Data, Request, +}; +use tracing::warn; + +/// What a caller may do on the external listener. +#[derive(Clone)] +pub struct GuestApiAuth { + verifier: Verifier, + anonymous: ScopeSet, + /// The app id every token must be bound to. Not known until the boot + /// attestation has been decoded: until then anonymous access still works, + /// but no token can be checked, so none is accepted. + app_id: Arc>, +} + +impl GuestApiAuth { + /// Build from sys-config, given the app root key (if it parsed) and the + /// app id. + /// + /// `anonymous_scopes` is validated eagerly: a name outside the vocabulary + /// never matches anything, so a typo would otherwise read as "the host + /// asked for a permission that does not exist" only when someone could + /// not reach the dashboard. + pub fn new(config: Option<&GuestAgentApiConfig>, app_root_key: Option<&[u8]>) -> Result { + let config = config.cloned().unwrap_or_default(); + let anonymous = ScopeSet::from_names(config.anonymous_scopes.iter().cloned()); + for name in config.anonymous_scopes { + if !jwt::scope::is_known(&name) { + anyhow::bail!("guest_agent_api: unknown anonymous scope {name:?}"); + } + } + + let internal = match app_root_key { + Some(root) => { + let secret = ra_tls::api_v1::derive_app_key( + root, + jwt::INTERNAL_ISSUER_DOMAIN, + ra_tls::api_v1::KeyAlgorithm::Ed25519, + ) + .context("failed to derive the internal issuer key")?; + Some(ed25519_dalek::SigningKey::from_bytes(&secret).verifying_key()) + } + None => None, + }; + + let mut external = Vec::with_capacity(config.external_issuers.len()); + for issuer in config.external_issuers { + let mut keys = Vec::with_capacity(issuer.public_keys.len()); + for encoded in &issuer.public_keys { + let bytes = hex::decode(encoded) + .with_context(|| format!("issuer {:?}: public key is not hex", issuer.name))?; + let Ok(bytes): Result<[u8; 32], _> = bytes.try_into() else { + anyhow::bail!("issuer {:?}: public key must be 32 bytes", issuer.name); + }; + keys.push(VerifyingKey::from_bytes(&bytes).with_context(|| { + format!( + "issuer {:?}: public key is not a valid Ed25519 key", + issuer.name + ) + })?); + } + if keys.is_empty() { + warn!("issuer {:?} has no public keys", issuer.name); + } + external.push(IssuerKeys { + name: issuer.name, + keys, + }); + } + + Ok(Self { + verifier: Verifier::new(internal, external), + anonymous, + app_id: Arc::default(), + }) + } + + /// Build from a sys-config file's contents. + pub fn from_sys_config(sys_config: &SysConfig, app_root_key: Option<&[u8]>) -> Result { + Self::new(sys_config.guest_agent_api.as_ref(), app_root_key) + } + + /// Bind tokens to `app_id`. Called once the boot attestation has been + /// decoded; a second call is ignored, since the value cannot change. + pub fn bind_app_id(&self, app_id: String) { + let _ = self.app_id.set(app_id); + } + + /// The scopes a request carries, or `Err` when it presented a token that + /// did not verify. + /// + /// A rejected token never falls back to anonymous: a caller that meant to + /// authenticate and got it wrong should see a refusal, not whatever the + /// host happened to leave open. + fn resolve(&self, token: Option<&str>) -> Result { + let Some(token) = token else { + return Ok(self.anonymous.clone()); + }; + let Some(app_id) = self.app_id.get().map(String::as_str) else { + anyhow::bail!("no token can be accepted until the app identity is known"); + }; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let granted = self + .verifier + .verify(token, app_id, now) + .context("rejected bearer token")?; + Ok(self.anonymous.union(&granted)) + } +} + +/// The scopes in force for one request, published by [`ScopeFairing`]. +/// +/// A request guard rather than a fairing-only side effect because the +/// dashboard renders *parts* of itself by scope: it needs the set, not a +/// yes/no. +pub struct EffectiveScopes(pub ScopeSet); + +impl EffectiveScopes { + pub fn allows(&self, scope: &str) -> bool { + self.0.contains(scope) + } +} + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for EffectiveScopes { + type Error = (); + + async fn from_request(request: &'r Request<'_>) -> Outcome { + match request.local_cache(|| None::) { + Some(scopes) => Outcome::Success(EffectiveScopes(scopes.clone())), + None => Outcome::Forward(rocket::http::Status::Forbidden), + } + } +} + +/// The scope a request to the external listener needs, or `None` when the +/// request names no scope at all (an unknown route, which the router answers). +/// +/// `/prpc` and `/prpc/v0` are the same frozen surface, and the frozen mounts +/// trim the `Worker.` prefix, so `/prpc/Worker.Info`, `/prpc/v0/Info` and +/// `/prpc/Info` are one route with three spellings. Normalising here is what +/// keeps a caller from picking the spelling whose check was forgotten. +/// +/// The segments come from Rocket's own parser rather than from the raw path, +/// because that is what the router matches on: it percent-decodes and drops +/// empty segments, so `/%70rpc/Info` and `/prpc//Info` reach the same handler +/// as `/prpc/Info`. Comparing raw strings would let those spellings through +/// unchecked. +pub fn required_scope(path: &str) -> Option<&'static str> { + let origin = Origin::parse(path).ok()?; + let segments: Vec<&str> = origin.path().segments().filter(|s| !s.is_empty()).collect(); + match segments.as_slice() { + [] => Some(jwt::scope::DASHBOARD), + ["metrics"] => Some(jwt::scope::METRICS), + ["logs", ..] => Some(jwt::scope::LOGS), + _ => None, + } + .or_else(|| { + let method = match segments.as_slice() { + ["prpc", method] | ["prpc", "v0" | "v1", method] => *method, + _ => return None, + }; + match method.strip_prefix("Worker.").unwrap_or(method) { + "Version" => Some(jwt::scope::VERSION), + "Health" => Some(jwt::scope::HEALTH), + "Info" => Some(jwt::scope::INFO), + "GetAttestationForAppKey" => Some(jwt::scope::ATTEST_APP_KEY), + _ => None, + } + }) +} + +/// Refuses a request whose caller lacks the scope it names. +pub struct ScopeFairing { + auth: GuestApiAuth, +} + +impl ScopeFairing { + pub fn new(auth: GuestApiAuth) -> Self { + Self { auth } + } +} + +#[rocket::async_trait] +impl Fairing for ScopeFairing { + fn info(&self) -> Info { + Info { + name: "guest API scope enforcement", + kind: Kind::Request, + } + } + + async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) { + let path = req.uri().path().as_str(); + let token = req + .headers() + .get_one("Authorization") + .and_then(|value| value.strip_prefix("Bearer ")) + .map(str::trim); + let scopes = match self.auth.resolve(token) { + Ok(scopes) => scopes, + Err(err) => { + warn!("{err:#}"); + deny(req); + return; + } + }; + let denied = required_scope(path).is_some_and(|scope| !scopes.contains(scope)); + if denied { + deny(req); + return; + } + req.local_cache(|| Some(scopes)); + } +} + +fn deny(req: &mut Request<'_>) { + // `Bearer`, not the shared-token `Basic` default: the way to get in here is + // to present a token, and a client told to send Basic would send the wrong + // thing. + req.local_cache(|| dstack_api_auth::Challenge::Bearer); + if let Ok(uri) = Origin::parse_owned(dstack_api_auth::UNAUTHORIZED_PATH.to_owned()) { + req.set_uri(uri); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_spelling_of_a_route_needs_the_same_scope() { + for path in [ + "/prpc/Info", + "/prpc/v0/Info", + "/prpc/Worker.Info", + "/prpc/v0/Worker.Info", + ] { + assert_eq!(required_scope(path), Some(jwt::scope::INFO), "{path}"); + } + // The frozen surface has no `Health`, but requiring the scope for that + // spelling too is what keeps the check keyed on the method name rather + // than on which mount happened to answer. + for path in ["/prpc/v1/Health", "/prpc/Health", "/prpc/Worker.Health"] { + assert_eq!(required_scope(path), Some(jwt::scope::HEALTH), "{path}"); + } + assert_eq!(required_scope("/"), Some(jwt::scope::DASHBOARD)); + assert_eq!(required_scope("/metrics"), Some(jwt::scope::METRICS)); + assert_eq!(required_scope("/logs/app-1"), Some(jwt::scope::LOGS)); + assert_eq!( + required_scope("/prpc/GetAttestationForAppKey"), + Some(jwt::scope::ATTEST_APP_KEY) + ); + assert_eq!(required_scope("/nope"), None); + + // The router matches on decoded, non-empty segments, so these reach + // the same handler and must not be able to slip past the check. + for path in ["/%70rpc/Info", "/prpc//Info", "/prpc/v0//Worker.Info"] { + assert_eq!(required_scope(path), Some(jwt::scope::INFO), "{path}"); + } + assert_eq!(required_scope("/%6detrics"), Some(jwt::scope::METRICS)); + } + + fn auth(anonymous: &[&str]) -> GuestApiAuth { + GuestApiAuth::new( + Some(&GuestAgentApiConfig { + anonymous_scopes: anonymous.iter().map(|s| s.to_string()).collect(), + external_issuers: vec![], + }), + Some(&[7u8; 32]), + ) + .unwrap() + } + + #[test] + fn anonymous_grants_only_what_was_configured() { + assert!(auth(&[]).resolve(None).unwrap().is_empty()); + let scopes = auth(&["guest:version"]).resolve(None).unwrap(); + assert!(scopes.contains(jwt::scope::VERSION)); + assert!(!scopes.contains(jwt::scope::INFO)); + } + + #[test] + fn a_bad_token_is_refused_rather_than_downgraded_to_anonymous() { + assert!(auth(&["guest:dashboard"]) + .resolve(Some("not-a-token")) + .is_err()); + } + + #[test] + fn an_unknown_anonymous_scope_fails_at_startup() { + let err = GuestApiAuth::new( + Some(&GuestAgentApiConfig { + anonymous_scopes: vec!["guest:everything".into()], + external_issuers: vec![], + }), + Some(&[7u8; 32]), + ) + .err() + .expect("should reject"); + assert!(err.to_string().contains("guest:everything"), "{err}"); + } +} diff --git a/dstack/guest-agent/src/config.rs b/dstack/guest-agent/src/config.rs index fb816f2f12..1c090c0ea7 100644 --- a/dstack/guest-agent/src/config.rs +++ b/dstack/guest-agent/src/config.rs @@ -23,9 +23,16 @@ pub fn load_config_figment_with_default( load_config("dstack", default_config, config_file, true) } -#[derive(Debug, Clone, Copy, Deserialize)] -pub struct BindAddr { - pub port: u16, +/// Where one listener binds. +/// +/// The external listener states a port; the internal ones state a unix socket +/// path. Deserialized as a whole rather than per field so a typo in either is +/// a startup error instead of a listener that silently binds elsewhere. +#[derive(Debug, Clone, Deserialize)] +pub struct SocketAddr { + pub address: String, + #[serde(default)] + pub port: Option, } #[derive(Debug, Clone)] diff --git a/dstack/guest-agent/src/http_routes.rs b/dstack/guest-agent/src/http_routes.rs index 833cd0bd3d..4a09aac90a 100644 --- a/dstack/guest-agent/src/http_routes.rs +++ b/dstack/guest-agent/src/http_routes.rs @@ -4,11 +4,13 @@ use std::time::Duration; +use crate::api_auth::EffectiveScopes; use crate::config::Config; use crate::guest_api_service::{list_containers, GuestApiHandler}; use crate::rpc_service::{AppState, ExternalRpcHandler}; use anyhow::Result; use docker_logs::parse_duration; +use dstack_api_auth::jwt; use dstack_guest_agent_rpc::v0::{worker_server::WorkerRpc, AppInfo}; use guest_api::guest_api_server::GuestApiRpc; use ra_rpc::{CallContext, RpcCall}; @@ -28,11 +30,26 @@ pub fn external_routes(config: &Config) -> Vec { routes } +/// The dashboard, filtered by what this caller was granted. +/// +/// Access to the page is `guest:dashboard` (enforced by the fairing); what it +/// *shows* is narrowed block by block. Two independent gates: the app's +/// measured `public_*` switches decide whether confidential data may leave the +/// TEE at all, and the caller's scopes decide whether this caller may see it. +/// A scope can only hide a block, never reveal one the app kept private. #[get("/")] -async fn index(state: &State) -> Result, String> { +async fn index( + state: &State, + scopes: EffectiveScopes, +) -> Result, String> { let public_logs = state.config().app_compose.public_logs; let public_sysinfo = state.config().app_compose.public_sysinfo; let public_tcbinfo = state.config().app_compose.public_tcbinfo; + let show_identity = scopes.allows(jwt::scope::INFO); + let show_sysinfo = public_sysinfo && scopes.allows(jwt::scope::METRICS); + let show_containers = scopes.allows(jwt::scope::CONTAINERS); + let show_logs = public_logs && scopes.allows(jwt::scope::LOGS); + let show_tcb = public_tcbinfo && show_identity; let context = CallContext::builder().state(&**state).build(); let handler = ExternalRpcHandler::construct(context.clone()) .map_err(|e| format!("Failed to construct RPC handler: {}", e))?; @@ -58,7 +75,7 @@ async fn index(state: &State) -> Result, String> { // Only collected when the page will actually render it. Collecting // otherwise would scan every process and disk, and spawn a GPU collector, // on guests that keep their sysinfo private. - let (system_info, gpu_info) = if public_sysinfo { + let (system_info, gpu_info) = if show_sysinfo { let handler = GuestApiHandler::construct(context) .map_err(|e| format!("Failed to construct RPC handler: {}", e))?; ( @@ -69,7 +86,13 @@ async fn index(state: &State) -> Result, String> { Default::default() }; - let containers = list_containers().await.unwrap_or_default().containers; + // Skipped, not merely hidden: the listing walks every container on a + // page an anonymous caller may be allowed to reach. + let containers = if show_containers { + list_containers().await.unwrap_or_default().containers + } else { + Vec::new() + }; let model = crate::models::Dashboard { app_name, app_id, @@ -79,9 +102,11 @@ async fn index(state: &State) -> Result, String> { tcb_info, containers, system_info, - public_sysinfo, - public_logs, - public_tcbinfo, + show_identity, + show_sysinfo, + show_containers, + show_logs, + show_tcb, cloud_vendor, cloud_product, gpu_info, diff --git a/dstack/guest-agent/src/lib.rs b/dstack/guest-agent/src/lib.rs index 7c70e192a3..d419cabf8d 100644 --- a/dstack/guest-agent/src/lib.rs +++ b/dstack/guest-agent/src/lib.rs @@ -5,6 +5,7 @@ pub const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION"); pub const GIT_REV: &str = dstack_build_info::git_revision!(); +mod api_auth; pub mod backend; pub mod config; mod container_health; diff --git a/dstack/guest-agent/src/models.rs b/dstack/guest-agent/src/models.rs index c8719105b2..89f9624cc7 100644 --- a/dstack/guest-agent/src/models.rs +++ b/dstack/guest-agent/src/models.rs @@ -116,12 +116,26 @@ pub struct Dashboard { pub tcb_info: String, pub containers: Vec, pub system_info: SystemInfo, - pub public_sysinfo: bool, - pub public_logs: bool, - pub public_tcbinfo: bool, + /// The host's sysinfo and GPU collection may be shown: published by the + /// app (`public_sysinfo`) *and* granted to this caller. + pub show_sysinfo: bool, + /// The TCB document may be shown: published by the app + /// (`public_tcbinfo`) *and* granted to this caller. + pub show_tcb: bool, pub cloud_vendor: String, pub cloud_product: String, pub gpu_info: GpuInfoResponse, + /// Whether the caller may see the identity block at all. The page itself + /// already needs `guest:dashboard`; this narrows what it shows, block by + /// block, so a token for one kind of data does not carry the rest. + pub show_identity: bool, + /// Whether the container table is shown. Also decides whether the + /// container list is collected: a scope that hides a block should not pay + /// for producing it. + pub show_containers: bool, + /// Whether the logs column is shown. Requires `public_logs` as well -- a + /// scope cannot unlock logs the app did not publish. + pub show_logs: bool, } #[derive(Template)] @@ -253,11 +267,13 @@ mod tests { tcb_info: String::new(), containers: vec![], system_info: Default::default(), - public_sysinfo: true, - public_logs: false, - public_tcbinfo: false, + show_sysinfo: true, + show_tcb: false, cloud_vendor: String::new(), cloud_product: String::new(), + show_identity: true, + show_containers: true, + show_logs: true, gpu_info: GpuInfoResponse { gpus: vec![GpuDevice { power_usage_mw: Some(70_123), @@ -404,11 +420,13 @@ mod tests { tcb_info: String::new(), containers: vec![], system_info: Default::default(), - public_sysinfo: true, - public_logs: false, - public_tcbinfo: false, + show_sysinfo: true, + show_tcb: false, cloud_vendor: String::new(), cloud_product: String::new(), + show_identity: true, + show_containers: true, + show_logs: true, gpu_info, } .render() diff --git a/dstack/guest-agent/src/rpc_service.rs b/dstack/guest-agent/src/rpc_service.rs index 6ae1a8aa7a..a180c0c5a9 100644 --- a/dstack/guest-agent/src/rpc_service.rs +++ b/dstack/guest-agent/src/rpc_service.rs @@ -123,6 +123,8 @@ struct AppStateInner { /// VM is running. cloud_vendor: String, cloud_product: String, + /// Access control for the external listener. See `api_auth`. + api_auth: crate::api_auth::GuestApiAuth, } /// The identity fields v1 `Info` reports, decoded once. @@ -258,7 +260,7 @@ impl AppState { .context("Failed to parse VM config")?; let collateral_urls = sys_config.collateral_urls(); let gpu_attestor = crate::gpu_attest::GpuAttestor::new(); - let vm_config = sys_config.vm_config; + let vm_config = sys_config.vm_config.clone(); // Same trust anchor decision as dstack-util: never host-supplied, and // development roots only when this guest published them itself. let verifier = Arc::new(default_verifier(&collateral_urls)?); @@ -279,6 +281,11 @@ impl AppState { config.app_compose.runner.clone(), ) }); + // Built before the state so a bad `guest_agent_api` block is a boot + // error: an unknown scope name would otherwise silently grant nothing. + let api_auth = + crate::api_auth::GuestApiAuth::from_sys_config(&sys_config, Some(&keys.k256_key)) + .context("Failed to set up guest API access control")?; // Parsed once, and non-fatally: an unusable app root key is reported by // the RPCs that need one, not by refusing to start. let app_root_signing_key = match SigningKey::from_slice(&keys.k256_key) { @@ -305,6 +312,7 @@ impl AppState { attest_lock: Arc::default(), cloud_vendor: read_dmi_file("sys_vendor"), cloud_product: read_dmi_file("product_name"), + api_auth, }), }; // Decode identity now so no request has to. Non-fatal: a platform that @@ -327,6 +335,11 @@ impl AppState { &self.inner.config } + /// Access control for the external listener. + pub(crate) fn api_auth(&self) -> &crate::api_auth::GuestApiAuth { + &self.inner.api_auth + } + pub(crate) fn health(&self) -> Option<&crate::health::HealthMonitor> { self.inner.health.as_deref() } @@ -405,6 +418,16 @@ impl AppState { self.inner .attest(decode_identity) .await + // External tokens are bound to the app id, which only the + // boot attestation can supply. Binding here rather than at + // startup covers the retry path too: until it lands the + // listener serves anonymous callers and refuses every + // token. + .inspect(|identity| { + self.inner + .api_auth + .bind_app_id(hex::encode(&identity.app_id)); + }) .inspect_err(|_| { *last_failure.lock().or_panic("lock should never fail") = Some(Instant::now()); @@ -1463,6 +1486,7 @@ pNs85uhOZE8z2jr8Pg== // against v0 `get_info` compares like with like. cloud_vendor: read_dmi_file("sys_vendor"), cloud_product: read_dmi_file("product_name"), + api_auth: crate::api_auth::GuestApiAuth::new(None, Some(&DUMMY_K256_KEY)).unwrap(), }; ( diff --git a/dstack/guest-agent/src/server.rs b/dstack/guest-agent/src/server.rs index 0021f4f9be..7a02500cde 100644 --- a/dstack/guest-agent/src/server.rs +++ b/dstack/guest-agent/src/server.rs @@ -4,7 +4,8 @@ use std::{future::pending, os::unix::net::UnixListener as StdUnixListener, time::Duration}; -use crate::config::BindAddr; +use crate::api_auth::ScopeFairing; +use crate::config::SocketAddr; use crate::guest_api_service::GuestApiHandler; use crate::http_routes; use crate::rpc_service::{AppState, ExternalRpcHandler, InternalRpcHandler, InternalRpcHandlerV0}; @@ -177,8 +178,13 @@ async fn run_internal( } async fn run_external(state: AppState, figment: Figment) -> Result<()> { + let scopes = ScopeFairing::new(state.api_auth().clone()); let rocket = mount_external(rocket::custom(figment)) .mount("/", http_routes::external_routes(state.config())) + // Mounted first so a denied request has somewhere to land that is not + // itself behind the check. + .mount("/", dstack_api_auth::routes()) + .attach(scopes) .attach(AdHoc::on_response("Add app version header", |_req, res| { Box::pin(async move { res.set_raw_header("X-App-Version", app_version()); @@ -220,7 +226,14 @@ async fn run_guest_api(state: AppState, figment: Figment) -> Result<()> { Ok(()) } -async fn run_watchdog(port: u16) { +/// Probe the internal socket, not the external listener. +/// +/// The external listener now refuses anonymous callers by default, so probing +/// it would report the agent dead whenever the host configured no anonymous +/// scope. The unix socket is the surface that cannot depend on that: it is +/// local-only, unauthenticated, and always mounted. It also answers with the +/// same `Version` the port probe asked for. +async fn run_watchdog(socket_path: String) { let mut watchdog_usec = 0; let enabled = sd_notify::watchdog_enabled(false, &mut watchdog_usec); if !enabled { @@ -237,19 +250,17 @@ async fn run_watchdog(port: u16) { info!("Watchdog enabled, interval={watchdog_usec}us, heartbeat={heatbeat_interval:?}"); let mut interval = tokio::time::interval(heatbeat_interval); - let probe_url = format!("http://localhost:{port}/prpc/Worker.Version"); loop { interval.tick().await; - let client = reqwest::Client::new(); - match client.get(&probe_url).send().await { - Ok(response) if response.status().is_success() => { + match http_client::http_request("GET", &socket_path, "/Version", &[]).await { + Ok((status, _)) if (200..300).contains(&status) => { if let Err(err) = sd_notify(false, &[NotifyState::Watchdog]) { error!("Failed to notify systemd: {err}"); } } - Ok(response) => { - error!("Health check failed with status: {}", response.status()); + Ok((status, _)) => { + error!("Health check failed with status: {status}"); } Err(err) => { error!("Health check request failed: {err:?}"); @@ -262,11 +273,12 @@ pub async fn run(state: AppState, figment: Figment, watchdog: bool) -> Result<() let internal_v0_figment = figment.clone().select("internal-v0"); let internal_figment = figment.clone().select("internal"); let external_figment = figment.clone().select("external"); - let bind_addr = if watchdog { + let watchdog_socket = if watchdog { Some( - external_figment - .extract::() - .context("Failed to extract bind address")?, + internal_figment + .extract::() + .context("Failed to extract the internal socket address")? + .address, ) } else { None @@ -288,8 +300,8 @@ pub async fn run(state: AppState, figment: Figment, watchdog: bool) -> Result<() _ = async { let _ = tappd_ready_rx.await; let _ = sock_ready_rx.await; - if let Some(bind_addr) = bind_addr { - run_watchdog(bind_addr.port).await; + if let Some(socket_path) = watchdog_socket { + run_watchdog(socket_path).await; } else { pending::<()>().await; } diff --git a/dstack/guest-agent/templates/dashboard.html b/dstack/guest-agent/templates/dashboard.html index ee973bb909..29e19d94e1 100644 --- a/dstack/guest-agent/templates/dashboard.html +++ b/dstack/guest-agent/templates/dashboard.html @@ -158,9 +158,11 @@ + {% if show_identity || show_sysinfo %}

Node Information

+ {% if show_identity %}
App Name
{{app_name}}
@@ -187,7 +189,8 @@

Node Information

{{cloud_vendor}} ({{cloud_product}})
{% endif %} - {% if public_sysinfo %} + {% endif %} + {% if show_sysinfo %}
Operating System
{{system_info.os_name}} {{system_info.os_version}}
@@ -225,8 +228,9 @@

Node Information

{% endif %}
+ {% endif %} - {% if public_sysinfo %} + {% if show_sysinfo %}

GPUs

{% if !gpu_info.error.is_empty() %}
{{ gpu_info.error }}
@@ -333,6 +337,7 @@

GPUs

{% endif %} {% endif %} + {% if show_containers %}

Deployed Containers

@@ -340,7 +345,7 @@

Deployed Containers

- {% if public_logs %} + {% if show_logs %} {% endif %} @@ -351,7 +356,7 @@

Deployed Containers

- {% if public_logs %} + {% if show_logs %}
Name StatusLogs
{{name|cname}} {{container.status}} View Logs @@ -362,12 +367,11 @@

Deployed Containers

+ {% endif %} + {% if show_tcb %}

TCB Info

- {% if public_tcbinfo %} - {% else %} -

TCB info is not public

{% endif %} diff --git a/dstack/vmm/src/app.rs b/dstack/vmm/src/app.rs index b43710e7be..7be178e7db 100644 --- a/dstack/vmm/src/app.rs +++ b/dstack/vmm/src/app.rs @@ -2078,6 +2078,11 @@ pub(crate) fn make_sys_config( "host_api_url": format!("vsock://2:{}/api", cfg.host_api.port), "vm_config": serde_json::to_string(&vm_config)?, }); + // Omitted when unconfigured so an existing node's sys-config does not + // change shape just because this setting exists. + if cfg.cvm.guest_agent_api != Default::default() { + sys_config["guest_agent_api"] = serde_json::to_value(&cfg.cvm.guest_agent_api)?; + } // No attestation trust anchor is ever written here. Simulated deployments // receive only the development seed through `.tee-simulator.json`; the // in-guest simulator derives the matching roots itself and publishes them diff --git a/dstack/vmm/src/config.rs b/dstack/vmm/src/config.rs index 7d97a5ef5a..6bacd08386 100644 --- a/dstack/vmm/src/config.rs +++ b/dstack/vmm/src/config.rs @@ -308,6 +308,29 @@ where ) } +/// Check the block before it is handed to guests: the guest rejects the same +/// things at boot, and an operator would rather learn about a typo at `vmm` +/// startup than from a CVM that will not come up. +fn validate_guest_agent_api(config: &dstack_types::GuestAgentApiConfig) -> Result<()> { + for name in &config.anonymous_scopes { + anyhow::ensure!( + dstack_api_auth::jwt::scope::is_known(name), + "unknown anonymous scope {name:?}" + ); + } + for issuer in &config.external_issuers { + anyhow::ensure!(!issuer.name.is_empty(), "an external issuer needs a name"); + for key in &issuer.public_keys { + anyhow::ensure!( + hex::decode(key).is_ok_and(|bytes| bytes.len() == 32), + "issuer {:?}: public key must be 32 bytes of hex", + issuer.name + ); + } + } + Ok(()) +} + impl CvmConfig { /// The effective TEE platform: the configured one, or host auto-detection /// when left unset (`platform` omitted / `auto`). @@ -496,6 +519,13 @@ pub struct CvmConfig { #[serde(default)] pub instance_id: String, + /// Who may call the guest agent's external API (port 8090). Handed to the + /// guest in sys-config, so it is a host decision and not part of the + /// measurement; the measured `public_*` switches in app-compose still + /// decide whether confidential data may be exposed at all. + #[serde(default)] + pub guest_agent_api: dstack_types::GuestAgentApiConfig, + /// Host sharing mode. (9p, vhd, vvfat) pub host_share_mode: String, @@ -828,6 +858,8 @@ impl Config { .context("Invalid host_api configuration")?; self.netd.validate()?; + validate_guest_agent_api(&self.cvm.guest_agent_api) + .context("Invalid cvm.guest_agent_api configuration")?; anyhow::ensure!(self.cvm.cid_start >= 3, "cvm.cid_start must be at least 3"); anyhow::ensure!( @@ -1462,6 +1494,29 @@ mod tests { assert!(err.contains("set `qemu_version` in vmm.toml"), "{err}"); } + #[test] + fn guest_agent_api_rejects_what_the_guest_would_reject_at_boot() { + let mut config = dstack_types::GuestAgentApiConfig::default(); + config.anonymous_scopes = vec!["guest:dashboard".into()]; + assert!(validate_guest_agent_api(&config).is_ok()); + + config.anonymous_scopes = vec!["guest:everything".into()]; + assert!(validate_guest_agent_api(&config) + .unwrap_err() + .to_string() + .contains("guest:everything")); + + config.anonymous_scopes.clear(); + config.external_issuers = vec![dstack_types::ExternalJwtIssuer { + name: "ops".into(), + public_keys: vec!["not-hex".into()], + }]; + assert!(validate_guest_agent_api(&config) + .unwrap_err() + .to_string() + .contains("ops")); + } + #[test] fn auto_restart_config_rejects_hot_loop_and_inverted_backoff() { let mut config = AutoRestartConfig { diff --git a/dstack/vmm/vmm.toml b/dstack/vmm/vmm.toml index f040d60f6b..680dbc8fb0 100644 --- a/dstack/vmm/vmm.toml +++ b/dstack/vmm/vmm.toml @@ -109,6 +109,18 @@ tdx_attestation_variant = "auto" host_share_mode = "9p" +# Access control for the guest agent's external listener (port 8090). Absent +# means nothing is anonymous: only holders of a token (the gateway, minted +# inside the CVM) can call it. This is an exposure choice, not a +# confidentiality one -- what may leave the TEE is still decided by the +# measured public_logs / public_sysinfo / public_tcbinfo switches in +# app-compose. See docs/guest-api-auth.md. +# [cvm.guest_agent_api] +# anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health"] +# [[cvm.guest_agent_api.external_issuers]] +# name = "ops" +# public_keys = ["<32-byte ed25519 public key, hex>"] + # Default preallocation for a new CVM data disk. This is a host storage # policy -- the guest cannot see it and it does not affect measurements -- and # a deploy request may pick another mode per VM. From 23a6ed629519c1b9e508978e6da3591377713d42 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Thu, 22 Oct 2026 00:54:48 -0700 Subject: [PATCH 040/572] guest-agent: fail closed on unknown external routes `/prpc/Worker.Worker.Info` reached `Info` with no token: the scope check stripped one `Worker.` prefix and saw an unknown method, which it let through, while ra-rpc stripped every leading prefix with `trim_start_matches` and dispatched it. ra-rpc now strips exactly one, and a path the scope table does not name is refused instead of passed on. Tokens were refused for the life of the process if the startup identity decode failed: the app id was only bound when `identity()` succeeded, and nothing on the token path retried it. The fairing now asks `identity()` itself whenever a token is presented, which also drops the `OnceLock`. Also: - The gateway token carries only `guest:health`. A CVM that mints one always reports its port policy, so the lazy `Info` fetch never runs with it; the `port_policy.rs` plumbing is reverted. - The systemd watchdog probes the external listener again and counts a 401 as alive, instead of moving to the internal socket. - The bearer scheme is matched case-insensitively. - Docs: the CVM is one trust domain, so any process with `dstack.sock` can derive the issuer key through `GetKey`; fix who holds the app root key. Signed-off-by: Kevin Wang --- docs/guest-api-auth.md | 46 ++-- dstack/Cargo.lock | 2 +- dstack/crates/api-auth/src/jwt.rs | 16 +- dstack/crates/api-auth/src/lib.rs | 2 +- dstack/dstack-util/src/system_setup.rs | 57 ++--- dstack/gateway/rpc/proto/gateway_rpc.proto | 6 +- dstack/gateway/src/kv/mod.rs | 5 +- dstack/gateway/src/main_service.rs | 9 - dstack/gateway/src/models.rs | 4 +- dstack/gateway/src/proxy/port_policy.rs | 23 +- dstack/guest-agent/Cargo.toml | 2 +- dstack/guest-agent/src/api_auth.rs | 261 ++++++++++----------- dstack/guest-agent/src/config.rs | 13 +- dstack/guest-agent/src/rpc_service.rs | 32 +-- dstack/guest-agent/src/server.rs | 114 +++++++-- dstack/ra-rpc/src/rocket_helper.rs | 4 +- 16 files changed, 302 insertions(+), 294 deletions(-) diff --git a/docs/guest-api-auth.md b/docs/guest-api-auth.md index 2ec51495ba..c6c7451861 100644 --- a/docs/guest-api-auth.md +++ b/docs/guest-api-auth.md @@ -26,11 +26,10 @@ only narrow what those allow. See `/prpc`, `/prpc/v0` and `/prpc/v1` are matched after percent-decoding and segment normalisation, so `/prpc/Worker.Info`, `/prpc/v0/Info` and -`/%70rpc/Info` all need `guest:info`. There is no spelling that reaches a -handler with a weaker check. +`/%70rpc/Info` all need `guest:info`. -A route the vocabulary does not name needs no scope: nothing is mounted there, -and the router's 404 is the answer. +The check fails closed: a path the table does not name is answered with 401, +not passed to the router. ## Default: nothing anonymous @@ -88,24 +87,32 @@ so they cannot be expressed. ### Where the internal issuer comes from -The agent and the gateway both hold the app root key inside the TEE. The token -the gateway presents is minted in the guest's own setup (`dstack-util`) and -carried on registration, so it can be bound to the app id and expire: +The gateway does not hold the app root key; the CVM mints its token and hands +it over on registration, bound to the app id and short-lived: -1. Both derive the same Ed25519 key: - `derive_app_key(app_root_key, "dstack:guest-api:issuer:v1", Ed25519)`. +1. The agent and `dstack-util`, both inside the CVM, derive the same Ed25519 + key: `derive_app_key(app_root_key, "dstack:guest-api:issuer:v1", Ed25519)`. 2. `dstack-util` signs a token with `iss = "dstack:guest-api:"`, - `aud = `, a 10-minute lifetime, and the `guest:health`, `guest:info` - scopes. + `aud = `, a 10-minute lifetime, and only the `guest:health` scope. 3. Registration carries it to the gateway, which presents it on the v1 `Health` - poll and on the lazy `Info` fetch that fills in a port policy the CVM did not - report. + poll. -Nothing else gets a token: the gateway has no business on the dashboard or in -the logs. +The host cannot mint an internal token: the signing key is derived from the app +root key, which KMS releases only after the boot measurement is verified. The +host can still name its own [external issuer](#external-issuers) and grant +itself any scope; that is the same exposure as listing the scope in +`anonymous_scopes`, and still bounded by the measured switches. -The host cannot mint one: the signing key is derived from the app root key, which -is released to the guest by KMS only after the boot measurement is verified. +### Trust inside the CVM + +The CVM is one trust domain; the agent does not sandbox the processes in it. The +issuer key is an ordinary v1 application key, so any process that can reach +`dstack.sock` can obtain it with +`GetKey(domain = "dstack:guest-api:issuer:v1", algorithm = ed25519)` and mint a +token with any scope. That is by design -- the same process can already read +the data those scopes expose -- and it is also how an app issues tokens of its +own. Do not mount `dstack.sock` into a container you would not trust with +that. ## The two gates @@ -137,8 +144,5 @@ During the rollout, either upgrade the gateway first, or leave the host open: ```toml [cvm.guest_agent_api] -anonymous_scopes = ["guest:version", "guest:health", "guest:info"] +anonymous_scopes = ["guest:version", "guest:health"] ``` - -`guest:info` is needed by gateways that did not report a port policy and fetch -it lazily. diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index fcfd0385a2..06397dbdde 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -2039,7 +2039,6 @@ dependencies = [ "guest-api", "hex", "host-api", - "http-client", "k256", "libc", "listenfd", @@ -2051,6 +2050,7 @@ dependencies = [ "ra-tls", "rand 0.8.6", "rcgen 0.13.2", + "reqwest", "ring", "rinja", "rocket", diff --git a/dstack/crates/api-auth/src/jwt.rs b/dstack/crates/api-auth/src/jwt.rs index 361e868c82..6f13599810 100644 --- a/dstack/crates/api-auth/src/jwt.rs +++ b/dstack/crates/api-auth/src/jwt.rs @@ -170,21 +170,15 @@ pub struct IssuerKeys { /// Verifies tokens and reports what they grant. #[derive(Clone)] pub struct Verifier { - internal: Option, + internal: VerifyingKey, external: Vec, } impl Verifier { - /// `internal` is absent only when the app root key could not produce one; - /// an agent in that state still verifies external issuers. - pub fn new(internal: Option, external: Vec) -> Self { + pub fn new(internal: VerifyingKey, external: Vec) -> Self { Self { internal, external } } - pub fn is_empty(&self) -> bool { - self.internal.is_none() && self.external.is_empty() - } - /// Verify `token` for the application whose id is `app_id_hex`. /// /// `now` is seconds since the UNIX epoch, passed in rather than read here @@ -238,7 +232,7 @@ impl Verifier { fn keys_for(&self, iss: &str, app_id_hex: &str) -> Vec<&VerifyingKey> { if iss == internal_issuer(app_id_hex) { - return self.internal.iter().collect(); + return vec![&self.internal]; } self.external .iter() @@ -274,7 +268,7 @@ mod tests { fn verifier(seed: u8) -> Verifier { Verifier::new( - Some(SigningKey::from_bytes(&signing_key(seed)).verifying_key()), + SigningKey::from_bytes(&signing_key(seed)).verifying_key(), vec![], ) } @@ -362,7 +356,7 @@ mod tests { #[test] fn accepts_an_external_issuer_by_name() { let verifier = Verifier::new( - None, + SigningKey::from_bytes(&signing_key(1)).verifying_key(), vec![IssuerKeys { name: "ops".into(), keys: vec![SigningKey::from_bytes(&signing_key(9)).verifying_key()], diff --git a/dstack/crates/api-auth/src/lib.rs b/dstack/crates/api-auth/src/lib.rs index 3932de22ad..f53deab2b7 100644 --- a/dstack/crates/api-auth/src/lib.rs +++ b/dstack/crates/api-auth/src/lib.rs @@ -301,7 +301,7 @@ impl<'r> Responder<'r, 'static> for Unauthorized { } } -pub(crate) struct RequestRealm(String); +struct RequestRealm(String); #[rocket::get("/__dstack_api_auth_unauthorized")] fn unauth_get() -> Unauthorized { diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index bc2b227595..86f1cc5f2f 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -494,48 +494,35 @@ struct GatewayContext<'a> { keys: &'a AppKeys, } -/// Scopes the gateway needs on the guest agent's external listener: the v1 -/// `Health` poll, and the frozen `Info` call that fills in a port policy the -/// CVM did not report. Nothing else -- the gateway has no business on the -/// dashboard or in the logs. -const GATEWAY_AGENT_SCOPES: &[&str] = &[jwt::scope::HEALTH, jwt::scope::INFO]; - -/// Mint the token the gateway presents to this CVM's guest agent. -/// -/// Derived from the app root key, so it needs no distribution: the agent holds -/// the public half, this holds the private one, and the gateway only carries -/// the result. `None` when either side is not ready yet -- an app id that only -/// the boot attestation can supply, or an app root key that does not parse -- -/// in which case registration carries no token and the agent answers -/// anonymously, exactly as it did before this existed. -/// -/// One token for both calls the gateway makes, because both are the gateway -/// doing its own job: the v1 `Health` poll, and the frozen `Info` that fills in -/// a port policy the CVM did not report. Scopes are still a whitelist -- the -/// gateway gets nothing on the dashboard or in the logs. -fn gateway_agent_token(app_id: &[u8], app_root_key: &[u8]) -> Option { +/// The gateway only polls `Health`. Port policy reaches it on registration, so +/// it never needs `Info` from a CVM that can mint this token. +const GATEWAY_AGENT_SCOPES: &[&str] = &[jwt::scope::HEALTH]; + +/// Lifetime of the gateway's token. Registration refreshes every three +/// minutes; this survives a few failed refreshes so a gateway outage does not +/// also lock the gateway out of the agent. +const GATEWAY_AGENT_TOKEN_LIFETIME_SECS: u64 = 600; + +/// Mint the token the gateway presents to this CVM's guest agent, signed with +/// the key the agent derives the same way from the app root key. +fn gateway_agent_token(app_id: &[u8], app_root_key: &[u8]) -> Result { let secret = ra_tls::api_v1::derive_app_key( app_root_key, jwt::INTERNAL_ISSUER_DOMAIN, ra_tls::api_v1::KeyAlgorithm::Ed25519, - ) - .ok()?; + )?; let app_id = hex::encode(app_id); - // Long enough to survive a few failed refreshes: a token that expired - // during a gateway outage would turn "we could not re-register" into "we - // are locked out until the outage ends". let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .ok()? + .duration_since(std::time::UNIX_EPOCH)? .as_secs(); let claims = jwt::Claims { iss: jwt::internal_issuer(&app_id), aud: app_id, iat: now, - exp: now + 600, + exp: now + GATEWAY_AGENT_TOKEN_LIFETIME_SECS, scope: GATEWAY_AGENT_SCOPES.join(" "), }; - jwt::sign(&secret, &claims).ok() + jwt::sign(&secret, &claims) } impl<'a> GatewayContext<'a> { @@ -577,14 +564,12 @@ impl<'a> GatewayContext<'a> { key_store: &GatewayKeyStore, gateway_app_id: &str, ) -> Result { + // Not fatal: without a token the gateway's health poll is refused, which + // costs routing but should not cost the boot. let agent_token = - gateway_agent_token(&self.shared.instance_info.app_id, &self.keys.k256_key); - if agent_token.is_none() { - // Not fatal: the CVM registers without one and the agent answers - // however the host configured it. Say so once per registration - // rather than failing a boot over it. - info!("no guest agent token available; registering without one"); - } + gateway_agent_token(&self.shared.instance_info.app_id, &self.keys.k256_key) + .inspect_err(|err| warn!("failed to mint the guest agent token: {err:#}")) + .ok(); let port_policy = RpcPortPolicy { ports: self .shared diff --git a/dstack/gateway/rpc/proto/gateway_rpc.proto b/dstack/gateway/rpc/proto/gateway_rpc.proto index 6a889673fb..04ad4c795a 100644 --- a/dstack/gateway/rpc/proto/gateway_rpc.proto +++ b/dstack/gateway/rpc/proto/gateway_rpc.proto @@ -37,9 +37,9 @@ message RegisterCvmRequest { // CVM re-registers every three minutes, so a stale copy never outlives its // usefulness. // - // Empty from a CVM that predates the field, or one whose app identity is - // not known yet. The gateway then calls without a token and gets whatever - // the host left open -- possibly nothing, which is the intended default. + // Empty from a CVM that predates the field, or one that could not mint it. + // The gateway then calls without a token and gets whatever the host left + // open -- possibly nothing, which is the intended default. optional string agent_token = 4; } diff --git a/dstack/gateway/src/kv/mod.rs b/dstack/gateway/src/kv/mod.rs index 5238d36765..915baee5e1 100644 --- a/dstack/gateway/src/kv/mod.rs +++ b/dstack/gateway/src/kv/mod.rs @@ -130,9 +130,8 @@ pub struct InstanceRecord { /// a rollback and forward again. #[serde(default)] pub health_check: Option, - /// Token this CVM minted for the gateway, so the agent's external listener - /// can answer an operator-run caller. `None` for a CVM that predates the - /// field, or one whose app id is not yet known. + /// Token this CVM minted for the gateway's `Health` poll. `None` for a CVM + /// that predates the field, or one that could not mint it. /// /// Per-instance rather than per-app: the token is bound to the instance's /// app id and expires within the hour, and the CVM re-registers every diff --git a/dstack/gateway/src/main_service.rs b/dstack/gateway/src/main_service.rs index 5c77116c70..7c931a4306 100644 --- a/dstack/gateway/src/main_service.rs +++ b/dstack/gateway/src/main_service.rs @@ -2134,15 +2134,6 @@ impl ProxyState { self.state.instances.get(instance_id).map(|i| i.ip) } - /// The bearer token an instance's guest agent external listener accepts, - /// if the CVM supplied one at registration. - pub(crate) fn instance_agent_token(&self, instance_id: &str) -> Option { - self.state - .instances - .get(instance_id) - .and_then(|info| info.agent_token.clone()) - } - /// Lookup the effective port_policy for an instance: admin override wins, /// otherwise fall back to the instance-reported policy. `None` means /// neither is set — caller fails closed and may schedule a lazy fetch. diff --git a/dstack/gateway/src/models.rs b/dstack/gateway/src/models.rs index abaa9663a8..6ee4e11d48 100644 --- a/dstack/gateway/src/models.rs +++ b/dstack/gateway/src/models.rs @@ -73,8 +73,8 @@ pub struct InstanceInfo { /// declaration and verdict disagree. pub(crate) health: Health, /// Bearer token for the instance's guest agent external listener, minted - /// by the CVM at registration. Absent for a legacy CVM, which has no such - /// listener to authenticate against. + /// by the CVM at registration. Absent for a legacy CVM, whose listener + /// needs none. pub agent_token: Option, pub connections: Arc, } diff --git a/dstack/gateway/src/proxy/port_policy.rs b/dstack/gateway/src/proxy/port_policy.rs index a8573afdbe..bc8ce05d1a 100644 --- a/dstack/gateway/src/proxy/port_policy.rs +++ b/dstack/gateway/src/proxy/port_policy.rs @@ -217,41 +217,28 @@ async fn fetch_with_retry(state: &Proxy, instance_id: &str) { } async fn fetch_and_store(state: &Proxy, instance_id: &str) -> Result<(), FetchError> { - let (ip, agent_port, agent_token) = { + let (ip, agent_port) = { let guard = state.lock(); let ip = guard .instance_ip(instance_id) // Instance was recycled — never coming back under this id. .ok_or_else(|| FetchError::Permanent(anyhow::anyhow!("unknown instance")))?; - ( - ip, - guard.config.proxy.agent_port, - guard.instance_agent_token(instance_id), - ) + (ip, guard.config.proxy.agent_port) }; - let policy = fetch_port_policy(ip, agent_port, agent_token.as_deref()).await?; + let policy = fetch_port_policy(ip, agent_port).await?; state .lock() .update_instance_port_policy(instance_id, policy); Ok(()) } -async fn fetch_port_policy( - ip: Ipv4Addr, - agent_port: u16, - agent_token: Option<&str>, -) -> Result { +async fn fetch_port_policy(ip: Ipv4Addr, agent_port: u16) -> Result { let url = format!("http://{ip}:{agent_port}/prpc"); // Same untrusted peer as the health poller; see `guest_agent_client`. // Pooled, unlike the poller: this fills a cache rather than deciding // anything, it fires once per instance instead of on a timer, and a // connection that died while idle costs one retry of a lazy fetch. - let transport = super::guest_agent_client(url, ConnectionReuse::Pooled); - let transport = match agent_token { - Some(token) => transport.with_bearer_token(token), - None => transport, - }; - let client = DstackGuestClient::new(transport); + let client = DstackGuestClient::new(super::guest_agent_client(url, ConnectionReuse::Pooled)); // Network/RPC errors here are transient: agent might still be coming up. let info = client .info() diff --git a/dstack/guest-agent/Cargo.toml b/dstack/guest-agent/Cargo.toml index c0cff94d21..4d81c6172b 100644 --- a/dstack/guest-agent/Cargo.toml +++ b/dstack/guest-agent/Cargo.toml @@ -40,12 +40,12 @@ sysinfo.workspace = true default-net.workspace = true rocket-vsock-listener.workspace = true sd-notify.workspace = true +reqwest.workspace = true cmd_lib.workspace = true figment = { workspace = true, features = ["json", "toml"] } load_config.workspace = true k256 = { workspace = true, features = ["ecdsa"] } dstack-api-auth.workspace = true -http-client.workspace = true dstack-types.workspace = true sha3.workspace = true strip-ansi-escapes.workspace = true diff --git a/dstack/guest-agent/src/api_auth.rs b/dstack/guest-agent/src/api_auth.rs index 8dc31db4ac..907f6c0f47 100644 --- a/dstack/guest-agent/src/api_auth.rs +++ b/dstack/guest-agent/src/api_auth.rs @@ -14,14 +14,11 @@ //! it. What scopes decide is who may *ask* -- which the host configures, and //! which therefore cannot be part of the measurement. -use std::{ - sync::{Arc, OnceLock}, - time::{SystemTime, UNIX_EPOCH}, -}; +use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result}; use dstack_api_auth::jwt::{self, IssuerKeys, ScopeSet, Verifier}; -use dstack_types::{GuestAgentApiConfig, SysConfig}; +use dstack_types::GuestAgentApiConfig; use ed25519_dalek::VerifyingKey; use rocket::{ fairing::{Fairing, Info, Kind}, @@ -31,103 +28,77 @@ use rocket::{ }; use tracing::warn; +use crate::rpc_service::AppState; + /// What a caller may do on the external listener. #[derive(Clone)] pub struct GuestApiAuth { verifier: Verifier, anonymous: ScopeSet, - /// The app id every token must be bound to. Not known until the boot - /// attestation has been decoded: until then anonymous access still works, - /// but no token can be checked, so none is accepted. - app_id: Arc>, } impl GuestApiAuth { - /// Build from sys-config, given the app root key (if it parsed) and the - /// app id. + /// Build from sys-config's `guest_agent_api` block and the app root key. /// - /// `anonymous_scopes` is validated eagerly: a name outside the vocabulary - /// never matches anything, so a typo would otherwise read as "the host - /// asked for a permission that does not exist" only when someone could - /// not reach the dashboard. - pub fn new(config: Option<&GuestAgentApiConfig>, app_root_key: Option<&[u8]>) -> Result { + /// `anonymous_scopes` is validated eagerly so a typo is a boot error rather + /// than a permission that silently never matches. + pub fn new(config: Option<&GuestAgentApiConfig>, app_root_key: &[u8]) -> Result { let config = config.cloned().unwrap_or_default(); - let anonymous = ScopeSet::from_names(config.anonymous_scopes.iter().cloned()); - for name in config.anonymous_scopes { - if !jwt::scope::is_known(&name) { - anyhow::bail!("guest_agent_api: unknown anonymous scope {name:?}"); - } + if let Some(name) = config + .anonymous_scopes + .iter() + .find(|name| !jwt::scope::is_known(name)) + { + anyhow::bail!("guest_agent_api: unknown anonymous scope {name:?}"); } + let anonymous = ScopeSet::from_names(config.anonymous_scopes); - let internal = match app_root_key { - Some(root) => { - let secret = ra_tls::api_v1::derive_app_key( - root, - jwt::INTERNAL_ISSUER_DOMAIN, - ra_tls::api_v1::KeyAlgorithm::Ed25519, - ) - .context("failed to derive the internal issuer key")?; - Some(ed25519_dalek::SigningKey::from_bytes(&secret).verifying_key()) - } - None => None, - }; + let secret = ra_tls::api_v1::derive_app_key( + app_root_key, + jwt::INTERNAL_ISSUER_DOMAIN, + ra_tls::api_v1::KeyAlgorithm::Ed25519, + ) + .context("failed to derive the internal issuer key")?; + let internal = ed25519_dalek::SigningKey::from_bytes(&secret).verifying_key(); - let mut external = Vec::with_capacity(config.external_issuers.len()); - for issuer in config.external_issuers { - let mut keys = Vec::with_capacity(issuer.public_keys.len()); - for encoded in &issuer.public_keys { - let bytes = hex::decode(encoded) - .with_context(|| format!("issuer {:?}: public key is not hex", issuer.name))?; - let Ok(bytes): Result<[u8; 32], _> = bytes.try_into() else { - anyhow::bail!("issuer {:?}: public key must be 32 bytes", issuer.name); - }; - keys.push(VerifyingKey::from_bytes(&bytes).with_context(|| { - format!( - "issuer {:?}: public key is not a valid Ed25519 key", - issuer.name - ) - })?); - } - if keys.is_empty() { - warn!("issuer {:?} has no public keys", issuer.name); - } - external.push(IssuerKeys { - name: issuer.name, - keys, - }); - } + let external = config + .external_issuers + .into_iter() + .map(|issuer| { + let keys = issuer + .public_keys + .iter() + .map(|encoded| parse_public_key(encoded)) + .collect::>>() + .with_context(|| format!("issuer {:?}", issuer.name))?; + if keys.is_empty() { + warn!("issuer {:?} has no public keys", issuer.name); + } + Ok(IssuerKeys { + name: issuer.name, + keys, + }) + }) + .collect::>()?; Ok(Self { verifier: Verifier::new(internal, external), anonymous, - app_id: Arc::default(), }) } - /// Build from a sys-config file's contents. - pub fn from_sys_config(sys_config: &SysConfig, app_root_key: Option<&[u8]>) -> Result { - Self::new(sys_config.guest_agent_api.as_ref(), app_root_key) - } - - /// Bind tokens to `app_id`. Called once the boot attestation has been - /// decoded; a second call is ignored, since the value cannot change. - pub fn bind_app_id(&self, app_id: String) { - let _ = self.app_id.set(app_id); - } - /// The scopes a request carries, or `Err` when it presented a token that /// did not verify. /// /// A rejected token never falls back to anonymous: a caller that meant to /// authenticate and got it wrong should see a refusal, not whatever the - /// host happened to leave open. - fn resolve(&self, token: Option<&str>) -> Result { + /// host happened to leave open. `app_id` is `None` while the app identity + /// is unavailable, in which case no token can be checked. + fn resolve(&self, token: Option<&str>, app_id: Option<&str>) -> Result { let Some(token) = token else { return Ok(self.anonymous.clone()); }; - let Some(app_id) = self.app_id.get().map(String::as_str) else { - anyhow::bail!("no token can be accepted until the app identity is known"); - }; + let app_id = app_id.context("no token can be accepted until the app identity is known")?; let now = SystemTime::now() .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) @@ -140,11 +111,19 @@ impl GuestApiAuth { } } +fn parse_public_key(encoded: &str) -> Result { + let bytes: [u8; 32] = hex::decode(encoded) + .context("public key is not hex")? + .try_into() + .ok() + .context("public key must be 32 bytes")?; + VerifyingKey::from_bytes(&bytes).context("public key is not a valid Ed25519 key") +} + /// The scopes in force for one request, published by [`ScopeFairing`]. /// -/// A request guard rather than a fairing-only side effect because the -/// dashboard renders *parts* of itself by scope: it needs the set, not a -/// yes/no. +/// A request guard because the dashboard renders parts of itself by scope: it +/// needs the set, not a yes/no. pub struct EffectiveScopes(pub ScopeSet); impl EffectiveScopes { @@ -165,54 +144,58 @@ impl<'r> FromRequest<'r> for EffectiveScopes { } } -/// The scope a request to the external listener needs, or `None` when the -/// request names no scope at all (an unknown route, which the router answers). +/// The scope a request to the external listener needs, or `None` for a path +/// that names no known route. `None` is refused: the check fails closed, so a +/// spelling this function does not recognise can never reach a handler. /// -/// `/prpc` and `/prpc/v0` are the same frozen surface, and the frozen mounts -/// trim the `Worker.` prefix, so `/prpc/Worker.Info`, `/prpc/v0/Info` and -/// `/prpc/Info` are one route with three spellings. Normalising here is what -/// keeps a caller from picking the spelling whose check was forgotten. +/// Segments come from Rocket's own parser, because that is what the router +/// matches on: it percent-decodes and drops empty segments, so `/%70rpc/Info` +/// and `/prpc//Info` reach the same handler as `/prpc/Info`. /// -/// The segments come from Rocket's own parser rather than from the raw path, -/// because that is what the router matches on: it percent-decodes and drops -/// empty segments, so `/%70rpc/Info` and `/prpc//Info` reach the same handler -/// as `/prpc/Info`. Comparing raw strings would let those spellings through -/// unchecked. +/// The frozen mounts (`/prpc`, `/prpc/v0`) strip one `Worker.` prefix before +/// dispatch, exactly as here; `/prpc/v1` strips nothing. pub fn required_scope(path: &str) -> Option<&'static str> { let origin = Origin::parse(path).ok()?; let segments: Vec<&str> = origin.path().segments().filter(|s| !s.is_empty()).collect(); - match segments.as_slice() { - [] => Some(jwt::scope::DASHBOARD), - ["metrics"] => Some(jwt::scope::METRICS), - ["logs", ..] => Some(jwt::scope::LOGS), + let method = match segments.as_slice() { + [] => return Some(jwt::scope::DASHBOARD), + ["metrics"] => return Some(jwt::scope::METRICS), + ["logs", _] => return Some(jwt::scope::LOGS), + ["prpc", "v1", method] => *method, + ["prpc", "v0", method] | ["prpc", method] => { + method.strip_prefix("Worker.").unwrap_or(method) + } + _ => return None, + }; + match method { + "Version" => Some(jwt::scope::VERSION), + "Health" => Some(jwt::scope::HEALTH), + "Info" => Some(jwt::scope::INFO), + "GetAttestationForAppKey" => Some(jwt::scope::ATTEST_APP_KEY), _ => None, } - .or_else(|| { - let method = match segments.as_slice() { - ["prpc", method] | ["prpc", "v0" | "v1", method] => *method, - _ => return None, - }; - match method.strip_prefix("Worker.").unwrap_or(method) { - "Version" => Some(jwt::scope::VERSION), - "Health" => Some(jwt::scope::HEALTH), - "Info" => Some(jwt::scope::INFO), - "GetAttestationForAppKey" => Some(jwt::scope::ATTEST_APP_KEY), - _ => None, - } - }) } -/// Refuses a request whose caller lacks the scope it names. +/// Refuses a request whose caller lacks the scope its route needs. pub struct ScopeFairing { - auth: GuestApiAuth, + state: AppState, } impl ScopeFairing { - pub fn new(auth: GuestApiAuth) -> Self { - Self { auth } + pub fn new(state: AppState) -> Self { + Self { state } } } +/// The token from an `Authorization: Bearer` header. The scheme is +/// case-insensitive (RFC 9110 §11.1); any other scheme is no token at all. +fn bearer_token<'r>(req: &'r Request<'_>) -> Option<&'r str> { + let (scheme, token) = req.headers().get_one("Authorization")?.split_once(' ')?; + scheme + .eq_ignore_ascii_case("bearer") + .then_some(token.trim()) +} + #[rocket::async_trait] impl Fairing for ScopeFairing { fn info(&self) -> Info { @@ -223,33 +206,37 @@ impl Fairing for ScopeFairing { } async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) { - let path = req.uri().path().as_str(); - let token = req - .headers() - .get_one("Authorization") - .and_then(|value| value.strip_prefix("Bearer ")) - .map(str::trim); - let scopes = match self.auth.resolve(token) { + let token = bearer_token(req); + // Only a token needs the app id. Going through `identity()` rather + // than a value bound at startup is what lets a boot whose first decode + // failed recover: the retry is driven by the callers that need it. + let app_id = match token { + Some(_) => self + .state + .identity() + .await + .ok() + .map(|identity| hex::encode(&identity.app_id)), + None => None, + }; + let scopes = match self.state.api_auth().resolve(token, app_id.as_deref()) { Ok(scopes) => scopes, Err(err) => { warn!("{err:#}"); - deny(req); - return; + return deny(req); } }; - let denied = required_scope(path).is_some_and(|scope| !scopes.contains(scope)); - if denied { - deny(req); - return; + match required_scope(req.uri().path().as_str()) { + Some(scope) if scopes.contains(scope) => { + req.local_cache(|| Some(scopes)); + } + _ => deny(req), } - req.local_cache(|| Some(scopes)); } } fn deny(req: &mut Request<'_>) { - // `Bearer`, not the shared-token `Basic` default: the way to get in here is - // to present a token, and a client told to send Basic would send the wrong - // thing. + // `Bearer`, not the shared-token `Basic` default: the way in is a token. req.local_cache(|| dstack_api_auth::Challenge::Bearer); if let Ok(uri) = Origin::parse_owned(dstack_api_auth::UNAUTHORIZED_PATH.to_owned()) { req.set_uri(uri); @@ -283,7 +270,17 @@ mod tests { required_scope("/prpc/GetAttestationForAppKey"), Some(jwt::scope::ATTEST_APP_KEY) ); - assert_eq!(required_scope("/nope"), None); + // Fails closed: anything not named here is refused, including a + // second service prefix the dispatcher would not strip. + for path in [ + "/nope", + "/prpc/Worker.Worker.Info", + "/prpc/v0/Worker.Worker.Info", + "/prpc/v1/Worker.Health", + "/prpc/GetQuote", + ] { + assert_eq!(required_scope(path), None, "{path}"); + } // The router matches on decoded, non-empty segments, so these reach // the same handler and must not be able to slip past the check. @@ -299,15 +296,15 @@ mod tests { anonymous_scopes: anonymous.iter().map(|s| s.to_string()).collect(), external_issuers: vec![], }), - Some(&[7u8; 32]), + &[7u8; 32], ) .unwrap() } #[test] fn anonymous_grants_only_what_was_configured() { - assert!(auth(&[]).resolve(None).unwrap().is_empty()); - let scopes = auth(&["guest:version"]).resolve(None).unwrap(); + assert!(auth(&[]).resolve(None, None).unwrap().is_empty()); + let scopes = auth(&["guest:version"]).resolve(None, None).unwrap(); assert!(scopes.contains(jwt::scope::VERSION)); assert!(!scopes.contains(jwt::scope::INFO)); } @@ -315,7 +312,7 @@ mod tests { #[test] fn a_bad_token_is_refused_rather_than_downgraded_to_anonymous() { assert!(auth(&["guest:dashboard"]) - .resolve(Some("not-a-token")) + .resolve(Some("not-a-token"), Some("00")) .is_err()); } @@ -326,7 +323,7 @@ mod tests { anonymous_scopes: vec!["guest:everything".into()], external_issuers: vec![], }), - Some(&[7u8; 32]), + &[7u8; 32], ) .err() .expect("should reject"); diff --git a/dstack/guest-agent/src/config.rs b/dstack/guest-agent/src/config.rs index 1c090c0ea7..fb816f2f12 100644 --- a/dstack/guest-agent/src/config.rs +++ b/dstack/guest-agent/src/config.rs @@ -23,16 +23,9 @@ pub fn load_config_figment_with_default( load_config("dstack", default_config, config_file, true) } -/// Where one listener binds. -/// -/// The external listener states a port; the internal ones state a unix socket -/// path. Deserialized as a whole rather than per field so a typo in either is -/// a startup error instead of a listener that silently binds elsewhere. -#[derive(Debug, Clone, Deserialize)] -pub struct SocketAddr { - pub address: String, - #[serde(default)] - pub port: Option, +#[derive(Debug, Clone, Copy, Deserialize)] +pub struct BindAddr { + pub port: u16, } #[derive(Debug, Clone)] diff --git a/dstack/guest-agent/src/rpc_service.rs b/dstack/guest-agent/src/rpc_service.rs index a180c0c5a9..a6dcd8e5fb 100644 --- a/dstack/guest-agent/src/rpc_service.rs +++ b/dstack/guest-agent/src/rpc_service.rs @@ -281,11 +281,11 @@ impl AppState { config.app_compose.runner.clone(), ) }); - // Built before the state so a bad `guest_agent_api` block is a boot - // error: an unknown scope name would otherwise silently grant nothing. + // A bad `guest_agent_api` block is a boot error: an unknown scope name + // would otherwise silently grant nothing. let api_auth = - crate::api_auth::GuestApiAuth::from_sys_config(&sys_config, Some(&keys.k256_key)) - .context("Failed to set up guest API access control")?; + crate::api_auth::GuestApiAuth::new(sys_config.guest_agent_api.as_ref(), &keys.k256_key) + .context("failed to set up guest API access control")?; // Parsed once, and non-fatally: an unusable app root key is reported by // the RPCs that need one, not by refusing to start. let app_root_signing_key = match SigningKey::from_slice(&keys.k256_key) { @@ -418,16 +418,6 @@ impl AppState { self.inner .attest(decode_identity) .await - // External tokens are bound to the app id, which only the - // boot attestation can supply. Binding here rather than at - // startup covers the retry path too: until it lands the - // listener serves anonymous callers and refuses every - // token. - .inspect(|identity| { - self.inner - .api_auth - .bind_app_id(hex::encode(&identity.app_id)); - }) .inspect_err(|_| { *last_failure.lock().or_panic("lock should never fail") = Some(Instant::now()); @@ -1126,6 +1116,12 @@ pub(crate) mod tests { use std::io::Write; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + pub(crate) const DUMMY_K256_KEY: [u8; 32] = [ + 0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F, 0x7A, 0x8B, 0x9C, 0x0D, 0x1E, 0x2F, 0x3A, 0x4B, 0x5C, + 0x6D, 0x7E, 0x8F, 0x9A, 0x0B, 0x1C, 0x2D, 0x3E, 0x4F, 0x5A, 0x6B, 0x7C, 0x8D, 0x9E, 0x0F, + 0x1A, 0x2B, + ]; + fn extract_pubkey_from_report_data(report_data: &[u8], prefix: &str) -> Result> { let end = report_data .iter() @@ -1352,12 +1348,6 @@ pNs85uhOZE8z2jr8Pg== -----END CERTIFICATE----- "#; - const DUMMY_K256_KEY: [u8; 32] = [ - 0x1A, 0x2B, 0x3C, 0x4D, 0x5E, 0x6F, 0x7A, 0x8B, 0x9C, 0x0D, 0x1E, 0x2F, 0x3A, 0x4B, - 0x5C, 0x6D, 0x7E, 0x8F, 0x9A, 0x0B, 0x1C, 0x2D, 0x3E, 0x4F, 0x5A, 0x6B, 0x7C, 0x8D, - 0x9E, 0x0F, 0x1A, 0x2B, - ]; - let dummy_keys = AppKeys { disk_crypt_key: Vec::new(), env_crypt_key: Vec::new(), @@ -1486,7 +1476,7 @@ pNs85uhOZE8z2jr8Pg== // against v0 `get_info` compares like with like. cloud_vendor: read_dmi_file("sys_vendor"), cloud_product: read_dmi_file("product_name"), - api_auth: crate::api_auth::GuestApiAuth::new(None, Some(&DUMMY_K256_KEY)).unwrap(), + api_auth: crate::api_auth::GuestApiAuth::new(None, &DUMMY_K256_KEY).unwrap(), }; ( diff --git a/dstack/guest-agent/src/server.rs b/dstack/guest-agent/src/server.rs index 7a02500cde..4590cc82f4 100644 --- a/dstack/guest-agent/src/server.rs +++ b/dstack/guest-agent/src/server.rs @@ -5,7 +5,7 @@ use std::{future::pending, os::unix::net::UnixListener as StdUnixListener, time::Duration}; use crate::api_auth::ScopeFairing; -use crate::config::SocketAddr; +use crate::config::BindAddr; use crate::guest_api_service::GuestApiHandler; use crate::http_routes; use crate::rpc_service::{AppState, ExternalRpcHandler, InternalRpcHandler, InternalRpcHandlerV0}; @@ -178,13 +178,11 @@ async fn run_internal( } async fn run_external(state: AppState, figment: Figment) -> Result<()> { - let scopes = ScopeFairing::new(state.api_auth().clone()); let rocket = mount_external(rocket::custom(figment)) .mount("/", http_routes::external_routes(state.config())) - // Mounted first so a denied request has somewhere to land that is not - // itself behind the check. + // Where `ScopeFairing` rewrites a denied request. .mount("/", dstack_api_auth::routes()) - .attach(scopes) + .attach(ScopeFairing::new(state.clone())) .attach(AdHoc::on_response("Add app version header", |_req, res| { Box::pin(async move { res.set_raw_header("X-App-Version", app_version()); @@ -226,14 +224,7 @@ async fn run_guest_api(state: AppState, figment: Figment) -> Result<()> { Ok(()) } -/// Probe the internal socket, not the external listener. -/// -/// The external listener now refuses anonymous callers by default, so probing -/// it would report the agent dead whenever the host configured no anonymous -/// scope. The unix socket is the surface that cannot depend on that: it is -/// local-only, unauthenticated, and always mounted. It also answers with the -/// same `Version` the port probe asked for. -async fn run_watchdog(socket_path: String) { +async fn run_watchdog(port: u16) { let mut watchdog_usec = 0; let enabled = sd_notify::watchdog_enabled(false, &mut watchdog_usec); if !enabled { @@ -250,17 +241,24 @@ async fn run_watchdog(socket_path: String) { info!("Watchdog enabled, interval={watchdog_usec}us, heartbeat={heatbeat_interval:?}"); let mut interval = tokio::time::interval(heatbeat_interval); + let probe_url = format!("http://localhost:{port}/prpc/Worker.Version"); loop { interval.tick().await; - match http_client::http_request("GET", &socket_path, "/Version", &[]).await { - Ok((status, _)) if (200..300).contains(&status) => { + let client = reqwest::Client::new(); + match client.get(&probe_url).send().await { + // 401 is the listener answering a caller with no scope, which is + // the default; it proves the listener is up as well as a 200. + Ok(response) + if response.status().is_success() + || response.status() == reqwest::StatusCode::UNAUTHORIZED => + { if let Err(err) = sd_notify(false, &[NotifyState::Watchdog]) { error!("Failed to notify systemd: {err}"); } } - Ok((status, _)) => { - error!("Health check failed with status: {status}"); + Ok(response) => { + error!("Health check failed with status: {}", response.status()); } Err(err) => { error!("Health check request failed: {err:?}"); @@ -273,12 +271,11 @@ pub async fn run(state: AppState, figment: Figment, watchdog: bool) -> Result<() let internal_v0_figment = figment.clone().select("internal-v0"); let internal_figment = figment.clone().select("internal"); let external_figment = figment.clone().select("external"); - let watchdog_socket = if watchdog { + let bind_addr = if watchdog { Some( - internal_figment - .extract::() - .context("Failed to extract the internal socket address")? - .address, + external_figment + .extract::() + .context("Failed to extract bind address")?, ) } else { None @@ -300,8 +297,8 @@ pub async fn run(state: AppState, figment: Figment, watchdog: bool) -> Result<() _ = async { let _ = tappd_ready_rx.await; let _ = sock_ready_rx.await; - if let Some(socket_path) = watchdog_socket { - run_watchdog(socket_path).await; + if let Some(bind_addr) = bind_addr { + run_watchdog(bind_addr.port).await; } else { pending::<()>().await; } @@ -437,4 +434,73 @@ mod tests { let (status, _) = get(&pre_v1, "/EmitEvent").await; assert_eq!(status, 400); } + + /// With nothing anonymous, no spelling of a route reaches a handler + /// without a token. + #[tokio::test] + async fn the_external_listener_refuses_every_spelling_without_a_token() { + let (state, _guard) = setup_test_state().await; + let client = Client::tracked( + mount_external(rocket::build()) + .mount("/", dstack_api_auth::routes()) + .attach(ScopeFairing::new(state.clone())) + .manage(state), + ) + .await + .expect("rocket failed to ignite"); + for path in [ + "/prpc/Info", + "/prpc/Worker.Worker.Info", + "/prpc/v0/Worker.Worker.GetAttestationForAppKey", + "/%70rpc/Version", + "/prpc/v1/Health", + "/nope", + ] { + let (status, _) = get(&client, path).await; + assert_eq!(status, 401, "{path}"); + } + } + + /// A token from the app's own issuer opens exactly its scopes. + #[tokio::test] + async fn an_internal_token_grants_only_its_own_scopes() { + use dstack_api_auth::jwt; + + let (state, _guard) = setup_test_state().await; + let app_id = hex::encode(&state.identity().await.unwrap().app_id); + let secret = ra_tls::api_v1::derive_app_key( + &crate::rpc_service::tests::DUMMY_K256_KEY, + jwt::INTERNAL_ISSUER_DOMAIN, + ra_tls::api_v1::KeyAlgorithm::Ed25519, + ) + .unwrap(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let token = jwt::sign( + &secret, + &jwt::Claims { + iss: jwt::internal_issuer(&app_id), + aud: app_id, + iat: now, + exp: now + 60, + scope: jwt::scope::INFO.into(), + }, + ) + .unwrap(); + let client = Client::tracked( + mount_external(rocket::build()) + .mount("/", dstack_api_auth::routes()) + .attach(ScopeFairing::new(state.clone())) + .manage(state), + ) + .await + .expect("rocket failed to ignite"); + let auth = rocket::http::Header::new("Authorization", format!("bearer {token}")); + for (path, expected) in [("/prpc/Info", 200), ("/prpc/Version", 401)] { + let response = client.get(path).header(auth.clone()).dispatch().await; + assert_eq!(response.status().code, expected, "{path}"); + } + } } diff --git a/dstack/ra-rpc/src/rocket_helper.rs b/dstack/ra-rpc/src/rocket_helper.rs index b17dce88c9..b3b93d6a9d 100644 --- a/dstack/ra-rpc/src/rocket_helper.rs +++ b/dstack/ra-rpc/src/rocket_helper.rs @@ -527,7 +527,9 @@ pub async fn handle_prpc_impl>( method_trim_prefix, data, } = args; - let method = method.trim_start_matches(method_trim_prefix.unwrap_or_default()); + let method = method + .strip_prefix(method_trim_prefix.unwrap_or_default()) + .unwrap_or(method); let is_json = request.wants_json(); let info = request .certificate From 47587d5ebb8ffda6b9c89512e90f347fa99b3de2 Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 19:30:35 +0800 Subject: [PATCH 041/572] chore(kms): bump auth-mock to Bun 1.4.4 for emSign distrust Bun 1.4.3 still accepts certificate chains from the distrusted eMudhra/emSign intermediates. Bun 1.4.4 updates its root store to NSS 3.131.1 and blocks the affected public keys, so fetch() rejects such chains with CERT_REVOKED. Move auth-mock from oven/bun:1.4.3-alpine to oven/bun:1.4.4-alpine, pinned by the multi-arch index digest. Signed-off-by: Leechael Yim --- dstack/kms/auth-mock/Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dstack/kms/auth-mock/Dockerfile b/dstack/kms/auth-mock/Dockerfile index d0d36e5958..75ecb51873 100644 --- a/dstack/kms/auth-mock/Dockerfile +++ b/dstack/kms/auth-mock/Dockerfile @@ -2,7 +2,7 @@ # # SPDX-License-Identifier: Apache-2.0 -FROM oven/bun:1.4.3-alpine@sha256:629e17411f1f129dbec3af78d5af9c9f2a937435c80349437206c6b0b7422373 +FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a WORKDIR /app ARG DSTACK_REV From b29cea45f5b605900b2171bcdbf8dbbfa32d35ab Mon Sep 17 00:00:00 2001 From: Leechael Yim Date: Thu, 22 Oct 2026 19:33:07 +0800 Subject: [PATCH 042/572] chore(kms): bump auth-eth-bun to Bun 1.4.4 for emSign distrust Bun 1.4.2 still accepts certificate chains from the distrusted eMudhra/emSign intermediates. Bun 1.4.4 is the first stable release whose bundled root store is NSS 3.131.1 with the affected public keys blocked, so fetch() rejects such chains with CERT_REVOKED. Move both Dockerfile stages from oven/bun:1.4.2-alpine to oven/bun:1.4.4-alpine, pinned by the multi-arch index digest, and set the release workflow's bun-version to 1.4.4 to match. Signed-off-by: Leechael Yim --- .github/workflows/kms-auth-eth-bun.yml | 2 +- dstack/kms/auth-eth-bun/Dockerfile | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/kms-auth-eth-bun.yml b/.github/workflows/kms-auth-eth-bun.yml index 41049365e2..bd2d946556 100644 --- a/.github/workflows/kms-auth-eth-bun.yml +++ b/.github/workflows/kms-auth-eth-bun.yml @@ -50,7 +50,7 @@ jobs: uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 with: # Keep in step with the base image in the Dockerfile. - bun-version: 1.4.2 + bun-version: 1.4.4 # A release build must not restore a cache an untrusted run wrote. no-cache: true diff --git a/dstack/kms/auth-eth-bun/Dockerfile b/dstack/kms/auth-eth-bun/Dockerfile index b39c94c757..e5e96bae2b 100644 --- a/dstack/kms/auth-eth-bun/Dockerfile +++ b/dstack/kms/auth-eth-bun/Dockerfile @@ -4,12 +4,12 @@ # Built from this directory, so the image carries exactly the checked-out # source and lockfile rather than a clone fetched at build time. -FROM oven/bun:1.4.2-alpine@sha256:d888c0ae6c86d7866ff10c5aafdd9077b36aee6455b33dd270fb93c0dd5cef6f AS deps +FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a AS deps WORKDIR /app COPY package.json bun.lock ./ RUN bun install --frozen-lockfile --production --ignore-scripts -FROM oven/bun:1.4.2-alpine@sha256:d888c0ae6c86d7866ff10c5aafdd9077b36aee6455b33dd270fb93c0dd5cef6f +FROM oven/bun:1.4.4-alpine@sha256:4cf82f5686b196504fe119db3fcd9185b191f82ece82c40680e597228ec6070a WORKDIR /app COPY --from=deps /app/node_modules ./node_modules COPY package.json index.ts ./ From 476cd6b202c32f1e2c24815abce3f2ae06a701d2 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Thu, 22 Oct 2026 19:02:41 -0700 Subject: [PATCH 043/572] guest-agent: refuse a malformed token before paying for identity The scope fairing resolved the app id before looking at the token, so any string in an Authorization header could drive a boot attestation and queue behind attest_lock. Split `jwt::decode` out of `Verifier::verify` so the fairing reads the header and claims first, and only then asks for the app id. `verify_decoded` checks the signature before the claims: a claim error from an unsigned token describes a guess at the caller's intent, not the token. Also: - the dashboard skips `Worker.Info` unless a block would render it, so an anonymous page view no longer costs an attestation; - the watchdog builds one HTTP client instead of one per heartbeat; - `EffectiveScopes` answers 401, not 403, when the fairing published nothing; - the gateway drops an `agent_token` longer than 4 KiB with a warning: it is self-declared, persisted and synced, and must not be sized by the CVM. Co-Authored-By: Claude Code Signed-off-by: Kevin Wang --- dstack/crates/api-auth/src/jwt.rs | 125 +++++++++++++++++++------- dstack/gateway/src/main_service.rs | 30 ++++++- dstack/guest-agent/src/api_auth.rs | 53 +++++++++-- dstack/guest-agent/src/http_routes.rs | 21 +++-- dstack/guest-agent/src/models.rs | 53 +++++++++++ dstack/guest-agent/src/server.rs | 8 +- dstack/ra-rpc/tests/status_codes.rs | 11 +++ 7 files changed, 253 insertions(+), 48 deletions(-) diff --git a/dstack/crates/api-auth/src/jwt.rs b/dstack/crates/api-auth/src/jwt.rs index 6f13599810..855af31508 100644 --- a/dstack/crates/api-auth/src/jwt.rs +++ b/dstack/crates/api-auth/src/jwt.rs @@ -145,6 +145,48 @@ pub fn internal_issuer(app_id_hex: &str) -> String { format!("dstack:guest-api:{app_id_hex}") } +/// A token whose shape and claims have been read, with the signature still +/// unchecked. +/// +/// Split out from verification so a caller can refuse a malformed token before +/// it does anything expensive. The guest agent needs exactly that: checking a +/// token it was handed must not cost a boot attestation. +#[derive(Clone, Debug)] +pub struct Decoded { + signing_input: String, + signature: Vec, + pub claims: Claims, +} + +/// Read a token's header and claims without verifying it. +/// +/// Everything here is cheap and local. The result says nothing about whether +/// the token was signed by anyone; [`Verifier::verify_decoded`] answers that. +pub fn decode(token: &str) -> Result { + let mut parts = token.split('.'); + let (Some(header), Some(encoded_payload), Some(encoded_signature), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + bail!("token is not a JWT"); + }; + if header != HEADER { + // Covers `alg: none`, HMAC, and any header carrying key material. + bail!("unsupported JWT header"); + } + let payload = URL_SAFE_NO_PAD + .decode(encoded_payload) + .context("payload is not base64url")?; + let claims = serde_json::from_slice(&payload).context("malformed claims")?; + let signature = URL_SAFE_NO_PAD + .decode(encoded_signature) + .context("signature is not base64url")?; + Ok(Decoded { + signing_input: format!("{header}.{encoded_payload}"), + signature, + claims, + }) +} + /// Mint a token. `signing_key` is the raw 32-byte Ed25519 seed. pub fn sign(signing_key: &[u8; 32], claims: &Claims) -> Result { let payload = serde_json::to_vec(claims).context("failed to serialize claims")?; @@ -184,20 +226,37 @@ impl Verifier { /// `now` is seconds since the UNIX epoch, passed in rather than read here /// so the expiry rules can be tested. pub fn verify(&self, token: &str, app_id_hex: &str, now: u64) -> Result { - let mut parts = token.split('.'); - let (Some(header), Some(encoded_payload), Some(signature), None) = - (parts.next(), parts.next(), parts.next(), parts.next()) - else { - bail!("token is not a JWT"); - }; - if header != HEADER { - // Covers `alg: none`, HMAC, and any header carrying key material. - bail!("unsupported JWT header"); + self.verify_decoded(&decode(token)?, app_id_hex, now) + } + + /// Check the signature and claims of a token [`decode`] already read. + /// + /// Separate from [`Verifier::verify`] so a caller can pay for [`decode`] + /// alone -- it needs no key material and no app id -- and refuse the token + /// before doing anything that costs. + /// + /// The signature is checked before the claims: a claim error from an + /// unsigned token is a guess about a caller's intent, not a fact. + pub fn verify_decoded(&self, token: &Decoded, app_id_hex: &str, now: u64) -> Result { + let Decoded { + signing_input, + signature, + claims, + } = token; + let signature = + Signature::from_slice(signature).context("signature has the wrong length")?; + + let keys = self.keys_for(&claims.iss, app_id_hex); + if keys.is_empty() { + bail!("unknown token issuer"); + } + if !keys.iter().any(|key| { + key.verify_strict(signing_input.as_bytes(), &signature) + .is_ok() + }) { + bail!("token signature does not verify"); } - let payload = URL_SAFE_NO_PAD - .decode(encoded_payload) - .context("payload is not base64url")?; - let claims: Claims = serde_json::from_slice(&payload).context("malformed claims")?; + if claims.aud != app_id_hex { bail!("token was issued for a different application"); } @@ -210,23 +269,6 @@ impl Verifier { if claims.iat > now + CLOCK_LEEWAY_SECS { bail!("token was issued in the future"); } - let signature = URL_SAFE_NO_PAD - .decode(signature) - .context("signature is not base64url")?; - let signature = - Signature::from_slice(&signature).context("signature has the wrong length")?; - let signing_input = format!("{header}.{encoded_payload}"); - - let keys = self.keys_for(&claims.iss, app_id_hex); - if keys.is_empty() { - bail!("unknown token issuer"); - } - if !keys.iter().any(|key| { - key.verify_strict(signing_input.as_bytes(), &signature) - .is_ok() - }) { - bail!("token signature does not verify"); - } Ok(claims.scopes()) } @@ -353,6 +395,29 @@ mod tests { assert!(verifier(1).verify(&future, APP_ID, 1000).is_err()); } + #[test] + fn decoding_refuses_a_shape_no_token_could_have() { + for token in [ + "not-a-token", + "a.b.c.d", + "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJpc3MiOiJ4In0.", + "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.!!!.c2ln", + ] { + assert!(decode(token).is_err(), "{token}"); + } + // A well-formed token decodes without any key: that is what lets the + // caller refuse it before doing work. + let token = mint( + 1, + &internal_issuer(APP_ID), + APP_ID, + 1000, + 1300, + "guest:info", + ); + assert_eq!(decode(&token).unwrap().claims.aud, APP_ID); + } + #[test] fn accepts_an_external_issuer_by_name() { let verifier = Verifier::new( diff --git a/dstack/gateway/src/main_service.rs b/dstack/gateway/src/main_service.rs index 7c931a4306..1761fe84e3 100644 --- a/dstack/gateway/src/main_service.rs +++ b/dstack/gateway/src/main_service.rs @@ -2757,6 +2757,33 @@ fn gateway_nodes(kv_store: &KvStore, exclude_down: bool) -> Vec .collect() } +/// Longest `agent_token` a registration may carry. +/// +/// The token is a short Ed25519 JWT -- a few hundred bytes. The field is +/// self-declared, persisted, synced to every peer and sent back out as a +/// request header, so it is bounded here rather than trusted. +const MAX_AGENT_TOKEN_BYTES: usize = 4096; + +/// The `agent_token` a registration may store, or `None`. +/// +/// Absent and empty both mean "this CVM has no token", which is what a CVM +/// that predates the field or could not mint one reports. A value past +/// [`MAX_AGENT_TOKEN_BYTES`] is not a token at all: it is dropped with a +/// warning rather than stored, so one CVM cannot inflate every record. +fn validated_agent_token(instance_id: &str, token: Option) -> Option { + match token { + Some(token) if token.len() > MAX_AGENT_TOKEN_BYTES => { + warn!( + "[{instance_id}] ignoring an agent token of {} bytes (limit {MAX_AGENT_TOKEN_BYTES})", + token.len() + ); + None + } + Some(token) if token.is_empty() => None, + token => token, + } +} + pub struct RpcHandler { remote_app_id: Option>, remote_app_info: Option, @@ -2817,6 +2844,7 @@ impl GatewayRpc for RpcHandler { }) }) .transpose()?; + let agent_token = validated_agent_token(&instance_id, request.agent_token); self.state .register_cvm_async( app_id, @@ -2827,7 +2855,7 @@ impl GatewayRpc for RpcHandler { port_policy, // A real CVM always states its intent, either way. health_check: Some(request.health_check), - agent_token: request.agent_token.filter(|token| !token.is_empty()), + agent_token, }, ) .await diff --git a/dstack/guest-agent/src/api_auth.rs b/dstack/guest-agent/src/api_auth.rs index 907f6c0f47..f247a5a229 100644 --- a/dstack/guest-agent/src/api_auth.rs +++ b/dstack/guest-agent/src/api_auth.rs @@ -6,7 +6,7 @@ //! //! Every request that reaches `[external]` names a scope, and the caller has //! to be granted it: either by an Ed25519 JWT, or -- when the host configured -//! it -- by being anonymous. Nothing is granted by default. +//! it -- by being anonymous. Nothing is granted without one or the other. //! //! This is deliberately not a trust boundary. The measured `public_*` switches //! in app-compose still decide whether confidential data (logs, sysinfo, TCB @@ -17,7 +17,7 @@ use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result}; -use dstack_api_auth::jwt::{self, IssuerKeys, ScopeSet, Verifier}; +use dstack_api_auth::jwt::{self, Decoded, IssuerKeys, ScopeSet, Verifier}; use dstack_types::GuestAgentApiConfig; use ed25519_dalek::VerifyingKey; use rocket::{ @@ -94,7 +94,7 @@ impl GuestApiAuth { /// authenticate and got it wrong should see a refusal, not whatever the /// host happened to leave open. `app_id` is `None` while the app identity /// is unavailable, in which case no token can be checked. - fn resolve(&self, token: Option<&str>, app_id: Option<&str>) -> Result { + fn resolve(&self, token: Option<&Decoded>, app_id: Option<&str>) -> Result { let Some(token) = token else { return Ok(self.anonymous.clone()); }; @@ -105,7 +105,7 @@ impl GuestApiAuth { .unwrap_or(0); let granted = self .verifier - .verify(token, app_id, now) + .verify_decoded(token, app_id, now) .context("rejected bearer token")?; Ok(self.anonymous.union(&granted)) } @@ -139,7 +139,11 @@ impl<'r> FromRequest<'r> for EffectiveScopes { async fn from_request(request: &'r Request<'_>) -> Outcome { match request.local_cache(|| None::) { Some(scopes) => Outcome::Success(EffectiveScopes(scopes.clone())), - None => Outcome::Forward(rocket::http::Status::Forbidden), + // Unreachable: `ScopeFairing` either publishes a set or rewrites + // the request to the 401 route. Kept as a 401 rather than a 403 so + // a request that somehow got past the fairing still looks like + // every other refusal. + None => Outcome::Error((rocket::http::Status::Unauthorized, ())), } } } @@ -206,7 +210,17 @@ impl Fairing for ScopeFairing { } async fn on_request(&self, req: &mut Request<'_>, _: &mut Data<'_>) { - let token = bearer_token(req); + // Read the token's shape first. It is the only cheap step, and it is + // the one an unauthenticated caller can drive; the app id lookup below + // can cost a boot attestation, so nothing that arrives here gets that + // far unless it is at least a well-formed Ed25519 token. + let token = match bearer_token(req).map(jwt::decode).transpose() { + Ok(token) => token, + Err(err) => { + tracing::debug!("{err:#}"); + return deny(req); + } + }; // Only a token needs the app id. Going through `identity()` rather // than a value bound at startup is what lets a boot whose first decode // failed recover: the retry is driven by the callers that need it. @@ -219,10 +233,16 @@ impl Fairing for ScopeFairing { .map(|identity| hex::encode(&identity.app_id)), None => None, }; - let scopes = match self.state.api_auth().resolve(token, app_id.as_deref()) { + let scopes = match self + .state + .api_auth() + .resolve(token.as_ref(), app_id.as_deref()) + { Ok(scopes) => scopes, Err(err) => { - warn!("{err:#}"); + // Every caller on the internet reaches this. A warning per + // attempt is a log the public gets to size. + tracing::debug!("{err:#}"); return deny(req); } }; @@ -301,6 +321,13 @@ mod tests { .unwrap() } + /// Stands in for a token that is well-formed but not signed by anything + /// this agent trusts. + fn decoded(claims: jwt::Claims) -> Decoded { + let token = jwt::sign(&[1u8; 32], &claims).unwrap(); + jwt::decode(&token).unwrap() + } + #[test] fn anonymous_grants_only_what_was_configured() { assert!(auth(&[]).resolve(None, None).unwrap().is_empty()); @@ -311,8 +338,16 @@ mod tests { #[test] fn a_bad_token_is_refused_rather_than_downgraded_to_anonymous() { + let claims = jwt::Claims { + iss: jwt::internal_issuer("00"), + aud: "00".into(), + iat: 0, + exp: u64::MAX / 2, + scope: jwt::scope::DASHBOARD.into(), + }; + // Signed by the wrong key, so it decodes and fails to verify. assert!(auth(&["guest:dashboard"]) - .resolve(Some("not-a-token"), Some("00")) + .resolve(Some(&decoded(claims)), Some("00")) .is_err()); } diff --git a/dstack/guest-agent/src/http_routes.rs b/dstack/guest-agent/src/http_routes.rs index 4a09aac90a..dc59c674ae 100644 --- a/dstack/guest-agent/src/http_routes.rs +++ b/dstack/guest-agent/src/http_routes.rs @@ -51,8 +51,11 @@ async fn index( let show_logs = public_logs && scopes.allows(jwt::scope::LOGS); let show_tcb = public_tcbinfo && show_identity; let context = CallContext::builder().state(&**state).build(); - let handler = ExternalRpcHandler::construct(context.clone()) - .map_err(|e| format!("Failed to construct RPC handler: {}", e))?; + // `Info` costs a boot attestation (and may start a demo-cert request), so + // it is only asked for when the identity block -- and with it the TCB + // block, which requires `guest:info` too -- will be rendered. + // `guest:dashboard` is the one scope an anonymous visitor is most likely + // to be given, and on its own it renders every block hidden. let AppInfo { app_name, app_id, @@ -67,10 +70,16 @@ async fn index( vm_config: _, cloud_vendor, cloud_product, - } = handler - .info() - .await - .map_err(|e| format!("Failed to get worker info: {}", e))?; + } = if show_identity || show_tcb { + let handler = ExternalRpcHandler::construct(context.clone()) + .map_err(|e| format!("Failed to construct RPC handler: {}", e))?; + handler + .info() + .await + .map_err(|e| format!("Failed to get worker info: {}", e))? + } else { + Default::default() + }; // Only collected when the page will actually render it. Collecting // otherwise would scan every process and disk, and spawn a GPU collector, diff --git a/dstack/guest-agent/src/models.rs b/dstack/guest-agent/src/models.rs index 89f9624cc7..7b86f599c7 100644 --- a/dstack/guest-agent/src/models.rs +++ b/dstack/guest-agent/src/models.rs @@ -410,6 +410,59 @@ mod tests { assert!(body.contains("system_load_average_1m 0.40"), "{body}"); } + /// A caller granted only `guest:dashboard` gets the page and nothing on + /// it. Each block is guarded independently, so a missing guard shows up as + /// data in an otherwise empty document rather than as a stray heading. + #[test] + fn a_dashboard_granted_no_block_renders_none_of_them() { + let (app_id, instance_id, device_id) = ([0xd3u8; 32], [0xe5u8; 32], [0xf7u8; 32]); + let html = Dashboard { + app_name: "secret-app".into(), + app_id: app_id.to_vec(), + instance_id: instance_id.to_vec(), + device_id: device_id.to_vec(), + key_provider_info: "secret-kms".into(), + tcb_info: "secret-tcb".into(), + containers: vec![Container { + names: vec!["secret-container".into()], + status: "running".into(), + ..Default::default() + }], + system_info: SystemInfo { + os_name: "secret-os".into(), + cpu_model: "secret-cpu".into(), + ..Default::default() + }, + show_identity: false, + show_sysinfo: false, + show_containers: false, + show_logs: false, + show_tcb: false, + cloud_vendor: "secret-vendor".into(), + cloud_product: "secret-product".into(), + gpu_info: Default::default(), + } + .render() + .expect("render"); + for hidden in [ + "secret-app".to_owned(), + hex::encode(app_id), + hex::encode(instance_id), + hex::encode(device_id), + "secret-kms".into(), + "secret-tcb".into(), + "secret-container".into(), + "secret-os".into(), + "secret-cpu".into(), + "secret-vendor".into(), + "Deployed Containers".into(), + "TCB Info".into(), + "Node Information".into(), + ] { + assert!(!html.contains(&hidden), "{hidden} leaked into {html}"); + } + } + fn dashboard_with(gpu_info: GpuInfoResponse) -> String { Dashboard { app_name: String::new(), diff --git a/dstack/guest-agent/src/server.rs b/dstack/guest-agent/src/server.rs index 4590cc82f4..77fb6214ac 100644 --- a/dstack/guest-agent/src/server.rs +++ b/dstack/guest-agent/src/server.rs @@ -242,13 +242,17 @@ async fn run_watchdog(port: u16) { let mut interval = tokio::time::interval(heatbeat_interval); let probe_url = format!("http://localhost:{port}/prpc/Worker.Version"); + // Built once: the loop runs every few seconds for the process's lifetime, + // and a fresh client per tick leaks a connection pool each time. + let client = reqwest::Client::new(); loop { interval.tick().await; - let client = reqwest::Client::new(); match client.get(&probe_url).send().await { // 401 is the listener answering a caller with no scope, which is - // the default; it proves the listener is up as well as a 200. + // what happens when the host removes `guest:version` from + // `anonymous_scopes`; it proves the listener is up as well as a + // 200 does. Ok(response) if response.status().is_success() || response.status() == reqwest::StatusCode::UNAUTHORIZED => diff --git a/dstack/ra-rpc/tests/status_codes.rs b/dstack/ra-rpc/tests/status_codes.rs index 1ce44f467a..80e12f74ce 100644 --- a/dstack/ra-rpc/tests/status_codes.rs +++ b/dstack/ra-rpc/tests/status_codes.rs @@ -143,6 +143,17 @@ async fn an_unknown_method_is_reported_as_not_found() { assert!(body.contains("Service not found: NoSuchMethod"), "{body}"); } +#[tokio::test] +async fn a_repeated_service_prefix_is_not_stripped() { + // Exactly one prefix goes, so a caller cannot spell `Echo` in a path the + // routes do not name -- a front-end that keys a check on the route would + // otherwise let the request through. + let client = client().await; + let (status, body) = post(&client, "Demo.Demo.Echo", r#"{"text":"hello"}"#).await; + assert_eq!(status, 404, "{body}"); + assert!(body.contains("Service not found: Demo.Echo"), "{body}"); +} + #[tokio::test] async fn a_malformed_body_is_reported_as_a_bad_request() { let client = client().await; From 2d75cd1956d1bdcf208fedce4929d24672d83704 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Thu, 22 Oct 2026 19:02:43 -0700 Subject: [PATCH 044/572] guest-agent: document where anonymous scopes are configured There is no built-in anonymous default, so the sample configs are the only place a host learns what to open. Fill in `[cvm.guest_agent_api]` in the shipped `vmm.toml`, in the `dstackup install` renderer, and in the two dev/test stacks with what an unconfigured 8090 used to serve: the dashboard plus the identity, version and health it publishes. Co-Authored-By: Claude Code Signed-off-by: Kevin Wang --- CHANGELOG.md | 2 +- docs/guest-api-auth.md | 50 +++++++++++++++---- dstack/crates/dstack-cli-core/src/config.rs | 6 +++ dstack/dstack-types/src/lib.rs | 7 +-- dstack/vmm/vmm.toml | 29 ++++++----- .../scripts/render-config.sh | 3 ++ tools/dev-stack.sh | 4 ++ 7 files changed, 75 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b2a077738..d7c01b43a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - guest: a fresh CVM with a verity volume could take the volume for its data disk and try to LUKS-format it: volumes labelled their data partition `dstack-data`, the data disk's label. `dstack verity` now labels it `dstack-volume-data`, and the guest skips disks that carry a `dstack-volume` partition, so volumes built by older releases are safe too ### Changed -- guest-agent: the external listener (port 8090) is no longer anonymous. Every route needs a scope, granted by a signed Ed25519 JWT or by `[cvm.guest_agent_api].anonymous_scopes` in sys-config; the gateway gets its token minted inside the CVM from the app root key. `public_logs` / `public_sysinfo` / `public_tcbinfo` are unchanged and still decide what may leave the TEE. The dashboard is filtered block by block by scope. See `docs/guest-api-auth.md`. An old gateway sees 401s and drops new guests from rotation until it is upgraded +- guest-agent: the external listener (port 8090) is no longer anonymous. Every route needs a scope, granted by a signed Ed25519 JWT or by `[cvm.guest_agent_api].anonymous_scopes` in sys-config. There is no built-in anonymous default; the sample `vmm.toml` opens `guest:dashboard`, `guest:info`, `guest:version` and `guest:health`, which is what an unconfigured 8090 used to serve, while containers, logs, metrics and app-key attestation stay behind a token. The gateway gets its token minted inside the CVM from the app root key. `public_logs` / `public_sysinfo` / `public_tcbinfo` are unchanged and still decide what may leave the TEE. The dashboard is filtered block by block by scope. See `docs/guest-api-auth.md`. An old gateway sees 401s and drops new guests from rotation until it is upgraded - vmm: `qmp_socket` now defaults to `true`. Each CVM's QEMU exposes `qmp.sock` in its work dir, so the host can change disk options or compact a bloated `hda.img` (`blockdev-mirror`) without stopping the CVM. Applies to CVMs started after the change; set `qmp_socket = false` to opt out ## [0.6.1] - 2026-10-12 diff --git a/docs/guest-api-auth.md b/docs/guest-api-auth.md index c6c7451861..3a665f5b46 100644 --- a/docs/guest-api-auth.md +++ b/docs/guest-api-auth.md @@ -33,13 +33,29 @@ not passed to the router. ## Default: nothing anonymous -With no configuration, every scope above requires a token. The gateway still -works, because it is issued one internally; the dashboard, `/metrics` and the -log views stop answering to the public. - -The app's own SDKs are unaffected: they use the internal Unix socket, which is +With no `[cvm.guest_agent_api]` block, an anonymous caller is granted nothing: +the dashboard, its identity block, `/metrics` and the log views all need a +token. The gateway still works, because it is issued one internally. The app's +own SDKs are unaffected: they use the internal Unix socket, which is unauthenticated and reachable only by the application. +The sample `vmm.toml` ships the block filled in with what an unconfigured 8090 +used to serve, so a host that copies the sample keeps the page it had: + +| Scope | Effect | +|---|---| +| `guest:version` | `Worker.Version` answers | +| `guest:health` | `Worker.Health` answers | +| `guest:info` | the identity block renders | +| `guest:dashboard` | the page loads at all | + +Everything else is about the app's *contents* and stays behind a token even in +that sample: the container table, `/metrics`, the log views and +`Worker.GetAttestationForAppKey`. + +The dashboard does not fetch `Info` unless a block would show it, so an +anonymous visitor granted only `guest:dashboard` costs the TEE no attestation. + ## Configuring anonymous access Anonymous access is a host decision, made in sys-config. The VMM writes it from @@ -47,7 +63,7 @@ Anonymous access is a host decision, made in sys-config. The VMM writes it from ```toml [cvm.guest_agent_api] -anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health"] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] ``` The same block in the guest's `/dstack/.host-shared/.sys-config.json`: @@ -55,11 +71,15 @@ The same block in the guest's `/dstack/.host-shared/.sys-config.json`: ```json { "guest_agent_api": { - "anonymous_scopes": ["guest:dashboard", "guest:version", "guest:health"] + "anonymous_scopes": ["guest:dashboard", "guest:version", "guest:health", "guest:info"] } } ``` +The list is whole, not additive, and there is no built-in default to fall back +on: omitting `anonymous_scopes`, or leaving the list empty, closes the listener +to anonymous callers. Removing the block entirely does the same. + Listing `guest:dashboard` without `guest:containers`, `guest:info`, `guest:logs` or `guest:metrics` gives an anonymous visitor the page with every block hidden. Scopes are independent: each one adds exactly its own block. @@ -92,6 +112,9 @@ it over on registration, bound to the app id and short-lived: 1. The agent and `dstack-util`, both inside the CVM, derive the same Ed25519 key: `derive_app_key(app_root_key, "dstack:guest-api:issuer:v1", Ed25519)`. + That domain string is final: it is a wire contract between `dstack-util` and + the agent, which are upgraded together but may briefly disagree, so it is + never versioned again. 2. `dstack-util` signs a token with `iss = "dstack:guest-api:"`, `aud = `, a 10-minute lifetime, and only the `guest:health` scope. 3. Registration carries it to the gateway, which presents it on the v1 `Health` @@ -135,8 +158,8 @@ host cannot alter without changing the app id. ## Compatibility -A guest with this change answers 401 to an old gateway that presents no token. The -gateway counts that as unreachable and drops the instance after +A guest with this change answers 401 to an old gateway that presents no token. +The gateway counts that as unreachable and drops the instance after `failure_threshold` consecutive polls, so a mixed cluster rebalances away from new guests until the gateway is upgraded. @@ -144,5 +167,12 @@ During the rollout, either upgrade the gateway first, or leave the host open: ```toml [cvm.guest_agent_api] -anonymous_scopes = ["guest:version", "guest:health"] +anonymous_scopes = ["guest:version", "guest:health", "guest:info", "guest:dashboard"] ``` + +The reverse direction is quieter. A new guest registers with an old gateway +node that does not store `agent_token`; when that record syncs to an upgraded +node, the missing token means the upgraded node's health probe is refused too. +The instance drops out of rotation while `order_by_stickiness` keeps routing +user traffic to it. Upgrade every gateway node in the cluster before rolling +guests, not just the one the VMM talks to. diff --git a/dstack/crates/dstack-cli-core/src/config.rs b/dstack/crates/dstack-cli-core/src/config.rs index 2618bc6d98..0f885265e5 100644 --- a/dstack/crates/dstack-cli-core/src/config.rs +++ b/dstack/crates/dstack-cli-core/src/config.rs @@ -348,6 +348,12 @@ qemu_hotplug_off = true host_share_mode = "{host_share_mode}" qgs_port = 4050 +# What an unconfigured 8090 serves: the dashboard, and the identity, version +# and health it publishes. Containers, logs, metrics and app-key attestation +# need a token. See docs/guest-api-auth.md. +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] + [cvm.product] sys_vendor = "dstack" product_name = "dstack" diff --git a/dstack/dstack-types/src/lib.rs b/dstack/dstack-types/src/lib.rs index ccf2ed02f8..68369be189 100644 --- a/dstack/dstack-types/src/lib.rs +++ b/dstack/dstack-types/src/lib.rs @@ -1255,7 +1255,7 @@ pub struct SysConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub mr_config: Option, /// Access control for the guest agent's external listener. Absent means - /// the code defaults: nothing anonymous, no external issuers. + /// nothing anonymous and no external issuers. /// /// Host-supplied, and deliberately not measured: it decides who may *ask* /// the agent, never whether data may leave the TEE. Confidentiality stays @@ -1273,8 +1273,9 @@ pub struct GuestAgentApiConfig { /// Scopes granted to a caller that presents no token. /// /// Empty by default: an app that wants its dashboard on the internet has - /// to say so. This is an exposure choice, not a trust one -- the anonymous - /// caller is the same party a public 8090 already served. + /// to say so, in `vmm.toml` or in the guest's sys-config. What a host is + /// expected to open is spelled out in the sample `vmm.toml` rather than + /// here, so the shipped default stays visible where an operator sets it. #[serde(default)] pub anonymous_scopes: Vec, /// Issuers other than the app's own root key. diff --git a/dstack/vmm/vmm.toml b/dstack/vmm/vmm.toml index 680dbc8fb0..6db4441f68 100644 --- a/dstack/vmm/vmm.toml +++ b/dstack/vmm/vmm.toml @@ -109,18 +109,6 @@ tdx_attestation_variant = "auto" host_share_mode = "9p" -# Access control for the guest agent's external listener (port 8090). Absent -# means nothing is anonymous: only holders of a token (the gateway, minted -# inside the CVM) can call it. This is an exposure choice, not a -# confidentiality one -- what may leave the TEE is still decided by the -# measured public_logs / public_sysinfo / public_tcbinfo switches in -# app-compose. See docs/guest-api-auth.md. -# [cvm.guest_agent_api] -# anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health"] -# [[cvm.guest_agent_api.external_issuers]] -# name = "ops" -# public_keys = ["<32-byte ed25519 public key, hex>"] - # Default preallocation for a new CVM data disk. This is a host storage # policy -- the guest cannot see it and it does not affect measurements -- and # a deploy request may pick another mode per VM. @@ -317,6 +305,23 @@ sanitize_on_attach = false # Maximum time for all reset GPUs to become continuously VFIO-ready. sbr_timeout_ms = 10000 +# Access control for the guest agent's external listener (port 8090). Every +# route needs a scope, granted by a signed Ed25519 JWT or by the anonymous list +# below. This is an exposure choice, not a confidentiality one -- what may leave +# the TEE is still decided by the measured public_logs / public_sysinfo / +# public_tcbinfo switches in app-compose. See docs/guest-api-auth.md. +# +# The list is whole, not additive, and there is no built-in anonymous default: +# comment the whole block out to refuse anonymous callers entirely. The set +# below is what an unconfigured 8090 used to serve -- the dashboard, and the +# identity, version and health it publishes. Containers, logs, metrics and +# app-key attestation need a token either way. +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] +# [[cvm.guest_agent_api.external_issuers]] +# name = "ops" +# public_keys = ["<32-byte ed25519 public key, hex>"] + [gateway] base_domain = "localhost" port = 8082 diff --git a/test-suites/full-stack-compose/scripts/render-config.sh b/test-suites/full-stack-compose/scripts/render-config.sh index 3a585d6cad..5f1c4c946f 100755 --- a/test-suites/full-stack-compose/scripts/render-config.sh +++ b/test-suites/full-stack-compose/scripts/render-config.sh @@ -216,6 +216,9 @@ exclude = [] include = [] allow_attach_all = false +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] + [gateway] base_domain = "${BASE_DOMAIN}" port = ${GATEWAY1_PROXY_HOST_PORT} diff --git a/tools/dev-stack.sh b/tools/dev-stack.sh index cb43aa8cf7..9884c88bf4 100755 --- a/tools/dev-stack.sh +++ b/tools/dev-stack.sh @@ -261,6 +261,10 @@ kms_urls = ["https://$KMS_DOMAIN:$KMS_RPC_LISTEN_PORT"] gateway_urls = ["https://$GATEWAY_DOMAIN:$GATEWAY_RPC_LISTEN_PORT"] cid_start = $VMM_CID_POOL_START cid_pool_size = $VMM_CID_POOL_SIZE + +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] + [cvm.port_mapping] enabled = $VMM_PORT_MAPPING_ENABLED address = "127.0.0.1" From e835d611640bc158ec0976c6da5a576d274699d4 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Thu, 22 Oct 2026 20:29:58 -0700 Subject: [PATCH 045/572] fix(dstack-util): validate gateway WireGuard fields before rendering Signed-off-by: Kevin Wang --- dstack/dstack-util/Cargo.toml | 2 +- dstack/dstack-util/src/system_setup.rs | 81 ++++++++++++++++++++++++-- 2 files changed, 77 insertions(+), 6 deletions(-) diff --git a/dstack/dstack-util/Cargo.toml b/dstack/dstack-util/Cargo.toml index a38f02f411..4df0dd1083 100644 --- a/dstack/dstack-util/Cargo.toml +++ b/dstack/dstack-util/Cargo.toml @@ -68,7 +68,7 @@ ez-hash.workspace = true cc-eventlog.workspace = true safe-write.workspace = true errify.workspace = true +base64.workspace = true [dev-dependencies] -base64.workspace = true rand.workspace = true diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 114e8d37e2..b834683c91 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -7,6 +7,7 @@ use std::{ collections::{BTreeMap, BTreeSet}, fmt::Display, io::Write as _, + net::{Ipv4Addr, Ipv6Addr}, ops::Deref, path::{Path, PathBuf}, process::{Command, Stdio}, @@ -477,6 +478,43 @@ fn wireguard_endpoint_hosts(config: &str) -> Result> { .collect() } +// The gateway's WireGuard fields are rendered into a wg-quick config, and +// wg-quick runs its `PreUp`/`PostUp` hooks as root. Accept only values that +// cannot carry config syntax, so the gateway cannot inject lines. +fn parse_wg_ip(ip: &str) -> Result { + ip.parse() + .with_context(|| format!("invalid WireGuard address: {ip:?}")) +} + +fn parse_wg_public_key(key: &str) -> Result { + use base64::{engine::general_purpose::STANDARD, Engine as _}; + let decoded = STANDARD + .decode(key) + .ok() + .filter(|decoded| decoded.len() == 32) + .with_context(|| format!("invalid WireGuard public key: {key:?}"))?; + Ok(STANDARD.encode(decoded)) +} + +fn validate_wg_endpoint(endpoint: &str) -> Result<&str> { + let valid = endpoint.rsplit_once(':').is_some_and(|(host, port)| { + let host_ok = match host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) { + Some(v6) => v6.parse::().is_ok(), + None => { + !host.is_empty() + && host + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-') + } + }; + host_ok && port.parse::().is_ok() + }); + if !valid { + bail!("invalid WireGuard endpoint: {endpoint:?}"); + } + Ok(endpoint) +} + fn remove_partial_wireguard_config(path: &str, cluster: &str) { if let Err(error) = fs::remove_file(path) { if error.kind() != std::io::ErrorKind::NotFound { @@ -838,12 +876,15 @@ impl<'a> GatewayContext<'a> { .context("too many gateway clusters")?; let mut wg_info = cluster.response.wg.take().context("missing wg info")?; wg_info.servers.sort_by(|a, b| a.pk.cmp(&b.pk)); + let client_ip = parse_wg_ip(&wg_info.client_ip)?; let mut new_config = format!( - "[Interface]\nPrivateKey = {}\nListenPort = {listen_port}\nAddress = {}/32\n\n", - cluster.key_store.wg_sk, wg_info.client_ip + "[Interface]\nPrivateKey = {}\nListenPort = {listen_port}\nAddress = {client_ip}/32\n\n", + cluster.key_store.wg_sk ); for WireGuardPeer { pk, ip, endpoint } in &wg_info.servers { - let ip = ip.split('/').next().unwrap_or_default(); + let pk = parse_wg_public_key(pk)?; + let ip = parse_wg_ip(ip.split('/').next().unwrap_or_default())?; + let endpoint = validate_wg_endpoint(endpoint)?; new_config.push_str(&format!( "[Peer]\nPublicKey = {pk}\nAllowedIPs = {ip}/32\nEndpoint = {endpoint}\nPersistentKeepalive = 25\n" )); @@ -4002,8 +4043,9 @@ mod kms_provider_inventory_tests { #[cfg(test)] mod gateway_registration_refresh_tests { use super::{ - carry_cluster_preference, gateway_rpc_url, order_by_stickiness, record_accepting_url, - wireguard_endpoint_hosts, GatewayKeyStore, IssuedClientCerts, + carry_cluster_preference, gateway_rpc_url, order_by_stickiness, parse_wg_ip, + parse_wg_public_key, record_accepting_url, validate_wg_endpoint, wireguard_endpoint_hosts, + GatewayKeyStore, IssuedClientCerts, }; use std::os::unix::fs::PermissionsExt as _; @@ -4354,4 +4396,33 @@ Endpoint = [2001:db8::1]:51822 ); assert!(wireguard_endpoint_hosts("Endpoint = missing-port").is_err()); } + + #[test] + fn wireguard_fields_reject_config_syntax() { + for endpoint in [ + "gateway.example.com:51820", + "192.0.2.1:51821", + "[2001:db8::1]:51822", + ] { + assert_eq!(validate_wg_endpoint(endpoint).unwrap(), endpoint); + } + for endpoint in [ + "", + "192.0.2.1", + "192.0.2.1:99999", + "0.0.0.0/0:1", + "192.0.2.1:51820\n[Interface]\nPostUp = id", + "[not-v6]:51820", + ] { + assert!(validate_wg_endpoint(endpoint).is_err(), "{endpoint:?}"); + } + + let key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; + assert_eq!(parse_wg_public_key(key).unwrap(), key); + assert!(parse_wg_public_key(&format!("{key}\nPostUp = id")).is_err()); + assert!(parse_wg_public_key("AAAA").is_err()); + + assert!(parse_wg_ip("10.0.0.2").is_ok()); + assert!(parse_wg_ip("10.0.0.2/32\n[Interface]").is_err()); + } } From c745a98b13dcda819b5d10ab8911d6e14944cb35 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Thu, 22 Oct 2026 21:17:18 -0700 Subject: [PATCH 046/572] chore(deps): bump rustls and h2 for RUSTSEC advisories Signed-off-by: Kevin Wang --- dstack/Cargo.lock | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 9d27c2c6b0..55ae031509 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -138,7 +138,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -149,7 +149,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -1762,7 +1762,7 @@ dependencies = [ "libc", "option-ext", "redox_users 0.5.2", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -2681,7 +2681,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -3187,9 +3187,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.14" +version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" dependencies = [ "atomic-waker", "bytes", @@ -3931,7 +3931,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4796,7 +4796,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -6506,14 +6506,14 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] name = "rustls" -version = "0.23.40" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "log", @@ -6574,7 +6574,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -7428,7 +7428,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -7745,7 +7745,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix 1.1.4", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] From bdb00fb691c557dea5d5cbbab9bdac3d50d9d2b5 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Thu, 22 Oct 2026 20:43:45 -0700 Subject: [PATCH 047/572] ci: pin actions and tools in release workflows that hold publish credentials Signed-off-by: Kevin Wang --- .github/workflows/guest-os.yml | 8 ++++---- .github/workflows/js-sdk-release.yml | 8 ++++---- .github/workflows/python-sdk-release.yml | 12 ++++++------ .github/workflows/rust-sdk-release.yml | 4 ++-- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/.github/workflows/guest-os.yml b/.github/workflows/guest-os.yml index 503159a7e1..0aebe7d437 100644 --- a/.github/workflows/guest-os.yml +++ b/.github/workflows/guest-os.yml @@ -23,13 +23,13 @@ jobs: contents: read steps: - name: Checkout - uses: actions/checkout@v5 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - name: Build production guest OS (deprecated Yocto backend) run: make os-image-yocto - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: guest-images path: | @@ -47,12 +47,12 @@ jobs: contents: write steps: - name: Checkout default branch - uses: actions/checkout@v5 + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 with: ref: ${{ github.event.repository.default_branch }} - name: Download artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 with: name: guest-images path: os/yocto/repro-build/dist diff --git a/.github/workflows/js-sdk-release.yml b/.github/workflows/js-sdk-release.yml index 97148f3905..660c09fc08 100644 --- a/.github/workflows/js-sdk-release.yml +++ b/.github/workflows/js-sdk-release.yml @@ -26,16 +26,16 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - - uses: actions/setup-node@v5 + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 with: node-version: '20' registry-url: 'https://registry.npmjs.org' - name: Upgrade npm for trusted publishers support run: | - npm install -g npm@latest + npm install -g npm@11.21.1 echo "npm: $(npm --version)" - name: Verify OIDC token availability @@ -104,7 +104,7 @@ jobs: - name: GitHub Release if: github.event_name == 'push' - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 with: name: "JS SDK v${{ steps.tag.outputs.version }}" body: | diff --git a/.github/workflows/python-sdk-release.yml b/.github/workflows/python-sdk-release.yml index 3aec79f1de..a7e2d6aa63 100644 --- a/.github/workflows/python-sdk-release.yml +++ b/.github/workflows/python-sdk-release.yml @@ -25,14 +25,14 @@ jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - - uses: actions/setup-python@v5 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: '3.11' - name: Install PDM - run: pip install pdm + run: pip install pdm==2.29.3 - name: Build distribution working-directory: sdk/python @@ -66,20 +66,20 @@ jobs: - name: Publish to PyPI if: github.event_name == 'push' || github.event.inputs.target == 'pypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: packages-dir: sdk/python/dist - name: Publish to TestPyPI if: github.event_name == 'workflow_dispatch' && github.event.inputs.target == 'testpypi' - uses: pypa/gh-action-pypi-publish@release/v1 + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 with: repository-url: https://test.pypi.org/legacy/ packages-dir: sdk/python/dist - name: GitHub Release if: github.event_name == 'push' - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 with: name: "Python SDK v${{ steps.version.outputs.version }}" body: | diff --git a/.github/workflows/rust-sdk-release.yml b/.github/workflows/rust-sdk-release.yml index 207c2bee9c..d10294011e 100644 --- a/.github/workflows/rust-sdk-release.yml +++ b/.github/workflows/rust-sdk-release.yml @@ -16,7 +16,7 @@ jobs: id-token: write contents: write steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 - name: Extract version from tag id: ver @@ -69,7 +69,7 @@ jobs: sys.exit(1) PY - - uses: rust-lang/crates-io-auth-action@v1 + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 id: auth - name: Publish dstack-sdk-types From 36aa4958094c908d6854a70868965328b5b09685 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Thu, 22 Oct 2026 20:46:07 -0700 Subject: [PATCH 048/572] fix(ra-rpc): pin swagger-ui with SRI on the api-docs page Signed-off-by: Kevin Wang --- dstack/ra-rpc/src/openapi.rs | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/dstack/ra-rpc/src/openapi.rs b/dstack/ra-rpc/src/openapi.rs index 8fe2f1561c..a19f9c8872 100644 --- a/dstack/ra-rpc/src/openapi.rs +++ b/dstack/ra-rpc/src/openapi.rs @@ -211,15 +211,24 @@ pub(crate) struct RenderedDoc { pub struct SwaggerUiConfig { pub title: String, pub dark_mode: bool, - pub swagger_ui_dist: String, } +// Pinned with SRI so a CDN or upstream compromise cannot run script on the +// page, which shares an origin with the API it documents. Hashes are of the +// files in the npm tarball for this version. +const SWAGGER_UI_DIST: &str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.32.15"; +const SWAGGER_UI_CSS_SRI: &str = + "sha384-fgyWYkUAamzuI8mJFu/xpRP0JWCJRwkwUwsYDoOYVHUJ8NQE5cENn8ib3ppwFFSX"; +const SWAGGER_UI_BUNDLE_SRI: &str = + "sha384-m7zaGj7MPzU+G4lz2eyy73GxK9bbRDr9bB2CSdj8wodg2wu/Wnt6wsoLP3JD+RS9"; +const SWAGGER_UI_PRESET_SRI: &str = + "sha384-9rDX8vR4ir9/JIiV/XvxMpb5T9tVyFbssk49PV935hrdwmkVNJ7VZMM0RXAm184h"; + impl Default for SwaggerUiConfig { fn default() -> Self { Self { title: "pRPC Explorer".to_string(), dark_mode: true, - swagger_ui_dist: "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5".to_string(), } } } @@ -1004,18 +1013,6 @@ fn field_type(field: &FieldDescriptorProto) -> FieldType { fn build_swagger_ui_html(spec_url: &str, cfg: &SwaggerUiConfig) -> String { let spec = spec_url.replace('\'', "\\'"); - let css = format!( - "{}/swagger-ui.css", - cfg.swagger_ui_dist.trim_end_matches('/') - ); - let bundle = format!( - "{}/swagger-ui-bundle.js", - cfg.swagger_ui_dist.trim_end_matches('/') - ); - let preset = format!( - "{}/swagger-ui-standalone-preset.js", - cfg.swagger_ui_dist.trim_end_matches('/') - ); let background = if cfg.dark_mode { "#0b0d10" } else { "#fafafa" }; format!( r#" @@ -1023,7 +1020,7 @@ fn build_swagger_ui_html(spec_url: &str, cfg: &SwaggerUiConfig) -> String { {title} - +