From 2c797be92aac43fdb04e0da9fcc42c1f17a3aef5 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 04:39:12 -0800 Subject: [PATCH 01/25] feat(value-spec): add a spec language for validating string values Signed-off-by: Kevin Wang --- dstack/Cargo.lock | 23 + dstack/Cargo.toml | 3 + dstack/value-spec/Cargo.toml | 19 + dstack/value-spec/src/lib.rs | 649 +++++++++++++++++++++++ formal/DstackFormal.lean | 1 + formal/DstackFormal/Guest/ValueSpec.lean | 472 +++++++++++++++++ formal/README.md | 1 + 7 files changed, 1168 insertions(+) create mode 100644 dstack/value-spec/Cargo.toml create mode 100644 dstack/value-spec/src/lib.rs create mode 100644 formal/DstackFormal/Guest/ValueSpec.lean diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 6c6e80447..e4737465b 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -500,6 +500,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "bigdecimal" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fa3f3d8cbf4dffcfe4991de61d012bef509a409ecbe9dd41049bfe32b4d4653" +dependencies = [ + "autocfg", + "libm", + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "binascii" version = "0.1.4" @@ -8646,6 +8659,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "value-spec" +version = "0.6.6" +dependencies = [ + "bigdecimal", + "regex", + "thiserror 2.0.18", + "winnow 1.0.3", +] + [[package]] name = "version_check" version = "0.9.5" diff --git a/dstack/Cargo.toml b/dstack/Cargo.toml index d1c2d15aa..dcfef933e 100644 --- a/dstack/Cargo.toml +++ b/dstack/Cargo.toml @@ -65,6 +65,7 @@ members = [ "nvidia-attest-proxy", "verifier", "size-parser", + "value-spec", "crates/dstack-cli-core", "crates/dstack-cli", "crates/dstack-volume", @@ -301,6 +302,8 @@ humantime = "2.2.0" parcelona = "0.4.3" pin-project = "1.1.10" regex = "1.11.1" +winnow = "1.0.3" +bigdecimal = "0.4.11" rinja = "0.3.5" shared_child = "1.0.1" strip-ansi-escapes = "0.2.1" diff --git a/dstack/value-spec/Cargo.toml b/dstack/value-spec/Cargo.toml new file mode 100644 index 000000000..2e7d33947 --- /dev/null +++ b/dstack/value-spec/Cargo.toml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "value-spec" +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +homepage.workspace = true +repository.workspace = true +description = "A compact spec language for validating string values" + +[dependencies] +bigdecimal.workspace = true +regex.workspace = true +thiserror.workspace = true +winnow.workspace = true diff --git a/dstack/value-spec/src/lib.rs b/dstack/value-spec/src/lib.rs new file mode 100644 index 000000000..8f0424bdf --- /dev/null +++ b/dstack/value-spec/src/lib.rs @@ -0,0 +1,649 @@ +// SPDX-FileCopyrightText: © 2026 Phala Network +// +// SPDX-License-Identifier: Apache-2.0 + +//! A compact spec language for validating string values such as environment +//! variables. +//! +//! A spec is an integer spec, a decimal spec or a regex: +//! +//! | Spec | Accepts | +//! | --- | --- | +//! | `int` | any integer | +//! | `int(1..=65535)` | integers from 1 to 65535 | +//! | `int(0..<256)` | integers from 0 to 255 | +//! | `int(0\|1024..=65535)` | 0, or integers from 1024 to 65535 | +//! | `float` | any decimal | +//! | `float(0<..=1)` | numbers above 0, up to 1 | +//! | `float(..<0\|0.5..)` | numbers below 0, or from 0.5 | +//! | `/[a-z]{1,8}/` | values the regex matches in full | +//! +//! A range is `start..=end`, where either side may be omitted to leave it +//! unbounded. Writing `<` instead of `=` excludes the end, and `<` after the +//! start excludes the start. +//! +//! Numbers are canonical decimals: no `+`, no leading zeros, no negative zero, +//! no exponent, no whitespace, at most 64 bytes. Integers are bounded by `i128` +//! and numbers are compared exactly. The regex is everything between the first +//! and the last `/`, in the dialect of the [`regex`] crate. +//! +//! ``` +//! use value_spec::ValueSpec; +//! +//! let port: ValueSpec = "int(0|1024..=65535)".parse().unwrap(); +//! assert!(port.matches("0")); +//! assert!(port.matches("8080")); +//! assert!(!port.matches("80")); +//! assert!(!port.matches("08080")); +//! assert!(!port.matches("8080.5")); +//! +//! let ratio: ValueSpec = "float(0<..=1)".parse().unwrap(); +//! assert!(ratio.matches("0.25")); +//! assert!(!ratio.matches("0")); +//! +//! let key: ValueSpec = "/[A-Za-z0-9_-]{1,128}/".parse().unwrap(); +//! assert!(key.matches("abc_123")); +//! assert!(!key.matches("abc/123")); +//! ``` + +use std::ops::Bound::{self, Excluded, Included, Unbounded}; +use std::ops::RangeBounds; +use std::str::FromStr; + +use bigdecimal::{BigDecimal, Zero}; +use regex::Regex; +use thiserror::Error; +use winnow::ascii::{digit0, digit1}; +use winnow::combinator::{ + alt, cut_err, empty, eof, fail, opt, peek, preceded, separated, terminated, +}; +use winnow::error::StrContext::{Expected, Label}; +use winnow::error::StrContextValue::Description; +use winnow::error::{ContextError, ErrMode}; +use winnow::token::{one_of, rest}; +use winnow::{ModalResult, Parser}; + +/// The error returned when a spec fails to parse. +#[derive(Debug, Error)] +#[error("invalid value spec at offset {offset}: {message}")] +pub struct ParseError { + offset: usize, + message: String, +} + +/// A parsed spec. Build one with [`str::parse`]. +#[derive(Debug, Clone)] +pub struct ValueSpec(Kind); + +#[derive(Debug, Clone)] +enum Kind { + Int(Vec>), + Float(Vec>), + Regex(Regex), +} + +const MAX_NUMBER_LEN: usize = 64; + +type Range = (Bound, Bound); + +type Number = fn(&mut &str) -> ModalResult; + +impl ValueSpec { + /// Returns whether `value` satisfies the spec. + pub fn matches(&self, value: &str) -> bool { + match &self.0 { + Kind::Int(ranges) => contains(ranges, int, value), + Kind::Float(ranges) => contains(ranges, decimal, value), + Kind::Regex(regex) => regex.is_match(value), + } + } +} + +impl FromStr for ValueSpec { + type Err = ParseError; + + fn from_str(s: &str) -> Result { + let spec = alt(( + regex.map(Kind::Regex), + ranges("int", int) + .verify(|ranges: &Vec<_>| ranges.iter().all(has_int)) + .map(Kind::Int), + ranges("float", decimal).map(Kind::Float), + fail.context(Expected(Description("`int`, `float` or `/regex/`"))), + )); + terminated(spec, eof.context(Expected(Description("end of spec")))) + .map(Self) + .parse(s) + .map_err(|e| ParseError { + offset: e.offset(), + message: e.inner().to_string(), + }) + } +} + +fn contains(ranges: &[Range], mut number: Number, value: &str) -> bool { + number + .parse(value) + .is_ok_and(|n| ranges.iter().any(|range| range.contains(&n))) +} + +fn int(input: &mut &str) -> ModalResult { + alt(("0", (opt('-'), one_of('1'..='9'), digit0).take())) + .verify(|s: &str| s.len() <= MAX_NUMBER_LEN) + .try_map(str::parse) + .context(Label("int")) + .parse_next(input) +} + +fn decimal(input: &mut &str) -> ModalResult { + let integer = alt(("0", (one_of('1'..='9'), digit0).take())); + (opt('-'), integer, opt(('.', digit1))) + .take() + .verify(|s: &str| s.len() <= MAX_NUMBER_LEN) + .try_map(|s: &str| s.parse::().map(|n| (s, n))) + .verify_map(|(s, n)| (!(s.starts_with('-') && n.is_zero())).then_some(n)) + .context(Label("float")) + .parse_next(input) +} + +fn ranges<'a, T: Clone + PartialOrd>( + name: &'static str, + number: Number, +) -> impl Parser<&'a str, Vec>, ErrMode> { + let single = number.map(|n| (Included(n.clone()), Included(n))); + let item = alt(( + terminated(single, peek(one_of(['|', ')']))), + cut_err(range(number)), + )); + let items = terminated(separated(1.., item, '|'), ')'); + let any = eof.value(vec![(Unbounded, Unbounded)]); + preceded(name, alt((preceded('(', cut_err(items)), any))).context(Label(name)) +} + +fn range<'a, T: Clone + PartialOrd>( + number: Number, +) -> impl Parser<&'a str, Range, ErrMode> { + let start = alt(( + (number, opt('<')).map(|(n, open)| open.map_or(Included(n.clone()), |_| Excluded(n))), + empty.value(Unbounded), + )); + let end = alt(( + preceded('=', cut_err(number)).map(Included), + preceded('<', cut_err(number)).map(Excluded), + empty.value(Unbounded), + )); + (terminated(start, ".."), end) + .verify(|(start, end)| match (start, end) { + (Included(start), Included(end)) => start <= end, + (Included(start) | Excluded(start), Included(end) | Excluded(end)) => start < end, + _ => true, + }) + .context(Expected(Description("number or non-empty range"))) +} + +/// Whether any integer lies in the range, which `1<..<2` has none of. +fn has_int((start, end): &Range) -> bool { + let first = match *start { + Included(n) => Some(n), + Excluded(n) => n.checked_add(1), + Unbounded => Some(i128::MIN), + }; + let last = match *end { + Included(n) => Some(n), + Excluded(n) => n.checked_sub(1), + Unbounded => Some(i128::MAX), + }; + first.zip(last).is_some_and(|(first, last)| first <= last) +} + +fn regex(input: &mut &str) -> ModalResult { + let pattern = rest.verify_map(|s: &str| s.strip_suffix('/')); + preceded('/', cut_err(pattern.try_map(anchored))) + .context(Label("regex")) + .parse_next(input) +} + +fn anchored(pattern: &str) -> Result { + // Reject patterns that are only valid once wrapped, such as `a)|(b`. + Regex::new(pattern)?; + Regex::new(&format!(r"\A(?:{pattern})\z")) +} + +#[cfg(test)] +mod tests { + use super::*; + + const INT_MIN: &str = "-170141183460469231731687303715884105728"; + const INT_MAX: &str = "170141183460469231731687303715884105727"; + const INT_OVERFLOW: &str = "170141183460469231731687303715884105728"; + const INT_UNDERFLOW: &str = "-170141183460469231731687303715884105729"; + + fn check(spec: &str, accepted: &[&str], rejected: &[&str]) { + let spec: ValueSpec = spec.parse().unwrap(); + for value in accepted { + assert!(spec.matches(value), "{spec:?} should accept {value:?}"); + } + for value in rejected { + assert!(!spec.matches(value), "{spec:?} should reject {value:?}"); + } + } + + fn check_invalid(specs: &[&str]) { + for spec in specs { + assert!(spec.parse::().is_err(), "{spec:?} should fail"); + } + } + + #[test] + fn int_ranges() { + check("int(1..=65535)", &["1", "65535"], &["0", "65536", "-1"]); + check("int(0..<256)", &["0", "255"], &["-1", "256"]); + check("int(0<..=256)", &["1", "256"], &["0", "257"]); + check("int(0<..<256)", &["1", "255"], &["0", "256"]); + check("int(-5..=-1)", &["-5", "-1"], &["-6", "0"]); + check("int(-1..=1)", &["-1", "0", "1"], &["-2", "2"]); + check("int(1..)", &["1", INT_MAX], &["0", INT_MIN]); + check("int(0<..)", &["1", INT_MAX], &["0"]); + check("int(..<0)", &["-1", INT_MIN], &["0"]); + check("int(..=0)", &["0", INT_MIN], &["1"]); + check("int(..)", &["0", INT_MIN, INT_MAX], &["a"]); + check("int(5..=5)", &["5"], &["4", "6"]); + check("int(4<..<6)", &["5"], &["4", "6"]); + } + + #[test] + fn int_singles_and_unions() { + check("int(0)", &["0"], &["1", "-1", "00"]); + check("int(-7)", &["-7"], &["7"]); + check("int(0|1024..=65535)", &["0", "1024"], &["1", "1023"]); + check("int(80|443|8000..<9000)", &["80", "443", "8999"], &["9000"]); + check("int(..=-1|1..)", &["-1", "1"], &["0"]); + check("int(1..=5|3..=8)", &["1", "4", "8"], &["0", "9"]); + check("int(1|1)", &["1"], &["2"]); + } + + #[test] + fn int_is_bounded_by_i128() { + check( + "int", + &["0", INT_MIN, INT_MAX], + &[INT_OVERFLOW, INT_UNDERFLOW], + ); + check( + &format!("int({INT_MIN}..={INT_MAX})"), + &[INT_MIN, INT_MAX], + &[], + ); + check(&format!("int({INT_MAX})"), &[INT_MAX], &[INT_MIN]); + check(&format!("int(..<{INT_MAX})"), &[INT_MIN], &[INT_MAX]); + check(&format!("int({INT_MIN}<..)"), &[INT_MAX], &[INT_MIN]); + check_invalid(&[ + &format!("int({INT_OVERFLOW})"), + &format!("int(..={INT_OVERFLOW})"), + &format!("int({INT_UNDERFLOW}..)"), + &format!("int(..<{INT_MIN})"), + &format!("int({INT_MAX}<..)"), + ]); + } + + #[test] + fn int_rejects_decimals() { + check("int", &[], &["1.0", "1.5", "0.0", "-1.0", "1."]); + check_invalid(&["int(1.5)", "int(1.0)", "int(1..=1.5)", "int(0.5..=1)"]); + } + + #[test] + fn float_ranges() { + check( + "float(0<..=1)", + &["0.001", "1", "1.0"], + &["0", "0.0", "1.001"], + ); + check("float(0.5..<1.5)", &["0.5", "1", "1.49"], &["0.49", "1.5"]); + check( + "float(-1.5..=-0.5)", + &["-1.5", "-1", "-0.5"], + &["-1.6", "0"], + ); + check("float(0.5..)", &["0.5", "1000000"], &["0.4999", "-1"]); + check("float(0.5<..)", &["0.5001"], &["0.5", "0.50"]); + check("float(..<0.5)", &["0.4999", "-3"], &["0.5"]); + check("float(..=0.5)", &["0.5", "0.500"], &["0.5001"]); + check("float(..)", &["0", "-7.5"], &["a"]); + check("float(1..=2)", &["1", "1.5", "2", "2.0"], &["0.9", "2.1"]); + check("float(0.50..=0.5)", &["0.5", "0.50"], &["0.51"]); + } + + #[test] + fn float_singles_and_unions() { + check( + "float(0.1|0.25)", + &["0.1", "0.10", "0.25"], + &["0.2", "0.11"], + ); + check("float(1)", &["1", "1.0", "1.000"], &["1.001"]); + check("float(..<0|0.5..)", &["-0.1", "0.5", "7"], &["0", "0.4"]); + check("float(0|0.5<..<1)", &["0", "0.0", "0.75"], &["0.5", "1"]); + } + + #[test] + fn float_compares_exactly() { + check( + "float(0.1<..<0.3)", + &["0.2", "0.10000000000000000000000000000000000000001"], + &["0.1", "0.3", "0.30000000000000000000000000000000000000001"], + ); + // 0.1 + 0.2 is 0.30000000000000004 in binary floating point. + check("float(0.3)", &["0.3", "0.30"], &["0.30000000000000004"]); + check( + "float(9007199254740993)", + &["9007199254740993"], + &["9007199254740992", "9007199254740994"], + ); + check( + "float", + &[ + INT_OVERFLOW, + INT_UNDERFLOW, + "1234567890123456789012345678901234567890.5", + ], + &[], + ); + check( + &format!("float({INT_OVERFLOW}<..)"), + &[&format!("{INT_OVERFLOW}.1")], + &[INT_OVERFLOW, INT_MAX], + ); + } + + #[test] + fn ranges_agree_with_rust() { + let accepts = |spec: String, value: &str| { + let spec = spec.parse::().ok(); + spec.is_some_and(|spec| spec.matches(value)) + }; + for (kind, scale) in [("int", 1.0), ("float", 4.0)] { + let n = |i: i32| f64::from(i) / scale; + for a in (-3..=3).map(n) { + for v in (-5..=5).map(n) { + let accepts = + |range: String| accepts(format!("{kind}({range})"), &v.to_string()); + for b in (-3..=3).map(n) { + assert_eq!(accepts(format!("{a}..={b}")), (a..=b).contains(&v)); + assert_eq!(accepts(format!("{a}..<{b}")), (a..b).contains(&v)); + assert_eq!(accepts(format!("{a}<..={b}")), a < v && v <= b); + assert_eq!(accepts(format!("{a}<..<{b}")), a < v && v < b); + assert_eq!(accepts(format!("{a}|{b}")), a == v || b == v); + assert_eq!(accepts(format!("..<{a}|{b}..")), v < a || v >= b); + } + assert_eq!(accepts(format!("{a}..")), (a..).contains(&v)); + assert_eq!(accepts(format!("{a}<..")), a < v); + assert_eq!(accepts(format!("..={a}")), (..=a).contains(&v)); + assert_eq!(accepts(format!("..<{a}")), (..a).contains(&v)); + assert_eq!(accepts(a.to_string()), a == v); + } + } + } + } + + #[test] + fn empty_ranges_are_rejected() { + check_invalid(&[ + "int(5..<5)", + "int(5<..=5)", + "int(5<..<5)", + "int(5<..<6)", + "int(5..=4)", + "int(5..<4)", + "int(1|5..=4)", + "float(0.5..<0.5)", + "float(0.5<..=0.5)", + "float(0.5<..<0.5)", + "float(0.50..<0.5)", + "float(0.5..=0.4)", + "float(1..=0.99)", + ]); + check("float(5<..<6)", &["5.5"], &["5", "6"]); + } + + #[test] + fn values_must_be_canonical() { + let common = [ + "", "-", "--7", "+7", "+0", "07", "-07", "-0", "00", " 7", "7 ", "7\n", "\t7", "7\0", + "- 7", "7-", "0x7", "0b1", "0o7", "1e3", "1E3", "1_000", "1,000", "1 000", "٧", "7", + "a", "true", "∞", + ]; + check("int", &["0", "7", "-7", "10", "-10"], &common); + check("float", &["0", "7", "-7", "10", "-10"], &common); + check( + "float", + &[ + "7.0", "0.5", "-0.5", "0.50", "0.05", "10.01", "0.0", "0.000", + ], + &[ + "7.", ".5", "-.5", "-0.0", "-0.000", "00.5", "-00.5", "1.2.3", "1..2", "1.5e3", + "1.5E-3", "1.٥", "1.5 ", "1,5", "inf", "-inf", "infinity", "NaN", "nan", + ], + ); + } + + #[test] + fn numbers_are_length_limited() { + let (fits, long) = ( + format!("0.{}", "1".repeat(MAX_NUMBER_LEN - 2)), + format!("0.{}", "1".repeat(MAX_NUMBER_LEN - 1)), + ); + let (digits, more_digits) = ("1".repeat(MAX_NUMBER_LEN), "1".repeat(MAX_NUMBER_LEN + 1)); + let negative = format!("-{digits}"); + check( + "float", + &[&fits, &digits], + &[&long, &more_digits, &negative], + ); + check("int", &[], &[&digits, &more_digits, &"1".repeat(1 << 20)]); + check("float", &[], &[&format!("0.{}", "1".repeat(1 << 20))]); + check(&format!("float({fits}..={digits})"), &[&fits], &[]); + check_invalid(&[ + &format!("float({long}..)"), + &format!("float(..={more_digits})"), + &format!("float({more_digits})"), + &format!("int({more_digits})"), + ]); + } + + #[test] + fn regex_matches_in_full() { + check( + "/[a-z]+/", + &["abc"], + &["", "abc1", "1abc", "abc\n", "\nabc"], + ); + check("/a/", &["a"], &["", "aa", "ba", "ab", "A"]); + check("/^a$/", &["a"], &["aa", "a\n"]); + check("/(?m)^a$/", &["a"], &["a\na", "a\n"]); + check("/a|ab/", &["a", "ab"], &["abc", "b"]); + check("/ab|a/", &["a", "ab"], &["abc"]); + check("/a*?/", &["", "a", "aaa"], &["b"]); + check("//", &[""], &["a", "\n"]); + check("/.*/", &["", "any thing"], &["two\nlines"]); + check("/(?s).*/", &["", "two\nlines"], &[]); + } + + #[test] + fn regex_enumerations_and_lengths() { + check( + "/mainnet|testnet|devnet/", + &["mainnet", "testnet", "devnet"], + &[ + "", + "main", + "mainnets", + "xdevnet", + "Mainnet", + "mainnet|testnet", + ], + ); + check( + "/(?i)true|false/", + &["true", "FALSE", "True"], + &["yes", "truefalse"], + ); + check("/v1\\.0|v2\\.0/", &["v1.0", "v2.0"], &["v1x0"]); + check("/.{1,8}/", &["a", "12345678", "é"], &["", "123456789"]); + check( + "/[A-Za-z0-9_-]{1,128}/", + &["abc_123", &"a".repeat(128)], + &["", "abc/123", "abc 123", &"a".repeat(129)], + ); + check( + "/0x[0-9a-fA-F]{40}/", + &[&format!("0x{}", "aB".repeat(20))], + &["0x12"], + ); + } + + #[test] + fn regex_slashes_and_unicode() { + check( + "/https://[^/]+/v2/", + &["https://rpc.example/v2"], + &["https://a/b/v2", "https://rpc.example/v2/"], + ); + check("///", &["/"], &["", "//"]); + check("/\\//", &["/"], &["\\/"]); + check("/a/b/", &["a/b"], &["a", "b"]); + check("/\\p{Han}+/", &["中文"], &["abc", ""]); + check("/\\d+/", &["123", "٧"], &["a"]); + check("/(?-u:\\d)+/", &["123"], &["٧"]); + check("/int(1..=5)/", &["int1..=5"], &["3"]); + } + + #[test] + fn invalid_regexes() { + check_invalid(&[ + "/", + "/a", + "a/", + "/a/ ", + "/a/i", + "/(/", + "/)/", + "/[/", + "/*/", + "/a{2,1}/", + "/a\\/", + "/a)|(b/", + "/(?x)a # comment/", + "/(a)\\1/", + "/a(?=b)/", + "/(?5)", + "int(1<)", + "int(<1)", + "int(<..5)", + "int(<..)", + "int(1<5)", + "int(1<<..5)", + "int(1<=..5)", + "int(1=..5)", + "int(1..=5..=9)", + "int(a..<5)", + "int(1..=a)", + "int(1..=+5)", + "int(+1..=5)", + "int(01..<5)", + "int(1..=05)", + "int(-0..=5)", + "int(1-5)", + "int(1,5)", + "int(1, 2)", + "int(1|)", + "int(|1)", + "int(|)", + "int(1||2)", + "int(1|2", + "int(1)|int(2)", + "int(1)|/a/", + "int|float", + "int(/a/)", + "float()", + "float(1.)", + "float(.5)", + "float(.5..)", + "float(1..=.5)", + "float(-0.0..)", + "float(1e3)", + "float(1.5e3..)", + "float(inf)", + "float(..=NaN)", + "float(0.1..0.5)", + "float(0.1 ..=0.5)", + ]); + } + + #[test] + fn errors_point_at_the_problem() { + let error = |spec: &str| spec.parse::().unwrap_err(); + assert_eq!(error("string").offset, 0); + assert_eq!(error("int(1)x").offset, 6); + assert_eq!(error("int(1..=x)").offset, 8); + assert_eq!(error("int(1|a)").offset, 6); + assert_eq!(error("/(/").offset, 1); + let message = error("string").to_string(); + assert!( + message.starts_with("invalid value spec at offset 0: "), + "{message}" + ); + assert!(message.contains("`int`, `float` or `/regex/`"), "{message}"); + assert!(error("/(/").to_string().contains("unclosed group")); + } +} diff --git a/formal/DstackFormal.lean b/formal/DstackFormal.lean index af83d7c36..5970e602a 100644 --- a/formal/DstackFormal.lean +++ b/formal/DstackFormal.lean @@ -17,6 +17,7 @@ import DstackFormal.Guest.EventLog import DstackFormal.Guest.InstanceId import DstackFormal.Guest.MrConfig import DstackFormal.Guest.Policy +import DstackFormal.Guest.ValueSpec import DstackFormal.Kms.KeyDerivation import DstackFormal.Kms.KeyRelease import DstackFormal.Kms.RaTlsEncoding diff --git a/formal/DstackFormal/Guest/ValueSpec.lean b/formal/DstackFormal/Guest/ValueSpec.lean new file mode 100644 index 000000000..08b73a00b --- /dev/null +++ b/formal/DstackFormal/Guest/ValueSpec.lean @@ -0,0 +1,472 @@ +-- SPDX-FileCopyrightText: © 2026 Phala Network +-- +-- SPDX-License-Identifier: Apache-2.0 + +/-! +# Value specs: canonical integers and range checks + +Models `dstack/value-spec/src/lib.rs`: the `int` parser (the grammar +`"0" | "-"? [1-9] [0-9]*`, `MAX_NUMBER_LEN` and `str::parse::`), the +bound comparison of `range`, `has_int`, and `ValueSpec::matches` for `int` +specs. + +Proven: +* `parseI128_iff`: a text parses to `n` iff `n` is an `i128` and the text is + the one spelling Rust's `i128::to_string` prints; hence no two accepted + texts denote the same integer (`parseI128_inj`) and `MAX_NUMBER_LEN` never + rejects an `i128` (`renderInt_length`). +* `matchesInt_iff`: an `int` spec accepts exactly the canonical spellings of + the `i128` values inside one of its ranges. +* `ordered_of_contains`: the bound comparison of `range` rejects only ranges + that hold no value, for `int` and `float` alike; `contains_of_ordered`: an + accepted range with an inclusive bound holds that bound. +* `hasInt_iff`: `has_int` holds iff the range holds an `i128`, so an accepted + `int` range is never empty. + +Assumptions: `BigDecimal`'s ordering is a parameter `lt` required to be +transitive. +Modeling gaps: a text is a sign and a list of digit values, so ASCII decoding +and non-digit characters are not modeled; `i128::to_string` is modeled as +`renderInt`; the `float` grammar, the spec syntax (the winnow parser) and +regexes are not modeled. An accepted `float` range between two bounds may +still hold no decimal of at most `MAX_NUMBER_LEN` bytes. +-/ + +namespace DstackFormal.Guest.ValueSpec + +/-! ## Digit strings -/ + +/-- Value of a digit string, least significant digit first. -/ +def val : List Nat → Nat + | [] => 0 + | d :: ds => d + 10 * val ds + +/-- Digits below ten whose most significant (last) digit is nonzero. -/ +def Trimmed : List Nat → Prop + | [] => True + | d :: ds => d < 10 ∧ (ds = [] → d ≠ 0) ∧ Trimmed ds + +theorem val_eq_zero {ds : List Nat} (h : Trimmed ds) (hv : val ds = 0) : ds = [] := by + induction ds with + | nil => rfl + | cons d ds ih => + simp only [val] at hv + obtain ⟨_, hd, ht⟩ := h + exact absurd (by omega) (hd (ih ht (by omega))) + +theorem val_inj {a b : List Nat} (ha : Trimmed a) (hb : Trimmed b) (h : val a = val b) : + a = b := by + induction a generalizing b with + | nil => exact (val_eq_zero hb h.symm).symm + | cons d ds ih => + cases b with + | nil => exact val_eq_zero ha h + | cons e es => + simp only [val] at h + obtain ⟨hd, _, hds⟩ := ha + obtain ⟨he, _, hes⟩ := hb + rw [ih hds hes (by omega), show d = e by omega] + +theorem trimmed_append (xs : List Nat) (d : Nat) : + Trimmed (xs ++ [d]) ↔ (∀ x ∈ xs, x < 10) ∧ d < 10 ∧ d ≠ 0 := by + induction xs with + | nil => simp [Trimmed] + | cons x xs ih => + simp only [List.cons_append, Trimmed, ih, List.mem_cons, forall_eq_or_imp] + constructor + · rintro ⟨hx, -, hxs, hd⟩ + exact ⟨⟨hx, hxs⟩, hd⟩ + · rintro ⟨⟨hx, hxs⟩, hd⟩ + exact ⟨hx, fun h => absurd h (by simp), hxs, hd⟩ + +/-- Digits of `n`, least significant first; empty for zero. -/ +def digits (n : Nat) : List Nat := + if n = 0 then [] else n % 10 :: digits (n / 10) +termination_by n +decreasing_by omega + +theorem digits_spec (n : Nat) : Trimmed (digits n) ∧ val (digits n) = n := by + induction n using Nat.strongRecOn with + | _ n ih => + unfold digits + split + · next h => exact ⟨trivial, h.symm⟩ + · next h => + obtain ⟨ht, hv⟩ := ih (n / 10) (by omega) + refine ⟨⟨by omega, fun he => ?_, ht⟩, by simp only [val, hv]; omega⟩ + rw [he] at hv + simp only [val] at hv + omega + +theorem digits_length (k n : Nat) (h : n < 10 ^ k) : (digits n).length ≤ k := by + induction k generalizing n with + | zero => + have : n = 0 := by simpa using h + subst this + simp [digits] + | succ k ih => + unfold digits + split + · simp + · have := ih (n / 10) (by rw [Nat.pow_succ] at h; omega) + simp only [List.length_cons] + omega + +/-! ## Canonical integer texts -/ + +/-- The grammar `"0" | [1-9] [0-9]*`, most significant digit first. -/ +def canonNat : List Nat → Bool + | [] => false + | [0] => true + | d :: ds => decide (0 < d ∧ d < 10) && ds.all (· < 10) + +def parseNat (t : List Nat) : Option Nat := + if canonNat t then some (val t.reverse) else none + +/-- `to_string` of an unsigned magnitude. -/ +def render (n : Nat) : List Nat := + if n = 0 then [0] else (digits n).reverse + +theorem canonNat_iff (t : List Nat) : + canonNat t = true ↔ t = [0] ∨ (t ≠ [] ∧ Trimmed t.reverse) := by + match t with + | [] => simp [canonNat] + | [0] => simp [canonNat] + | [d + 1] => simp [canonNat, Trimmed] + | d :: e :: ds => + rw [List.reverse_cons, trimmed_append] + simp only [canonNat, Bool.and_eq_true, decide_eq_true_eq, List.all_eq_true, List.mem_cons, + forall_eq_or_imp, reduceCtorEq, List.cons.injEq, and_false, false_or, ne_eq, + not_false_eq_true, true_and, List.mem_reverse] + constructor + · rintro ⟨⟨h0, h10⟩, he, h⟩ + exact ⟨⟨he, h⟩, h10, by omega⟩ + · rintro ⟨⟨he, h⟩, h10, h0⟩ + exact ⟨⟨by omega, h10⟩, he, h⟩ + +theorem parseNat_iff (t : List Nat) (n : Nat) : parseNat t = some n ↔ t = render n := by + obtain ⟨ht, hv⟩ := digits_spec n + unfold parseNat render + constructor + · intro h + split at h + · next hc => + have hn : val t.reverse = n := by simpa using h + rcases (canonNat_iff t).1 hc with rfl | ⟨hne, htr⟩ + · simp [← hn, val] + · have hrev : t.reverse = digits n := val_inj htr ht (by rw [hn, hv]) + have : n ≠ 0 := by + rintro rfl + rw [digits] at hrev + simp at hrev + exact hne hrev + simp only [this, ↓reduceIte, ← hrev, List.reverse_reverse] + · simp at h + · rintro rfl + split + · next hn => + subst hn + simp [canonNat, val] + · next hn => + have hne : digits n ≠ [] := by + intro he + rw [he] at hv + exact hn hv.symm + have : canonNat (digits n).reverse = true := + (canonNat_iff _).2 (.inr ⟨by simpa using hne, by simpa using ht⟩) + simp [this, hv] + +/-- `MAX_NUMBER_LEN`. -/ +def maxLen : Nat := 64 + +def InI128 (n : Int) : Prop := -2 ^ 127 ≤ n ∧ n < 2 ^ 127 + +instance (n : Int) : Decidable (InI128 n) := inferInstanceAs (Decidable (_ ∧ _)) + +/-- Byte length of a text: one per digit plus the sign. -/ +def textLen (neg : Bool) (t : List Nat) : Nat := (if neg then 1 else 0) + t.length + +/-- The grammar `"0" | "-"? [1-9] [0-9]*`. -/ +def parseInt (neg : Bool) (t : List Nat) : Option Int := + match parseNat t with + | some m => if neg then (if m = 0 then none else some (-(m : Int))) else some m + | none => none + +/-- The `int` parser: grammar, length limit, then `str::parse::`. -/ +def parseI128 (neg : Bool) (t : List Nat) : Option Int := + if textLen neg t ≤ maxLen then (parseInt neg t).filter (InI128 ·) else none + +/-- `i128::to_string`. -/ +def renderInt (n : Int) : Bool × List Nat := (decide (n < 0), render n.natAbs) + +theorem parseInt_iff (neg : Bool) (t : List Nat) (n : Int) : + parseInt neg t = some n ↔ (neg, t) = renderInt n := by + unfold parseInt renderInt + constructor + · intro h + split at h + · next m hm => + rw [parseNat_iff] at hm + subst hm + cases neg + · simp only [Bool.false_eq_true, ↓reduceIte, Option.some.injEq] at h + subst h + simp + · simp only [↓reduceIte] at h + split at h + · simp at h + · next hm => + simp only [Option.some.injEq] at h + subst h + simp + omega + · simp at h + · intro h + simp only [Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + rw [(parseNat_iff _ _).2 rfl] + by_cases hn : n < 0 + · have : n.natAbs ≠ 0 := by omega + simp only [hn, decide_true, ↓reduceIte, this, Option.some.injEq] + omega + · simp only [hn, decide_false, Bool.false_eq_true, ↓reduceIte, Option.some.injEq] + omega + +/-- An `i128` prints in at most 40 bytes, below `MAX_NUMBER_LEN`. -/ +theorem renderInt_length (n : Int) (h : InI128 n) : + textLen (renderInt n).1 (renderInt n).2 ≤ 40 := by + have hlen : (render n.natAbs).length ≤ 39 := by + unfold render + split + · simp + · rw [List.length_reverse] + refine digits_length 39 _ ?_ + have : (2 : Nat) ^ 127 < 10 ^ 39 := by decide + have h2 : ((2 : Nat) ^ 127 : Int) = (2 : Int) ^ 127 := by decide + obtain ⟨h1, h3⟩ := h + omega + simp only [renderInt, textLen] + by_cases hn : n < 0 <;> simp only [hn, decide_true, decide_false, Bool.false_eq_true, + ↓reduceIte] <;> omega + +theorem parseI128_iff (neg : Bool) (t : List Nat) (n : Int) : + parseI128 neg t = some n ↔ InI128 n ∧ (neg, t) = renderInt n := by + unfold parseI128 + constructor + · intro h + split at h + · rw [Option.filter_eq_some_iff] at h + exact ⟨by simpa using h.2, (parseInt_iff _ _ _).1 h.1⟩ + · simp at h + · rintro ⟨hn, h⟩ + have hlen : textLen neg t ≤ 40 := by + have := renderInt_length n hn + rw [← h] at this + exact this + have : textLen neg t ≤ maxLen := by unfold maxLen; omega + simp [this, (parseInt_iff _ _ _).2 h, Option.filter, hn] + +theorem parseI128_inj {neg neg' : Bool} {t t' : List Nat} {n : Int} + (h : parseI128 neg t = some n) (h' : parseI128 neg' t' = some n) : + (neg, t) = (neg', t') := + ((parseI128_iff _ _ _).1 h).2.trans ((parseI128_iff _ _ _).1 h').2.symm + +/-! ## Ranges -/ + +inductive Bound (α : Type) where + | incl (a : α) + | excl (a : α) + | unb + +abbrev Range (α : Type) := Bound α × Bound α + +section Order + +variable {α : Type} (lt : α → α → Prop) + +def Le (a b : α) : Prop := lt a b ∨ a = b + +def Above : Bound α → α → Prop + | .incl s, x => Le lt s x + | .excl s, x => lt s x + | .unb, _ => True + +def Below : Bound α → α → Prop + | .incl e, x => Le lt x e + | .excl e, x => lt x e + | .unb, _ => True + +/-- `RangeBounds::contains` on a pair of bounds. -/ +def Contains (r : Range α) (x : α) : Prop := Above lt r.1 x ∧ Below lt r.2 x + +/-- The bound comparison a range must pass in `range`. -/ +def Ordered : Range α → Prop + | (.incl s, .incl e) => Le lt s e + | (.incl s, .excl e) | (.excl s, .incl e) | (.excl s, .excl e) => lt s e + | _ => True + +/-- A range holding a value passes the comparison: only empty ranges are +rejected. -/ +theorem ordered_of_contains (trans : ∀ {a b c}, lt a b → lt b c → lt a c) + (r : Range α) (x : α) (h : Contains lt r x) : Ordered lt r := by + obtain ⟨s, e⟩ := r + cases s <;> cases e <;> simp only [Ordered] <;> simp only [Contains, Above, Below] at h + · rcases h with ⟨hs | rfl, he | rfl⟩ + · exact .inl (trans hs he) + · exact .inl hs + · exact .inl he + · exact .inr rfl + · rcases h with ⟨hs | rfl, he⟩ + · exact trans hs he + · exact he + · rcases h with ⟨hs, he | rfl⟩ + · exact trans hs he + · exact hs + · exact trans h.1 h.2 + +/-- An accepted range with an inclusive bound holds that bound. -/ +theorem contains_of_ordered (r : Range α) (h : Ordered lt r) : + match r with + | (.incl s, .incl _) | (.incl s, .excl _) | (.incl s, .unb) => Contains lt r s + | (.excl _, .incl e) | (.unb, .incl e) => Contains lt r e + | _ => True := by + obtain ⟨s, e⟩ := r + cases s <;> cases e <;> first + | trivial + | exact ⟨.inr rfl, h⟩ + | exact ⟨h, .inr rfl⟩ + | exact ⟨.inr rfl, trivial⟩ + | exact ⟨trivial, .inr rfl⟩ + +end Order + +/-! ## Integer ranges -/ + +def ContainsInt (r : Range Int) (n : Int) : Prop := Contains (· < ·) r n + +/-- Smallest candidate of a start bound; `checked_add` fails at `i128::MAX`. -/ +def first : Bound Int → Option Int + | .incl n => some n + | .excl n => if n + 1 < 2 ^ 127 then some (n + 1) else none + | .unb => some (-2 ^ 127) + +/-- Largest candidate of an end bound; `checked_sub` fails at `i128::MIN`. -/ +def last : Bound Int → Option Int + | .incl n => some n + | .excl n => if -2 ^ 127 ≤ n - 1 then some (n - 1) else none + | .unb => some (2 ^ 127 - 1) + +/-- `has_int`. -/ +def HasInt (r : Range Int) : Prop := + match first r.1, last r.2 with + | some f, some l => f ≤ l + | _, _ => False + +instance (r : Range Int) : Decidable (HasInt r) := by + unfold HasInt + split <;> infer_instance + +def BoundInI128 : Bound Int → Prop + | .incl n | .excl n => InI128 n + | .unb => True + +theorem first_spec (b : Bound Int) (hb : BoundInI128 b) : + match first b with + | some f => InI128 f ∧ Above (· < ·) b f ∧ ∀ n, InI128 n → (Above (· < ·) b n ↔ f ≤ n) + | none => ∀ n, InI128 n → ¬Above (· < ·) b n := by + cases b with + | incl a => exact ⟨hb, .inr rfl, fun n _ => by simp only [Above, Le]; omega⟩ + | excl a => + simp only [BoundInI128, InI128] at hb + by_cases c : a + 1 < 2 ^ 127 + · rw [show first (.excl a) = some (a + 1) by simp [first]; omega] + refine ⟨by simp only [InI128]; omega, ?_, fun n _ => ?_⟩ <;> simp only [Above] <;> omega + · rw [show first (.excl a) = none by simp [first]; omega] + intro n hn + simp only [Above, InI128] at hn ⊢ + omega + | unb => + exact ⟨by simp only [InI128]; omega, trivial, fun n hn => ⟨fun _ => hn.1, fun _ => trivial⟩⟩ + +theorem last_spec (b : Bound Int) (hb : BoundInI128 b) : + match last b with + | some l => InI128 l ∧ Below (· < ·) b l ∧ ∀ n, InI128 n → (Below (· < ·) b n ↔ n ≤ l) + | none => ∀ n, InI128 n → ¬Below (· < ·) b n := by + cases b with + | incl a => exact ⟨hb, .inr rfl, fun n _ => by simp only [Below, Le]; omega⟩ + | excl a => + simp only [BoundInI128, InI128] at hb + by_cases c : -2 ^ 127 ≤ a - 1 + · rw [show last (.excl a) = some (a - 1) by simp [last]; omega] + refine ⟨by simp only [InI128]; omega, ?_, fun n _ => ?_⟩ <;> simp only [Below] <;> omega + · rw [show last (.excl a) = none by simp [last]; omega] + intro n hn + simp only [Below, InI128] at hn ⊢ + omega + | unb => + refine ⟨by simp only [InI128]; omega, trivial, fun n hn => ⟨fun _ => ?_, fun _ => trivial⟩⟩ + have := hn.2 + omega + +/-- `has_int` holds iff the range holds an `i128`. -/ +theorem hasInt_iff (r : Range Int) (hs : BoundInI128 r.1) (he : BoundInI128 r.2) : + HasInt r ↔ ∃ n, InI128 n ∧ ContainsInt r n := by + have hf := first_spec r.1 hs + have hl := last_spec r.2 he + simp only [HasInt, ContainsInt, Contains] + revert hf hl + cases first r.1 <;> cases last r.2 <;> intro hf hl <;> dsimp only at hf hl ⊢ + · exact ⟨False.elim, fun ⟨n, hn, ha, _⟩ => hf n hn ha⟩ + · exact ⟨False.elim, fun ⟨n, hn, ha, _⟩ => hf n hn ha⟩ + · exact ⟨False.elim, fun ⟨n, hn, _, hb⟩ => hl n hn hb⟩ + · next f l => + constructor + · exact fun h => ⟨f, hf.1, hf.2.1, (hl.2.2 f hf.1).2 h⟩ + · rintro ⟨n, hn, ha, hb⟩ + exact Int.le_trans ((hf.2.2 n hn).1 ha) ((hl.2.2 n hn).1 hb) + +/-- An `int` range that passes `has_int` also passes the bound comparison. -/ +theorem ordered_of_hasInt (r : Range Int) (hs : BoundInI128 r.1) (he : BoundInI128 r.2) + (h : HasInt r) : Ordered (· < ·) r := + let ⟨n, _, hn⟩ := (hasInt_iff r hs he).1 h + ordered_of_contains (· < ·) Int.lt_trans r n hn + +/-! ## `ValueSpec::matches` for `int` specs -/ + +def MatchesInt (ranges : List (Range Int)) (neg : Bool) (t : List Nat) : Prop := + ∃ n, parseI128 neg t = some n ∧ ∃ r ∈ ranges, ContainsInt r n + +/-- An `int` spec accepts exactly the canonical spellings of the `i128` values +inside one of its ranges. -/ +theorem matchesInt_iff (ranges : List (Range Int)) (neg : Bool) (t : List Nat) : + MatchesInt ranges neg t ↔ + ∃ n, InI128 n ∧ (neg, t) = renderInt n ∧ ∃ r ∈ ranges, ContainsInt r n := by + simp only [MatchesInt, parseI128_iff, and_assoc] + +/-! ## Rust unit tests restated -/ + +-- `values_must_be_canonical`: "0", "7", "-7", "10"; then "", "-", "07", "-0", "00". +example : parseI128 false [0] = some 0 := by decide +example : parseI128 false [7] = some 7 := by decide +example : parseI128 true [7] = some (-7) := by decide +example : parseI128 false [1, 0] = some 10 := by decide +example : parseI128 false [] = none := by decide +example : parseI128 true [] = none := by decide +example : parseI128 false [0, 7] = none := by decide +example : parseI128 true [0] = none := by decide +example : parseI128 false [0, 0] = none := by decide + +-- `empty_ranges_are_rejected`: `5..<5`, `5<..=5`, `5<..<5`, `5<..<6`, `5..=4`. +example : ¬HasInt (.incl 5, .excl 5) := by decide +example : ¬HasInt (.excl 5, .incl 5) := by decide +example : ¬HasInt (.excl 5, .excl 5) := by decide +example : ¬HasInt (.excl 5, .excl 6) := by decide +example : ¬HasInt (.incl 5, .incl 4) := by decide +example : HasInt (.excl 4, .excl 6) := by decide + +-- `int_is_bounded_by_i128`: `.. Date: Wed, 25 Nov 2026 04:42:27 -0800 Subject: [PATCH 02/25] feat(dstack-util): validate env values against specs in allowed_envs Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 21 +++++- dstack/Cargo.lock | 1 + dstack/Cargo.toml | 1 + dstack/dstack-util/Cargo.toml | 1 + dstack/dstack-util/src/parse_env_file.rs | 89 ++++++++++++++++++++++-- dstack/dstack-util/src/system_setup.rs | 11 +-- formal/DstackFormal/Guest/EnvFile.lean | 81 ++++++++++++--------- 7 files changed, 157 insertions(+), 48 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index d5ac6e82b..cb76a661a 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -37,7 +37,7 @@ This is the main configuration file for the application in JSON format: | public_logs | 0.3.3 | boolean | Whether logs are publicly visible | | public_sysinfo | 0.3.3 | boolean | Whether system info is public. Covers the guest dashboard and `/metrics`, including the `dstack_gpu_*` series (since 0.6.0), which expose each GPU's UUID and PCI bus address alongside utilization, memory, temperature and power. | | public_tcbinfo | 0.5.1 | boolean | Whether TCB info is public | -| allowed_envs | 0.4.2 | array of string | List of allowed environment variable names | +| allowed_envs | 0.4.2 | array of string | List of allowed environment variable names. An entry may be `NAME:spec` to also constrain the value, see [Environment value specs](#environment-value-specs). | | no_instance_id | 0.4.2 | boolean | Disable instance ID generation | | secure_time | 0.5.0 | boolean | Whether secure time is enabled | | pre_launch_script | 0.4.0 | string | Prelaunch bash script that runs before `docker compose up`. It runs *after* dockerd, so containers restored by a Docker restart policy can already be running when it executes. Do not build security gates on it — see [security-best-practices.md](./security-best-practices.md#security-semantics-must-not-depend-on-pre_launch_script-running-first). | @@ -126,11 +126,28 @@ dstack uses encrypted environment variables to allow app developers to securely - CVM derives the shared secret using the ephemeral public key via X25519 key exchange - CVM decrypts the ciphertext using AESGCM with the derived shared secret - CVM parses the JSON and only stores variables listed in allowed_envs from app-compose.json - - CVM performs basic regex validation on values + - CVM validates variable names and checks each value against the specs given in allowed_envs - Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env` This file is not measured to RTMRs, and the envelope is not bound to an instance or compose hash: the KMS derives `env_crypt_key` from the app ID alone, so the host can withhold the file or replay any earlier ciphertext for the same app. It is highly recommended to add application-specific integrity checks, such as a version or expiry inside the plaintext, at the application layer. See [security-best-practices.md](./security-best-practices.md) for more details. +#### Environment value specs + +Since 0.6.7, an `allowed_envs` entry may be `NAME:spec`. The CVM refuses to boot when the value of `NAME` does not match the spec. A spec is one of: + +| Spec | Accepts | +|------|---------| +| `int` | any integer within `i128` | +| `int(1..=65535)` | integers from 1 to 65535 | +| `int(0\|1024..<65536)` | 0, or integers from 1024 up to but excluding 65536 | +| `float` | any decimal number, compared exactly | +| `float(0<..=1)` | decimals above 0 and up to 1 | +| `/mainnet\|testnet/` | values the regex matches in full | + +A range is `start..=end` or `start.., } -pub fn parse_env(env_json: &[u8], allowed: &BTreeSet) -> Result> { +/// The specs each allowed name's value must match. +pub type AllowedEnvs = BTreeMap>; + +/// Parses `allowed_envs` entries, each a name optionally followed by `:` and a +/// value spec. +pub fn parse_allowed_envs(entries: &[String]) -> Result { + let mut allowed = AllowedEnvs::new(); + for entry in entries { + let (name, spec) = match entry.split_once(':') { + Some((name, spec)) => (name, Some(spec)), + None => (entry.as_str(), None), + }; + let spec = spec + .map(str::parse) + .transpose() + .with_context(|| format!("invalid value spec for env {name}"))?; + allowed.entry(name.to_string()).or_default().extend(spec); + } + Ok(allowed) +} + +pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result> { const MAX_ITEMS: usize = 1024; const MAX_TOTAL_SIZE: usize = 1024 * 1024; @@ -58,10 +80,10 @@ pub fn parse_env(env_json: &[u8], allowed: &BTreeSet) -> Result 255 { bail!("Environment variable name too long: {}", key); @@ -77,6 +99,10 @@ pub fn parse_env(env_json: &[u8], allowed: &BTreeSet) -> Result MAX_TOTAL_SIZE { bail!("Environment variables total size too large"); @@ -115,6 +141,61 @@ mod tests { assert_eq!(escape_value("cr\r"), "\"cr\r\""); } + fn parse(allowed: &[&str], env: &[(&str, &str)]) -> Result> { + let allowed = allowed.iter().map(|s| s.to_string()).collect::>(); + let env: Vec<_> = env + .iter() + .map(|(key, value)| serde_json::json!({ "key": key, "value": value })) + .collect(); + let json = serde_json::to_vec(&serde_json::json!({ "env": env }))?; + parse_env(&json, &parse_allowed_envs(&allowed)?) + } + + #[test] + fn values_are_checked_against_specs() { + let allowed = [ + "PORT:int(1..=65535)", + "NET:/main|test/", + "URL:/https://.*/", + "ANY", + ]; + let env = [ + ("PORT", "8080"), + ("NET", "test"), + ("URL", "https://a:1/"), + ("ANY", "x y"), + ]; + assert_eq!(parse(&allowed, &env).unwrap().len(), 4); + assert!(parse(&allowed, &[("OTHER", "1")]).unwrap().is_empty()); + for bad in [ + ("PORT", "0"), + ("PORT", "80 "), + ("NET", "mainnet"), + ("URL", "http://a"), + ] { + let err = parse(&allowed, &[bad]).unwrap_err().to_string(); + assert!(!err.contains(bad.1), "{err}"); + } + } + + #[test] + fn repeated_names_must_match_every_spec() { + for allowed in [["N:int(0..=9)", "N"], ["N", "N:int(0..=9)"]] { + assert!(parse(&allowed, &[("N", "9")]).is_ok()); + assert!(parse(&allowed, &[("N", "10")]).is_err()); + } + let allowed = ["N:int(0..=9)", "N:int(5..)"]; + assert!(parse(&allowed, &[("N", "5")]).is_ok()); + assert!(parse(&allowed, &[("N", "4")]).is_err()); + } + + #[test] + fn invalid_specs_are_rejected() { + for entry in ["A:", "A:int(", "A:string", "A:int:int"] { + assert!(parse(&[entry], &[]).is_err(), "{entry}"); + } + } + /// Round-trip through systemd's own parser; skipped without a user manager. #[test] fn systemd_round_trip() { diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 51ba3436a..74edaa8e5 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::BTreeMap, fmt::Display, io::Write as _, net::{Ipv4Addr, Ipv6Addr}, @@ -3435,13 +3435,8 @@ impl Stage1<'_> { } async fn unseal_env_vars(&self) -> Result> { - let allowed_envs: BTreeSet = self - .shared - .app_compose - .allowed_envs - .iter() - .cloned() - .collect(); + let allowed_envs = + crate::parse_env_file::parse_allowed_envs(&self.shared.app_compose.allowed_envs)?; let (decrypted_env, sealed) = if self.shared.sealed_env.is_none() && self.shared.encrypted_env.is_empty() { info!("No encrypted env, using default"); diff --git a/formal/DstackFormal/Guest/EnvFile.lean b/formal/DstackFormal/Guest/EnvFile.lean index 197164264..88d14566e 100644 --- a/formal/DstackFormal/Guest/EnvFile.lean +++ b/formal/DstackFormal/Guest/EnvFile.lean @@ -20,15 +20,18 @@ Proven: encoding is lossy (`newline_collision`), as the Rust doc comment states. * `validKey_safe`: keys passing `KEY_REGEX` are nonempty and contain no `=`, whitespace, `#` or quote, so `KEY=value` lines split at the first `=`. -* `parseEnv_spec`: every accepted entry is allowed, has a valid key and - respects the length limits; unauthorized keys are dropped, not rejected. +* `parseEnv_spec`: every accepted entry is allowed, has a valid key, matches + its value specs and respects the length limits; unauthorized keys are + dropped, not rejected. Assumptions: Rust's `char::is_whitespace` is a parameter `rustWs` required to -hold for systemd's `WHITESPACE` (` `, `\t`, `\n`, `\r`). +hold for systemd's `WHITESPACE` (` `, `\t`, `\n`, `\r`). Whether a value matches +every spec of its name is a parameter `matchesSpecs`; `Guest.ValueSpec` models +the specs themselves. Modeling gaps: the systemd parser model is limited to one value line, is written from the upstream state machine rather than extracted from it, and the Rust `systemd_round_trip` test is its only executable cross-check; JSON -decoding, `MAX_ITEMS`, and the `BTreeMap` (later duplicates override) are not +decoding, `parse_allowed_envs`, `MAX_ITEMS`, and the `BTreeMap` (later duplicates override) are not modeled; lengths are counted in chars, not UTF-8 bytes. -/ @@ -262,24 +265,27 @@ theorem validKey_safe (k : List Char) (h : validKey k = true) : #guard !validKey [] /-- The loop of `parse_env` over decoded pairs; `none` is an error. -/ -def parseEnvGo (allowed : List Char → Bool) : +def parseEnvGo (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) : Nat → List (List Char × List Char) → Option (List (List Char × List Char)) | _, [] => some [] | total, (k, v) :: rest => - if !allowed k then parseEnvGo allowed total rest + if !allowed k then parseEnvGo allowed matchesSpecs total rest else if k.length > 255 then none else if v.length > 128 * 1024 then none else if !validKey k then none + else if !matchesSpecs k v then none else if total + k.length + v.length > 1024 * 1024 then none - else ((k, v) :: ·) <$> parseEnvGo allowed (total + k.length + v.length) rest + else ((k, v) :: ·) <$> parseEnvGo allowed matchesSpecs (total + k.length + v.length) rest -def parseEnv (allowed : List Char → Bool) (pairs : List (List Char × List Char)) : - Option (List (List Char × List Char)) := parseEnvGo allowed 0 pairs +def parseEnv (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) + (pairs : List (List Char × List Char)) : Option (List (List Char × List Char)) := + parseEnvGo allowed matchesSpecs 0 pairs -theorem parseEnvGo_spec (allowed : List Char → Bool) : - ∀ (total : Nat) (pairs out : List (List Char × List Char)), parseEnvGo allowed total pairs = some out → +theorem parseEnvGo_spec (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) : + ∀ (total : Nat) (pairs out : List (List Char × List Char)), + parseEnvGo allowed matchesSpecs total pairs = some out → out.Sublist pairs ∧ ∀ kv ∈ out, allowed kv.1 = true ∧ validKey kv.1 = true ∧ - kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024 + matchesSpecs kv.1 kv.2 = true ∧ kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024 | _, [], out, h => by simp [parseEnvGo] at h; subst h; simp | total, (k, v) :: rest, out, h => by unfold parseEnvGo at h @@ -290,35 +296,42 @@ theorem parseEnvGo_spec (allowed : List Char → Bool) : by_cases h2 : v.length > 128 * 1024 · simp [h1, h2] at h by_cases h3 : validKey k = true - · by_cases h4 : total + k.length + v.length > 1024 * 1024 - · simp [h1, h2, h3, h4] at h - simp only [h1, h2, h3, h4, ite_false, Bool.not_true, Bool.false_eq_true] at h - cases hr : parseEnvGo allowed (total + k.length + v.length) rest with - | none => simp [hr] at h - | some out' => - simp only [hr, Option.some.injEq, Functor.map, Option.map] at h - subst h - obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed _ rest out' hr - refine ⟨hs.cons_cons _, ?_⟩ - intro kv hkv - rcases List.mem_cons.mp hkv with rfl | hkv - · exact ⟨ha, h3, by dsimp only; omega, by dsimp only; omega⟩ - · exact hp kv hkv + · by_cases h5 : matchesSpecs k v = true + · by_cases h4 : total + k.length + v.length > 1024 * 1024 + · simp [h1, h2, h3, h4, h5] at h + simp only [h1, h2, h3, h4, h5, ite_false, Bool.not_true, Bool.false_eq_true] at h + cases hr : parseEnvGo allowed matchesSpecs (total + k.length + v.length) rest with + | none => simp [hr] at h + | some out' => + simp only [hr, Option.some.injEq, Functor.map, Option.map] at h + subst h + obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed matchesSpecs _ rest out' hr + refine ⟨hs.cons_cons _, ?_⟩ + intro kv hkv + rcases List.mem_cons.mp hkv with rfl | hkv + · exact ⟨ha, h3, h5, by dsimp only; omega, by dsimp only; omega⟩ + · exact hp kv hkv + · simp [h1, h2, h3, h5] at h · simp [h1, h2, h3] at h · simp only [Bool.not_eq_true] at ha simp only [ha, Bool.not_false, ite_true] at h - obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed total rest out h + obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed matchesSpecs total rest out h exact ⟨hs.cons _, hp⟩ -/-- Every accepted entry is allowed, has a valid key and respects the limits. -/ -theorem parseEnv_spec (allowed : List Char → Bool) (pairs out : List (List Char × List Char)) - (h : parseEnv allowed pairs = some out) : +/-- Every accepted entry is allowed, has a valid key, matches its specs and +respects the limits. -/ +theorem parseEnv_spec (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) + (pairs out : List (List Char × List Char)) (h : parseEnv allowed matchesSpecs pairs = some out) : out.Sublist pairs ∧ ∀ kv ∈ out, allowed kv.1 = true ∧ validKey kv.1 = true ∧ - kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024 := - parseEnvGo_spec allowed 0 pairs out h + matchesSpecs kv.1 kv.2 = true ∧ kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024 := + parseEnvGo_spec allowed matchesSpecs 0 pairs out h /-- Unauthorized keys are skipped, not rejected. -/ -example : parseEnv (fun k => k == "A".toList) [("B".toList, []), ("A".toList, "1".toList)] = - some [("A".toList, "1".toList)] := by decide +example : parseEnv (fun k => k == "A".toList) (fun _ _ => true) + [("B".toList, []), ("A".toList, "1".toList)] = some [("A".toList, "1".toList)] := by decide + +/-- A value failing its specs is an error, not a skip. -/ +example : parseEnv (fun _ => true) (fun _ v => v == "1".toList) + [("A".toList, "1".toList), ("B".toList, "2".toList)] = none := by decide end DstackFormal.Guest.EnvFile From 967353cbcfd2a944f42c227aca828f5cb3626fe8 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 04:46:39 -0800 Subject: [PATCH 03/25] feat(dstack-util): add validate-env subcommand Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 9 +++++ dstack/dstack-util/src/main.rs | 38 ++++++++++++++++++ dstack/dstack-util/src/parse_env_file.rs | 49 ++++++++++++++++++++++-- 3 files changed, 93 insertions(+), 3 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index cb76a661a..75ffd008c 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -146,6 +146,15 @@ Since 0.6.7, an `allowed_envs` entry may be `NAME:spec`. The CVM refuses to boot A range is `start..=end` or `start.., + /// JSON object mapping variable names to values, checked instead of the environment + #[arg(long)] + env_file: Option, + /// Variables that must be set, as `NAME:spec` or `NAME` + #[arg(required_unless_present = "compose")] + specs: Vec, } #[derive(Parser)] @@ -118,6 +133,28 @@ struct ExecWithEnvArgs { command: Vec, } +fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { + let env: Option> = args + .env_file + .map(|path| { + utils::deserialize_json_file(&path) + .with_context(|| format!("failed to load env from {}", path.display())) + }) + .transpose()?; + let compose: Option = args + .compose + .map(|path| { + utils::deserialize_json_file(&path) + .with_context(|| format!("failed to load app compose from {}", path.display())) + }) + .transpose()?; + let optional = compose.map(|c| c.allowed_envs).unwrap_or_default(); + parse_env_file::validate_env(&args.specs, &optional, |name| match &env { + Some(env) => env.get(name).cloned(), + None => std::env::var(name).ok(), + }) +} + #[derive(Parser)] /// Hex encode data struct HexCommand { @@ -1700,6 +1737,7 @@ async fn main() -> Result<()> { gpu_info::cmd_gpu_info()?; } Commands::ExecWithEnv(args) => cmd_exec_with_env(args)?, + Commands::ValidateEnv(args) => cmd_validate_env(args)?, } Ok(()) diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index 9c5f47bb3..4fff3c0a5 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -62,6 +62,32 @@ pub fn parse_allowed_envs(entries: &[String]) -> Result { Ok(allowed) } +fn check_value(name: &str, value: &str, specs: &[ValueSpec]) -> Result<()> { + if !specs.iter().all(|spec| spec.matches(value)) { + bail!("value of env {name} does not match its spec"); + } + Ok(()) +} + +/// Checks variables against `allowed_envs`-style entries. Those named by +/// `required` must be set; those named by `optional` are checked when set. +pub fn validate_env( + required: &[String], + optional: &[String], + get: impl Fn(&str) -> Option, +) -> Result<()> { + for (name, specs) in parse_allowed_envs(optional)? { + if let Some(value) = get(&name) { + check_value(&name, &value, &specs)?; + } + } + for (name, specs) in parse_allowed_envs(required)? { + let value = get(&name).with_context(|| format!("env {name} is not set"))?; + check_value(&name, &value, &specs)?; + } + Ok(()) +} + pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result> { const MAX_ITEMS: usize = 1024; const MAX_TOTAL_SIZE: usize = 1024 * 1024; @@ -99,9 +125,7 @@ pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result MAX_TOTAL_SIZE { @@ -196,6 +220,25 @@ mod tests { } } + #[test] + fn validate_env_requires_only_required_variables() { + let get = |name: &str| (name == "PORT").then(|| "8080".to_string()); + let check = |required: &[&str], optional: &[&str]| { + let [required, optional] = + [required, optional].map(|v| v.iter().map(|s| s.to_string()).collect::>()); + validate_env(&required, &optional, get) + }; + assert!(check(&["PORT:int(1..=65535)", "PORT"], &[]).is_ok()); + assert!(check(&["PORT:int(1..=1024)"], &[]).is_err()); + assert!(check(&["PORT:int", "HOST"], &[]).is_err()); + assert!(check(&["PORT:string"], &[]).is_err()); + + assert!(check(&[], &["PORT:int(1..=65535)", "HOST:/a/"]).is_ok()); + assert!(check(&[], &["PORT:int(1..=1024)"]).is_err()); + assert!(check(&[], &["HOST:string"]).is_err()); + assert!(check(&["PORT:int(8080)"], &["PORT:int(1..=1024)"]).is_err()); + } + /// Round-trip through systemd's own parser; skipped without a user manager. #[test] fn systemd_round_trip() { From e4fdafe21d97ea206e434b3d57439dce5c1c1419 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 07:26:14 -0800 Subject: [PATCH 04/25] feat(value-spec): accept the empty string with a trailing ? Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 3 +- dstack/value-spec/src/lib.rs | 51 ++++++++++++++++++++++-- formal/DstackFormal/Guest/ValueSpec.lean | 4 +- 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 75ffd008c..f4ad1e4d7 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -143,8 +143,9 @@ Since 0.6.7, an `allowed_envs` entry may be `NAME:spec`. The CVM refuses to boot | `float` | any decimal number, compared exactly | | `float(0<..=1)` | decimals above 0 and up to 1 | | `/mainnet\|testnet/` | values the regex matches in full | +| `int(1..=65535)?` | the empty string, or integers from 1 to 65535 | -A range is `start..=end` or `start.. = fn(&mut &str) -> ModalResult; impl ValueSpec { /// Returns whether `value` satisfies the spec. pub fn matches(&self, value: &str) -> bool { - match &self.0 { + if self.optional && value.is_empty() { + return true; + } + match &self.kind { Kind::Int(ranges) => contains(ranges, int, value), Kind::Float(ranges) => contains(ranges, decimal, value), Kind::Regex(regex) => regex.is_match(value), @@ -111,8 +125,9 @@ impl FromStr for ValueSpec { ranges("float", decimal).map(Kind::Float), fail.context(Expected(Description("`int`, `float` or `/regex/`"))), )); + let (s, optional) = s.strip_suffix('?').map_or((s, false), |s| (s, true)); terminated(spec, eof.context(Expected(Description("end of spec")))) - .map(Self) + .map(|kind| Self { kind, optional }) .parse(s) .map_err(|e| ParseError { offset: e.offset(), @@ -541,6 +556,36 @@ mod tests { ]); } + #[test] + fn optional_specs_accept_empty() { + check("int?", &["", "0", "-1"], &[" ", "a", "1.5"]); + check("int(1..=65535)?", &["", "1", "65535"], &["0", " ", "?"]); + check("int(0|5..)?", &["", "0", "5"], &["1"]); + check("float?", &["", "0.5"], &[".", "-"]); + check("float(0<..=1)?", &["", "1", "0.5"], &["0", "1.5"]); + check("/a|b/?", &["", "a", "b"], &["c", "ab"]); + check("/a?/", &["", "a"], &["aa", "?"]); + check("/a/?/", &["a/", "a"], &["", "a/?"]); + check("/a+/", &["a"], &[""]); + for spec in ["int", "int(0..)", "float", "float(..)", "/.+/"] { + check(spec, &[], &[""]); + } + check_invalid(&[ + "?", + "int??", + "int(1)??", + "int?(1)", + "int(1?)", + "int(1..=2?)", + "/a?", + "/?", + "/a/??", + "int ?", + "int(1)?x", + "float(?)", + ]); + } + #[test] fn invalid_specs() { check_invalid(&[ diff --git a/formal/DstackFormal/Guest/ValueSpec.lean b/formal/DstackFormal/Guest/ValueSpec.lean index 08b73a00b..79a573a55 100644 --- a/formal/DstackFormal/Guest/ValueSpec.lean +++ b/formal/DstackFormal/Guest/ValueSpec.lean @@ -27,8 +27,8 @@ Assumptions: `BigDecimal`'s ordering is a parameter `lt` required to be transitive. Modeling gaps: a text is a sign and a list of digit values, so ASCII decoding and non-digit characters are not modeled; `i128::to_string` is modeled as -`renderInt`; the `float` grammar, the spec syntax (the winnow parser) and -regexes are not modeled. An accepted `float` range between two bounds may +`renderInt`; the `float` grammar, the spec syntax (the winnow parser), the +trailing `?` that also accepts the empty string and regexes are not modeled. An accepted `float` range between two bounds may still hold no decimal of at most `MAX_NUMBER_LEN` bytes. -/ From c70fdd5647dbc12f3fc9f82265fb6817d0613ca3 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 07:41:06 -0800 Subject: [PATCH 05/25] feat(dstack-util): check env values against specs in exec-with-env Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 4 ++- dstack/dstack-util/src/main.rs | 53 ++++++++++++++++------------ os/common/rootfs/app-compose.service | 4 +-- 3 files changed, 36 insertions(+), 25 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index f4ad1e4d7..5a62fa59b 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -127,7 +127,7 @@ dstack uses encrypted environment variables to allow app developers to securely - CVM decrypts the ciphertext using AESGCM with the derived shared secret - CVM parses the JSON and only stores variables listed in allowed_envs from app-compose.json - CVM validates variable names and checks each value against the specs given in allowed_envs - - Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env` + - Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env`, which checks the values against the specs again This file is not measured to RTMRs, and the envelope is not bound to an instance or compose hash: the KMS derives `env_crypt_key` from the app ID alone, so the host can withhold the file or replay any earlier ciphertext for the same app. It is highly recommended to add application-specific integrity checks, such as a version or expiry inside the plaintext, at the application layer. See [security-best-practices.md](./security-best-practices.md) for more details. @@ -156,6 +156,8 @@ PORT=$PORT dstack-util validate-env 'PORT:int(1024..=65535)' || exit 1 dstack-util validate-env --compose /dstack/app-compose.json --env-file /dstack/.host-shared/.user-config || exit 1 ``` +`app-compose.service` passes `--compose /dstack/app-compose.json` to `dstack-util exec-with-env`, so an `init_script` that rewrites `.decrypted-env.json` cannot hand the application a value that breaks an `allowed_envs` spec. + Guests older than 0.6.7 treat `NAME:spec` as a name that no variable can have, so they drop the variable rather than deliver it unchecked. ### .user-config diff --git a/dstack/dstack-util/src/main.rs b/dstack/dstack-util/src/main.rs index fa007b45d..94177684b 100644 --- a/dstack/dstack-util/src/main.rs +++ b/dstack/dstack-util/src/main.rs @@ -128,31 +128,38 @@ struct ExecWithEnvArgs { /// JSON object mapping variable names to values #[arg(long)] env_file: PathBuf, + /// App compose file whose `allowed_envs` specs the values must match + #[arg(long)] + compose: Option, /// Command to exec, with its arguments #[arg(last = true, required = true)] command: Vec, } +type Envs = std::collections::BTreeMap; + +fn load_envs(path: &Path) -> Result { + utils::deserialize_json_file(path) + .with_context(|| format!("failed to load env from {}", path.display())) +} + +fn load_allowed_envs(path: &Path) -> Result> { + let compose: utils::AppCompose = utils::deserialize_json_file(path) + .with_context(|| format!("failed to load app compose from {}", path.display()))?; + Ok(compose.allowed_envs) +} + fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { - let env: Option> = args - .env_file - .map(|path| { - utils::deserialize_json_file(&path) - .with_context(|| format!("failed to load env from {}", path.display())) - }) - .transpose()?; - let compose: Option = args - .compose - .map(|path| { - utils::deserialize_json_file(&path) - .with_context(|| format!("failed to load app compose from {}", path.display())) - }) - .transpose()?; - let optional = compose.map(|c| c.allowed_envs).unwrap_or_default(); - parse_env_file::validate_env(&args.specs, &optional, |name| match &env { - Some(env) => env.get(name).cloned(), - None => std::env::var(name).ok(), - }) + let envs = args.env_file.as_deref().map(load_envs).transpose()?; + let allowed = args.compose.as_deref().map(load_allowed_envs).transpose()?; + parse_env_file::validate_env( + &args.specs, + &allowed.unwrap_or_default(), + |name| match &envs { + Some(envs) => envs.get(name).cloned(), + None => std::env::var(name).ok(), + }, + ) } #[derive(Parser)] @@ -771,9 +778,11 @@ async fn cmd_get_keys(args: GetKeysArgs) -> Result<()> { fn cmd_exec_with_env(args: ExecWithEnvArgs) -> Result<()> { use std::os::unix::process::CommandExt; - let envs: std::collections::BTreeMap = - utils::deserialize_json_file(&args.env_file) - .with_context(|| format!("failed to load env from {}", args.env_file.display()))?; + let envs = load_envs(&args.env_file)?; + if let Some(compose) = &args.compose { + let allowed = load_allowed_envs(compose)?; + parse_env_file::validate_env(&[], &allowed, |name| envs.get(name).cloned())?; + } let (program, program_args) = args.command.split_first().context("no command given")?; let err = std::process::Command::new(program) .args(program_args) diff --git a/os/common/rootfs/app-compose.service b/os/common/rootfs/app-compose.service index e7d4b0bb2..682b07191 100644 --- a/os/common/rootfs/app-compose.service +++ b/os/common/rootfs/app-compose.service @@ -10,8 +10,8 @@ OnFailure=dstack-boot-error@%n.service Type=oneshot RemainAfterExit=true WorkingDirectory=/dstack -ExecStart=/bin/dstack-util exec-with-env --env-file /dstack/.host-shared/.decrypted-env.json -- /bin/app-compose.sh -ExecStop=/bin/dstack-util exec-with-env --env-file /dstack/.host-shared/.decrypted-env.json -- /bin/app-compose.sh stop +ExecStart=/bin/dstack-util exec-with-env --env-file /dstack/.host-shared/.decrypted-env.json --compose /dstack/app-compose.json -- /bin/app-compose.sh +ExecStop=/bin/dstack-util exec-with-env --env-file /dstack/.host-shared/.decrypted-env.json --compose /dstack/app-compose.json -- /bin/app-compose.sh stop StandardOutput=journal+console StandardError=journal+console From 15c241209061a4cd631c9900130920ec45782b71 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 07:44:10 -0800 Subject: [PATCH 06/25] docs: add environment value specs to the changelog Signed-off-by: Kevin Wang --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 22f843276..58b7a4050 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `vmm-cli compose --init-script` sets `init_script` in the app compose file. +- **`allowed_envs` entries can constrain values.** An entry may be `NAME:spec`, + such as `PORT:int(1..=65535)` or `NETWORK:/mainnet|testnet/`, and the guest + refuses to boot when a value does not match. `dstack-util validate-env` + applies the same specs from an `init_script`. See + [Environment value specs](docs/security/cvm-boundaries.md#environment-value-specs). ### Security From 73c5cf16c0873eae4359faa4506d2379d4bea3f1 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 07:49:48 -0800 Subject: [PATCH 07/25] feat(dstack-util): allow whitespace before the spec in allowed_envs Signed-off-by: Kevin Wang --- CHANGELOG.md | 4 ++-- docs/security/cvm-boundaries.md | 10 +++++----- dstack/dstack-util/src/main.rs | 2 +- dstack/dstack-util/src/parse_env_file.rs | 10 +++++----- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 58b7a4050..8ebfebc3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,8 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - `vmm-cli compose --init-script` sets `init_script` in the app compose file. -- **`allowed_envs` entries can constrain values.** An entry may be `NAME:spec`, - such as `PORT:int(1..=65535)` or `NETWORK:/mainnet|testnet/`, and the guest +- **`allowed_envs` entries can constrain values.** An entry may be `NAME: spec`, + such as `PORT: int(1..=65535)` or `NETWORK: /mainnet|testnet/`, and the guest refuses to boot when a value does not match. `dstack-util validate-env` applies the same specs from an `init_script`. See [Environment value specs](docs/security/cvm-boundaries.md#environment-value-specs). diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 5a62fa59b..306bf793d 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -37,7 +37,7 @@ This is the main configuration file for the application in JSON format: | public_logs | 0.3.3 | boolean | Whether logs are publicly visible | | public_sysinfo | 0.3.3 | boolean | Whether system info is public. Covers the guest dashboard and `/metrics`, including the `dstack_gpu_*` series (since 0.6.0), which expose each GPU's UUID and PCI bus address alongside utilization, memory, temperature and power. | | public_tcbinfo | 0.5.1 | boolean | Whether TCB info is public | -| allowed_envs | 0.4.2 | array of string | List of allowed environment variable names. An entry may be `NAME:spec` to also constrain the value, see [Environment value specs](#environment-value-specs). | +| allowed_envs | 0.4.2 | array of string | List of allowed environment variable names. An entry may be `NAME: spec` to also constrain the value, see [Environment value specs](#environment-value-specs). | | no_instance_id | 0.4.2 | boolean | Disable instance ID generation | | secure_time | 0.5.0 | boolean | Whether secure time is enabled | | pre_launch_script | 0.4.0 | string | Prelaunch bash script that runs before `docker compose up`. It runs *after* dockerd, so containers restored by a Docker restart policy can already be running when it executes. Do not build security gates on it — see [security-best-practices.md](./security-best-practices.md#security-semantics-must-not-depend-on-pre_launch_script-running-first). | @@ -133,7 +133,7 @@ This file is not measured to RTMRs, and the envelope is not bound to an instance #### Environment value specs -Since 0.6.7, an `allowed_envs` entry may be `NAME:spec`. The CVM refuses to boot when the value of `NAME` does not match the spec. A spec is one of: +Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional. The CVM refuses to boot when the value of `NAME` does not match the spec. A spec is one of: | Spec | Accepts | |------|---------| @@ -147,18 +147,18 @@ Since 0.6.7, an `allowed_envs` entry may be `NAME:spec`. The CVM refuses to boot A range is `start..=end` or `start.., - /// Variables that must be set, as `NAME:spec` or `NAME` + /// Variables that must be set, as `NAME: spec` or `NAME` #[arg(required_unless_present = "compose")] specs: Vec, } diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index 4fff3c0a5..7ec892abc 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -44,13 +44,13 @@ struct Data { /// The specs each allowed name's value must match. pub type AllowedEnvs = BTreeMap>; -/// Parses `allowed_envs` entries, each a name optionally followed by `:` and a -/// value spec. +/// Parses `allowed_envs` entries, each a name optionally followed by `:`, +/// optional whitespace and a value spec. pub fn parse_allowed_envs(entries: &[String]) -> Result { let mut allowed = AllowedEnvs::new(); for entry in entries { let (name, spec) = match entry.split_once(':') { - Some((name, spec)) => (name, Some(spec)), + Some((name, spec)) => (name, Some(spec.trim_start())), None => (entry.as_str(), None), }; let spec = spec @@ -208,14 +208,14 @@ mod tests { assert!(parse(&allowed, &[("N", "9")]).is_ok()); assert!(parse(&allowed, &[("N", "10")]).is_err()); } - let allowed = ["N:int(0..=9)", "N:int(5..)"]; + let allowed = ["N: int(0..=9)", "N: int(5..)"]; assert!(parse(&allowed, &[("N", "5")]).is_ok()); assert!(parse(&allowed, &[("N", "4")]).is_err()); } #[test] fn invalid_specs_are_rejected() { - for entry in ["A:", "A:int(", "A:string", "A:int:int"] { + for entry in ["A:", "A: ", "A:int(", "A:string", "A:int:int", "A: int "] { assert!(parse(&[entry], &[]).is_err(), "{entry}"); } } From 6868d781b070939a4c7ba45635ffa741b0d58986 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 08:05:24 -0800 Subject: [PATCH 08/25] feat(value-spec): bound spec length and pin the regex size limit Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 2 +- dstack/value-spec/src/lib.rs | 91 +++++++++++++++++++++++++++++++-- 2 files changed, 89 insertions(+), 4 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 306bf793d..d284ddce6 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -145,7 +145,7 @@ Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1.. | `/mainnet\|testnet/` | values the regex matches in full | | `int(1..=65535)?` | the empty string, or integers from 1 to 65535 | -A range is `start..=end` or `start.. = (Bound, Bound); @@ -117,6 +123,12 @@ impl FromStr for ValueSpec { type Err = ParseError; fn from_str(s: &str) -> Result { + if s.len() > MAX_SPEC_LEN { + return Err(ParseError { + offset: MAX_SPEC_LEN, + message: format!("spec is longer than {MAX_SPEC_LEN} bytes"), + }); + } let spec = alt(( regex.map(Kind::Regex), ranges("int", int) @@ -220,8 +232,13 @@ fn regex(input: &mut &str) -> ModalResult { fn anchored(pattern: &str) -> Result { // Reject patterns that are only valid once wrapped, such as `a)|(b`. - Regex::new(pattern)?; - Regex::new(&format!(r"\A(?:{pattern})\z")) + let build = |pattern: &str| { + RegexBuilder::new(pattern) + .size_limit(MAX_REGEX_SIZE) + .build() + }; + build(pattern)?; + build(&format!(r"\A(?:{pattern})\z")) } #[cfg(test)] @@ -517,6 +534,74 @@ mod tests { ); } + #[test] + fn specs_are_size_limited() { + let enumeration = |len: usize| format!("/{}/", "a".repeat(len - 2)); + check( + &enumeration(MAX_SPEC_LEN), + &[&"a".repeat(MAX_SPEC_LEN - 2)], + &["a"], + ); + let items = |n: usize| format!("int({})", vec!["1"; n].join("|")); + assert_eq!(items(2046).len(), MAX_SPEC_LEN); + check(&items(2046), &["1"], &["2"]); + check_invalid(&[ + &enumeration(MAX_SPEC_LEN + 1), + &items(2047), + &"?".repeat(1 << 20), + "/(?:a{1000}){1000}/", + "/\\pL{1000}/", + &format!("/{}/", "(".repeat(300) + &")".repeat(300)), + ]); + } + + #[test] + fn regex_cannot_escape_its_anchors() { + check_invalid(&[ + "/a)|(b/", + "/a)|(?:b/", + "/(?x)a # b/", + "/(?x)a|b #/", + "/a\\/", + "/[a/", + ]); + check("/(?x)a # b\n/", &["a"], &["ab", "a # b"]); + check("/(?x) a | b /", &["a", "b"], &["ab", " a "]); + check("/(?m)a/", &["a"], &["a\n", "\na", "b\na\nb"]); + check("/(?m)^a$/", &["a"], &["a\n", "\na", "b\na\nb"]); + check("/(?s)a.?/", &["a", "a\n"], &["a\n\n", "\na"]); + check("/a|b/", &["a", "b"], &["ab", "a\n", "xa", "bx"]); + check("/a*/", &["", "aaa"], &["\n", "a\n", "a\0", "\0"]); + } + + #[test] + fn hostile_values_are_rejected() { + let huge = "9".repeat(1 << 20); + let values = [ + "8080\n", + "\n8080", + " 8080", + "8080 ", + "8080\0", + "+8080", + "٨٠٨٠", + "8080", + "0x10", + "1e3", + "1_000", + "8080\r", + &huge, + ]; + check("int", &[], &values); + check("float", &[], &values); + check("int(1..=65535)?", &[""], &values); + check( + "/[0-9]+/", + &[&huge], + &["8080\n", "٨٠٨٠", "8080", " 8080"], + ); + } + #[test] fn regex_slashes_and_unicode() { check( From 83e28d4ba57a8df2dbe4862caf3772a6597881f6 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 08:24:28 -0800 Subject: [PATCH 09/25] feat(dstack-util): treat an unset env variable as empty when checking specs Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 4 +- dstack/dstack-util/src/main.rs | 26 +++--- dstack/dstack-util/src/parse_env_file.rs | 98 +++++++++++--------- dstack/dstack-util/src/system_setup.rs | 1 + formal/DstackFormal/Guest/EnvFile.lean | 113 ++++++++++++++--------- 5 files changed, 141 insertions(+), 101 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index d284ddce6..f3b163ff7 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -133,7 +133,7 @@ This file is not measured to RTMRs, and the envelope is not bound to an instance #### Environment value specs -Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional. The CVM refuses to boot when the value of `NAME` does not match the spec. A spec is one of: +Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional. The CVM refuses to boot when the value of `NAME` does not match the spec. A variable that is not set counts as empty, so `NAME` is required unless its spec accepts the empty string, as one ending in `?` does. A spec is one of: | Spec | Accepts | |------|---------| @@ -147,7 +147,7 @@ Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1.. A range is `start..=end` or `start.., /// JSON object mapping variable names to values, checked instead of the environment #[arg(long)] env_file: Option, - /// Variables that must be set, as `NAME: spec` or `NAME` + /// Specs to check, as `NAME: spec`; an unset variable counts as empty #[arg(required_unless_present = "compose")] specs: Vec, } @@ -151,15 +151,15 @@ fn load_allowed_envs(path: &Path) -> Result> { fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { let envs = args.env_file.as_deref().map(load_envs).transpose()?; - let allowed = args.compose.as_deref().map(load_allowed_envs).transpose()?; - parse_env_file::validate_env( - &args.specs, - &allowed.unwrap_or_default(), - |name| match &envs { - Some(envs) => envs.get(name).cloned(), - None => std::env::var(name).ok(), - }, - ) + let mut entries = args.specs; + if let Some(compose) = &args.compose { + entries.extend(load_allowed_envs(compose)?); + } + let allowed = parse_env_file::parse_allowed_envs(&entries)?; + parse_env_file::check_env(&allowed, |name| match &envs { + Some(envs) => envs.get(name).cloned(), + None => std::env::var(name).ok(), + }) } #[derive(Parser)] @@ -780,8 +780,8 @@ fn cmd_exec_with_env(args: ExecWithEnvArgs) -> Result<()> { let envs = load_envs(&args.env_file)?; if let Some(compose) = &args.compose { - let allowed = load_allowed_envs(compose)?; - parse_env_file::validate_env(&[], &allowed, |name| envs.get(name).cloned())?; + let allowed = parse_env_file::parse_allowed_envs(&load_allowed_envs(compose)?)?; + parse_env_file::check_env(&allowed, |name| envs.get(name).cloned())?; } let (program, program_args) = args.command.split_first().context("no command given")?; let err = std::process::Command::new(program) diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index 7ec892abc..c981044c5 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -62,28 +62,22 @@ pub fn parse_allowed_envs(entries: &[String]) -> Result { Ok(allowed) } -fn check_value(name: &str, value: &str, specs: &[ValueSpec]) -> Result<()> { - if !specs.iter().all(|spec| spec.matches(value)) { - bail!("value of env {name} does not match its spec"); - } - Ok(()) -} - -/// Checks variables against `allowed_envs`-style entries. Those named by -/// `required` must be set; those named by `optional` are checked when set. -pub fn validate_env( - required: &[String], - optional: &[String], - get: impl Fn(&str) -> Option, -) -> Result<()> { - for (name, specs) in parse_allowed_envs(optional)? { - if let Some(value) = get(&name) { - check_value(&name, &value, &specs)?; +/// Checks the variables `allowed` names against their specs. An unset +/// variable counts as empty, so only a spec that accepts the empty string +/// leaves its variable optional. +pub fn check_env(allowed: &AllowedEnvs, get: impl Fn(&str) -> Option) -> Result<()> { + for (name, specs) in allowed { + let value = get(name); + if specs + .iter() + .all(|spec| spec.matches(value.as_deref().unwrap_or_default())) + { + continue; + } + match value { + Some(_) => bail!("value of env {name} does not match its spec"), + None => bail!("env {name} is not set and its spec does not accept an empty value"), } - } - for (name, specs) in parse_allowed_envs(required)? { - let value = get(&name).with_context(|| format!("env {name} is not set"))?; - check_value(&name, &value, &specs)?; } Ok(()) } @@ -106,10 +100,10 @@ pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result 255 { bail!("Environment variable name too long: {}", key); @@ -125,14 +119,13 @@ pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result MAX_TOTAL_SIZE { bail!("Environment variables total size too large"); } env.insert(key, value); } + check_env(allowed, |name| env.get(name).cloned())?; Ok(env) } @@ -190,18 +183,44 @@ mod tests { ("ANY", "x y"), ]; assert_eq!(parse(&allowed, &env).unwrap().len(), 4); - assert!(parse(&allowed, &[("OTHER", "1")]).unwrap().is_empty()); for bad in [ ("PORT", "0"), ("PORT", "80 "), ("NET", "mainnet"), ("URL", "http://a"), ] { - let err = parse(&allowed, &[bad]).unwrap_err().to_string(); - assert!(!err.contains(bad.1), "{err}"); + let env = env.map(|kv| if kv.0 == bad.0 { bad } else { kv }); + let err = parse(&allowed, &env).unwrap_err().to_string(); + assert!(err.contains(bad.0) && !err.contains(bad.1), "{err}"); } } + #[test] + fn unset_variables_count_as_empty() { + let allowed = ["PORT: int(1..=65535)?", "NET: /(main|test)?/", "ANY"]; + assert!(parse(&allowed, &[("OTHER", "1")]).unwrap().is_empty()); + assert!(parse(&allowed, &[("PORT", ""), ("ANY", "")]).is_ok()); + + for (allowed, name) in [ + ("PORT: int(1..=65535)", "PORT"), + ("NET: /main|test/", "NET"), + ] { + let err = parse(&[allowed], &[]).unwrap_err().to_string(); + assert!(err.contains(&format!("env {name} is not set")), "{err}"); + assert!(parse(&[allowed], &[(name, "")]).is_err()); + } + } + + #[test] + fn the_last_duplicate_is_the_one_checked() { + let allowed = ["N: int(0..=9)"]; + assert_eq!( + parse(&allowed, &[("N", "x"), ("N", "5")]).unwrap()["N"], + "5" + ); + assert!(parse(&allowed, &[("N", "5"), ("N", "x")]).is_err()); + } + #[test] fn repeated_names_must_match_every_spec() { for allowed in [["N:int(0..=9)", "N"], ["N", "N:int(0..=9)"]] { @@ -221,22 +240,17 @@ mod tests { } #[test] - fn validate_env_requires_only_required_variables() { + fn check_env_looks_up_every_allowed_name() { let get = |name: &str| (name == "PORT").then(|| "8080".to_string()); - let check = |required: &[&str], optional: &[&str]| { - let [required, optional] = - [required, optional].map(|v| v.iter().map(|s| s.to_string()).collect::>()); - validate_env(&required, &optional, get) + let check = |entries: &[&str]| { + let entries = entries.iter().map(|s| s.to_string()).collect::>(); + check_env(&parse_allowed_envs(&entries)?, get) }; - assert!(check(&["PORT:int(1..=65535)", "PORT"], &[]).is_ok()); - assert!(check(&["PORT:int(1..=1024)"], &[]).is_err()); - assert!(check(&["PORT:int", "HOST"], &[]).is_err()); - assert!(check(&["PORT:string"], &[]).is_err()); - - assert!(check(&[], &["PORT:int(1..=65535)", "HOST:/a/"]).is_ok()); - assert!(check(&[], &["PORT:int(1..=1024)"]).is_err()); - assert!(check(&[], &["HOST:string"]).is_err()); - assert!(check(&["PORT:int(8080)"], &["PORT:int(1..=1024)"]).is_err()); + assert!(check(&["PORT: int(1..=65535)", "PORT", "HOST", "N: int?"]).is_ok()); + assert!(check(&["PORT: int(1..=1024)"]).is_err()); + assert!(check(&["PORT: int", "HOST: /.+/"]).is_err()); + assert!(check(&["PORT: int(8080)", "PORT: int(1..=1024)"]).is_err()); + assert!(check(&["PORT: string"]).is_err()); } /// Round-trip through systemd's own parser; skipped without a user manager. diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index 74edaa8e5..be4fb9807 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -3440,6 +3440,7 @@ impl Stage1<'_> { let (decrypted_env, sealed) = if self.shared.sealed_env.is_none() && self.shared.encrypted_env.is_empty() { info!("No encrypted env, using default"); + crate::parse_env_file::check_env(&allowed_envs, |_| None)?; (Default::default(), Vec::new()) } else { info!("Processing encrypted env"); diff --git a/formal/DstackFormal/Guest/EnvFile.lean b/formal/DstackFormal/Guest/EnvFile.lean index 88d14566e..d876805ee 100644 --- a/formal/DstackFormal/Guest/EnvFile.lean +++ b/formal/DstackFormal/Guest/EnvFile.lean @@ -20,9 +20,9 @@ Proven: encoding is lossy (`newline_collision`), as the Rust doc comment states. * `validKey_safe`: keys passing `KEY_REGEX` are nonempty and contain no `=`, whitespace, `#` or quote, so `KEY=value` lines split at the first `=`. -* `parseEnv_spec`: every accepted entry is allowed, has a valid key, matches - its value specs and respects the length limits; unauthorized keys are - dropped, not rejected. +* `parseEnv_spec`: every accepted entry is allowed, has a valid key and + respects the length limits; unauthorized keys are dropped, not rejected; + and every allowed name's value, empty when unset, matches its value specs. Assumptions: Rust's `char::is_whitespace` is a parameter `rustWs` required to hold for systemd's `WHITESPACE` (` `, `\t`, `\n`, `\r`). Whether a value matches @@ -31,8 +31,8 @@ the specs themselves. Modeling gaps: the systemd parser model is limited to one value line, is written from the upstream state machine rather than extracted from it, and the Rust `systemd_round_trip` test is its only executable cross-check; JSON -decoding, `parse_allowed_envs`, `MAX_ITEMS`, and the `BTreeMap` (later duplicates override) are not -modeled; lengths are counted in chars, not UTF-8 bytes. +decoding, `parse_allowed_envs`, `MAX_ITEMS`, and the `BTreeMap` are not +modeled beyond `valueOf` taking the last duplicate; lengths are counted in chars, not UTF-8 bytes. -/ namespace DstackFormal.Guest.EnvFile @@ -265,27 +265,33 @@ theorem validKey_safe (k : List Char) (h : validKey k = true) : #guard !validKey [] /-- The loop of `parse_env` over decoded pairs; `none` is an error. -/ -def parseEnvGo (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) : +def parseEnvGo (allowed : List Char → Bool) : Nat → List (List Char × List Char) → Option (List (List Char × List Char)) | _, [] => some [] | total, (k, v) :: rest => - if !allowed k then parseEnvGo allowed matchesSpecs total rest + if !allowed k then parseEnvGo allowed total rest else if k.length > 255 then none else if v.length > 128 * 1024 then none else if !validKey k then none - else if !matchesSpecs k v then none else if total + k.length + v.length > 1024 * 1024 then none - else ((k, v) :: ·) <$> parseEnvGo allowed matchesSpecs (total + k.length + v.length) rest - -def parseEnv (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) - (pairs : List (List Char × List Char)) : Option (List (List Char × List Char)) := - parseEnvGo allowed matchesSpecs 0 pairs - -theorem parseEnvGo_spec (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) : - ∀ (total : Nat) (pairs out : List (List Char × List Char)), - parseEnvGo allowed matchesSpecs total pairs = some out → + else ((k, v) :: ·) <$> parseEnvGo allowed (total + k.length + v.length) rest + +/-- The value `check_env` sees for `name`: the last accepted pair, empty when +unset. -/ +def valueOf (name : List Char) (env : List (List Char × List Char)) : List Char := + (env.reverse.lookup name).getD [] + +/-- `parse_env`: the loop, then `check_env` over the allowed `names`. -/ +def parseEnv (allowed : List Char → Bool) (names : List (List Char)) + (matchesSpecs : List Char → List Char → Bool) (pairs : List (List Char × List Char)) : + Option (List (List Char × List Char)) := + (parseEnvGo allowed 0 pairs).bind fun env => + if names.all (fun name => matchesSpecs name (valueOf name env)) then some env else none + +theorem parseEnvGo_spec (allowed : List Char → Bool) : + ∀ (total : Nat) (pairs out : List (List Char × List Char)), parseEnvGo allowed total pairs = some out → out.Sublist pairs ∧ ∀ kv ∈ out, allowed kv.1 = true ∧ validKey kv.1 = true ∧ - matchesSpecs kv.1 kv.2 = true ∧ kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024 + kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024 | _, [], out, h => by simp [parseEnvGo] at h; subst h; simp | total, (k, v) :: rest, out, h => by unfold parseEnvGo at h @@ -296,42 +302,61 @@ theorem parseEnvGo_spec (allowed : List Char → Bool) (matchesSpecs : List Char by_cases h2 : v.length > 128 * 1024 · simp [h1, h2] at h by_cases h3 : validKey k = true - · by_cases h5 : matchesSpecs k v = true - · by_cases h4 : total + k.length + v.length > 1024 * 1024 - · simp [h1, h2, h3, h4, h5] at h - simp only [h1, h2, h3, h4, h5, ite_false, Bool.not_true, Bool.false_eq_true] at h - cases hr : parseEnvGo allowed matchesSpecs (total + k.length + v.length) rest with - | none => simp [hr] at h - | some out' => - simp only [hr, Option.some.injEq, Functor.map, Option.map] at h - subst h - obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed matchesSpecs _ rest out' hr - refine ⟨hs.cons_cons _, ?_⟩ - intro kv hkv - rcases List.mem_cons.mp hkv with rfl | hkv - · exact ⟨ha, h3, h5, by dsimp only; omega, by dsimp only; omega⟩ - · exact hp kv hkv - · simp [h1, h2, h3, h5] at h + · by_cases h4 : total + k.length + v.length > 1024 * 1024 + · simp [h1, h2, h3, h4] at h + simp only [h1, h2, h3, h4, ite_false, Bool.not_true, Bool.false_eq_true] at h + cases hr : parseEnvGo allowed (total + k.length + v.length) rest with + | none => simp [hr] at h + | some out' => + simp only [hr, Option.some.injEq, Functor.map, Option.map] at h + subst h + obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed _ rest out' hr + refine ⟨hs.cons_cons _, ?_⟩ + intro kv hkv + rcases List.mem_cons.mp hkv with rfl | hkv + · exact ⟨ha, h3, by dsimp only; omega, by dsimp only; omega⟩ + · exact hp kv hkv · simp [h1, h2, h3] at h · simp only [Bool.not_eq_true] at ha simp only [ha, Bool.not_false, ite_true] at h - obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed matchesSpecs total rest out h + obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed total rest out h exact ⟨hs.cons _, hp⟩ -/-- Every accepted entry is allowed, has a valid key, matches its specs and -respects the limits. -/ -theorem parseEnv_spec (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) - (pairs out : List (List Char × List Char)) (h : parseEnv allowed matchesSpecs pairs = some out) : - out.Sublist pairs ∧ ∀ kv ∈ out, allowed kv.1 = true ∧ validKey kv.1 = true ∧ - matchesSpecs kv.1 kv.2 = true ∧ kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024 := - parseEnvGo_spec allowed matchesSpecs 0 pairs out h +/-- Every accepted entry is allowed, has a valid key and respects the limits, +and every allowed name's value matches its specs. -/ +theorem parseEnv_spec (allowed : List Char → Bool) (names : List (List Char)) + (matchesSpecs : List Char → List Char → Bool) (pairs out : List (List Char × List Char)) + (h : parseEnv allowed names matchesSpecs pairs = some out) : + out.Sublist pairs ∧ + (∀ kv ∈ out, allowed kv.1 = true ∧ validKey kv.1 = true ∧ + kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024) ∧ + ∀ name ∈ names, matchesSpecs name (valueOf name out) = true := by + unfold parseEnv at h + cases hg : parseEnvGo allowed 0 pairs with + | none => simp [hg] at h + | some env => + simp only [hg, Option.bind_some] at h + by_cases hc : names.all (fun name => matchesSpecs name (valueOf name env)) = true + · simp only [hc, ite_true, Option.some.injEq] at h + subst h + obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed 0 pairs env hg + exact ⟨hs, hp, fun name hn => List.all_eq_true.mp hc name hn⟩ + · simp [hc] at h /-- Unauthorized keys are skipped, not rejected. -/ -example : parseEnv (fun k => k == "A".toList) (fun _ _ => true) +example : parseEnv (fun k => k == "A".toList) [] (fun _ _ => true) [("B".toList, []), ("A".toList, "1".toList)] = some [("A".toList, "1".toList)] := by decide /-- A value failing its specs is an error, not a skip. -/ -example : parseEnv (fun _ => true) (fun _ v => v == "1".toList) +example : parseEnv (fun _ => true) ["B".toList] (fun _ v => v == "1".toList) [("A".toList, "1".toList), ("B".toList, "2".toList)] = none := by decide +/-- An unset variable is checked as the empty value. -/ +example : parseEnv (fun _ => true) ["B".toList] (fun _ v => !v.isEmpty) + [("A".toList, "1".toList)] = none := by decide + +/-- The last duplicate is the one checked. -/ +example : (parseEnv (fun _ => true) ["A".toList] (fun _ v => v == "2".toList) + [("A".toList, "1".toList), ("A".toList, "2".toList)]).isSome = true := by decide + end DstackFormal.Guest.EnvFile From 3b1831cc360bf86c155e89df3a1836e0a90361c4 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 18:04:21 -0800 Subject: [PATCH 10/25] feat(dstack-util): reject env variables outside allowed_envs Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 10 ++++----- dstack/dstack-util/src/main.rs | 26 +++++++++++++++++------- dstack/dstack-util/src/parse_env_file.rs | 23 +++++++++++++++++++++ 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index f3b163ff7..31615320c 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -127,7 +127,7 @@ dstack uses encrypted environment variables to allow app developers to securely - CVM decrypts the ciphertext using AESGCM with the derived shared secret - CVM parses the JSON and only stores variables listed in allowed_envs from app-compose.json - CVM validates variable names and checks each value against the specs given in allowed_envs - - Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env`, which checks the values against the specs again + - Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env`, which rejects variables outside allowed_envs and checks the values against the specs again This file is not measured to RTMRs, and the envelope is not bound to an instance or compose hash: the KMS derives `env_crypt_key` from the app ID alone, so the host can withhold the file or replay any earlier ciphertext for the same app. It is highly recommended to add application-specific integrity checks, such as a version or expiry inside the plaintext, at the application layer. See [security-best-practices.md](./security-best-practices.md) for more details. @@ -147,16 +147,16 @@ Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1.. A range is `start..=end` or `start.., - /// Specs to check, as `NAME: spec`; an unset variable counts as empty + /// Accept variables that no spec or `allowed_envs` entry names + #[arg(long)] + allow_unlisted: bool, + /// Variables to allow, as `NAME` or `NAME: spec`; an unset variable counts as empty #[arg(required_unless_present = "compose")] specs: Vec, } @@ -128,7 +131,7 @@ struct ExecWithEnvArgs { /// JSON object mapping variable names to values #[arg(long)] env_file: PathBuf, - /// App compose file whose `allowed_envs` specs the values must match + /// App compose file; variables must be in its `allowed_envs` and match the specs there #[arg(long)] compose: Option, /// Command to exec, with its arguments @@ -150,16 +153,24 @@ fn load_allowed_envs(path: &Path) -> Result> { } fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { - let envs = args.env_file.as_deref().map(load_envs).transpose()?; + let envs = match &args.env_file { + Some(path) => load_envs(path)?, + None => std::env::vars_os() + .map(|(name, value)| { + let name = name.to_string_lossy().into_owned(); + (name, value.to_string_lossy().into_owned()) + }) + .collect(), + }; let mut entries = args.specs; if let Some(compose) = &args.compose { entries.extend(load_allowed_envs(compose)?); } let allowed = parse_env_file::parse_allowed_envs(&entries)?; - parse_env_file::check_env(&allowed, |name| match &envs { - Some(envs) => envs.get(name).cloned(), - None => std::env::var(name).ok(), - }) + if !args.allow_unlisted { + parse_env_file::check_names(&allowed, envs.keys())?; + } + parse_env_file::check_env(&allowed, |name| envs.get(name).cloned()) } #[derive(Parser)] @@ -781,6 +792,7 @@ fn cmd_exec_with_env(args: ExecWithEnvArgs) -> Result<()> { let envs = load_envs(&args.env_file)?; if let Some(compose) = &args.compose { let allowed = parse_env_file::parse_allowed_envs(&load_allowed_envs(compose)?)?; + parse_env_file::check_names(&allowed, envs.keys())?; parse_env_file::check_env(&allowed, |name| envs.get(name).cloned())?; } let (program, program_args) = args.command.split_first().context("no command given")?; diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index c981044c5..b0762326e 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -82,6 +82,17 @@ pub fn check_env(allowed: &AllowedEnvs, get: impl Fn(&str) -> Option) -> Ok(()) } +/// Rejects variables that `allowed` does not name. +pub fn check_names<'a>( + allowed: &AllowedEnvs, + names: impl IntoIterator, +) -> Result<()> { + match names.into_iter().find(|name| !allowed.contains_key(*name)) { + Some(name) => bail!("env {name} is not allowed"), + None => Ok(()), + } +} + pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result> { const MAX_ITEMS: usize = 1024; const MAX_TOTAL_SIZE: usize = 1024 * 1024; @@ -253,6 +264,18 @@ mod tests { assert!(check(&["PORT: string"]).is_err()); } + #[test] + fn unlisted_names_are_rejected() { + let allowed = parse_allowed_envs(&["PORT: int".to_string(), "HOST".to_string()]).unwrap(); + let check = |names: &[&str]| { + let names = names.iter().map(|s| s.to_string()).collect::>(); + check_names(&allowed, &names) + }; + assert!(check(&[]).is_ok()); + assert!(check(&["HOST", "PORT"]).is_ok()); + assert!(check(&["HOST", "LD_PRELOAD"]).is_err()); + } + /// Round-trip through systemd's own parser; skipped without a user manager. #[test] fn systemd_round_trip() { From 0e246f14f68169f1ee6162447f7132dbb5b6d5ab Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 08:11:13 -0800 Subject: [PATCH 11/25] refactor(value-spec): parse NAME: spec entries in the crate Signed-off-by: Kevin Wang --- dstack/dstack-util/src/parse_env_file.rs | 10 ++------- dstack/value-spec/src/lib.rs | 28 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index b0762326e..fc7e4e21c 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -49,14 +49,8 @@ pub type AllowedEnvs = BTreeMap>; pub fn parse_allowed_envs(entries: &[String]) -> Result { let mut allowed = AllowedEnvs::new(); for entry in entries { - let (name, spec) = match entry.split_once(':') { - Some((name, spec)) => (name, Some(spec.trim_start())), - None => (entry.as_str(), None), - }; - let spec = spec - .map(str::parse) - .transpose() - .with_context(|| format!("invalid value spec for env {name}"))?; + let (name, spec) = value_spec::parse_named(entry) + .with_context(|| format!("invalid allowed_envs entry {entry:?}"))?; allowed.entry(name.to_string()).or_default().extend(spec); } Ok(allowed) diff --git a/dstack/value-spec/src/lib.rs b/dstack/value-spec/src/lib.rs index ca62b3c09..2d6850db9 100644 --- a/dstack/value-spec/src/lib.rs +++ b/dstack/value-spec/src/lib.rs @@ -97,6 +97,22 @@ enum Kind { Regex(Regex), } +/// Splits a `NAME: spec` entry into the name and the text of its spec. The +/// whitespace after the colon is optional, and an entry without a colon is a +/// bare name. +pub fn split_named(entry: &str) -> (&str, Option<&str>) { + match entry.split_once(':') { + Some((name, spec)) => (name, Some(spec.trim_start())), + None => (entry, None), + } +} + +/// Parses a `NAME: spec` entry into the name and its spec. +pub fn parse_named(entry: &str) -> Result<(&str, Option), ParseError> { + let (name, spec) = split_named(entry); + Ok((name, spec.map(str::parse).transpose()?)) +} + const MAX_NUMBER_LEN: usize = 64; const MAX_SPEC_LEN: usize = 4096; const MAX_REGEX_SIZE: usize = 10 << 20; @@ -534,6 +550,18 @@ mod tests { ); } + #[test] + fn named_entries() { + let name = |entry| parse_named(entry).map(|(name, spec)| (name, spec.is_some())); + assert_eq!(name("PORT").unwrap(), ("PORT", false)); + assert_eq!(name("PORT:int").unwrap(), ("PORT", true)); + assert_eq!(name("PORT: int(1..=65535)?").unwrap(), ("PORT", true)); + assert_eq!(name("URL: /https://.*/").unwrap(), ("URL", true)); + for entry in ["A:", "A: ", "A: int ", "A:int:int", "A: string"] { + assert!(name(entry).is_err(), "{entry:?} should fail"); + } + } + #[test] fn specs_are_size_limited() { let enumeration = |len: usize| format!("/{}/", "a".repeat(len - 2)); From 2edb069d39a8b879ca7e3f6c71baa02d0c924b10 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 08:11:13 -0800 Subject: [PATCH 12/25] feat(vmm): reject malformed allowed_envs specs at deployment Signed-off-by: Kevin Wang --- dstack/Cargo.lock | 1 + dstack/vmm/Cargo.toml | 1 + dstack/vmm/src/main_service.rs | 42 ++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index e3fb8a84a..ba2db1d16 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -2616,6 +2616,7 @@ dependencies = [ "tracing-subscriber", "url", "uuid", + "value-spec", "vfio-ioctls", "wait-timeout", "which 7.0.3", diff --git a/dstack/vmm/Cargo.toml b/dstack/vmm/Cargo.toml index dd4f91d54..a49e01c91 100644 --- a/dstack/vmm/Cargo.toml +++ b/dstack/vmm/Cargo.toml @@ -58,6 +58,7 @@ lspci.workspace = true base64.workspace = true serde-human-bytes.workspace = true size-parser = { workspace = true, features = ["serde"] } +value-spec.workspace = true fatfs.workspace = true fscommon.workspace = true or-panic.workspace = true diff --git a/dstack/vmm/src/main_service.rs b/dstack/vmm/src/main_service.rs index a35dfc614..027b3a102 100644 --- a/dstack/vmm/src/main_service.rs +++ b/dstack/vmm/src/main_service.rs @@ -369,6 +369,7 @@ pub fn create_manifest_from_vm_config( let swtpm = needs_swtpm(key_provider, simulated_tee); let disk_prealloc = disk_prealloc_from_vm_config(&request, cvm_config)?; validate_disk_prealloc_against_compose(disk_prealloc, &request.compose_file)?; + validate_allowed_envs(&request.compose_file)?; Ok(Manifest { id, @@ -459,6 +460,23 @@ fn validate_disk_prealloc_against_compose( ) } +/// Catch mistyped `allowed_envs` value specs before the guest fails on them at +/// boot. Regex specs are left to the guest: compiling one is too costly to do +/// for as many entries as a compose file can hold. +fn validate_allowed_envs(compose_file: &str) -> Result<()> { + let compose: serde_json::Value = + serde_json::from_str(compose_file).context("invalid app compose JSON")?; + let entries = compose.get("allowed_envs").and_then(|v| v.as_array()); + for entry in entries.into_iter().flatten().filter_map(|v| v.as_str()) { + let (_, spec) = value_spec::split_named(entry); + if let Some(spec) = spec.filter(|spec| !spec.starts_with('/')) { + spec.parse::() + .with_context(|| format!("invalid allowed_envs entry {entry:?}"))?; + } + } + Ok(()) +} + /// Read `storage_discard` out of app-compose. Everything else in the document /// stays opaque, and a missing field means the app-compose default, which is /// discard enabled. @@ -1162,6 +1180,7 @@ impl VmmRpc for RpcHandler { bail!("The instance {} not found", request.id); } validate_disk_prealloc_against_compose(manifest.disk_prealloc, &request.compose_file)?; + validate_allowed_envs(&request.compose_file)?; app_id_of(&request.compose_file) } else { Default::default() @@ -1454,6 +1473,7 @@ impl VmmRpc for RpcHandler { // check the compose file is valid let _app_compose: AppCompose = serde_json::from_str(&request.compose_file).context("Invalid compose file")?; + validate_allowed_envs(&request.compose_file)?; let hash = hex_sha256(&request.compose_file); Ok(RpcComposeHash { hash }) } @@ -1752,6 +1772,28 @@ mod tests { assert_eq!(manifest.disk_prealloc, DiskPrealloc::Metadata); } + #[test] + fn allowed_envs_specs_are_checked_at_deployment() { + let create = |allowed_envs: &[&str]| { + let mut request = test_vm_configuration(); + request.compose_file = serde_json::json!({ "allowed_envs": allowed_envs }).to_string(); + create_manifest_from_vm_config(request, &test_cvm_config()) + }; + create(&["TOKEN", "PORT: int(1..=65535)", "RATIO:float(0<..=1)?"]).unwrap(); + // Regex specs are not compiled here, valid or not. + create(&["NET: /main|test/?", "BAD: /(/", r"SLOW: /\w{200}/"]).unwrap(); + for bad in [ + "PORT: int(1..=", + "PORT: integer", + "PORT:", + "PORT: int(5..=1)", + ] { + let err = format!("{:#}", create(&["TOKEN", bad]).unwrap_err()); + assert!(err.contains("invalid allowed_envs entry"), "{err}"); + assert!(err.contains("PORT"), "{err}"); + } + } + #[test] fn a_malformed_compose_is_reported_as_such() { // Not reachable today (the callers parse the compose first), but the From 7ef065b3f1c56720e8823461fa6adeaefb87b58b Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 08:11:13 -0800 Subject: [PATCH 13/25] feat(vmm-cli): add --env-spec and keep specs when rewriting allowed_envs Signed-off-by: Kevin Wang --- docs/vmm-cli-user-guide.md | 1 + dstack/vmm/src/tests/test_vmm_cli.py | 21 +++++++++++++++++++++ dstack/vmm/src/vmm-cli.py | 23 +++++++++++++++++++++-- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/docs/vmm-cli-user-guide.md b/docs/vmm-cli-user-guide.md index 43a895690..03c25bf6f 100644 --- a/docs/vmm-cli-user-guide.md +++ b/docs/vmm-cli-user-guide.md @@ -238,6 +238,7 @@ First, create an application composition file that describes your application: - `--public-logs`: Make logs publicly accessible - `--public-sysinfo`: Make system info publicly accessible - `--env-file`: File with environment variables to encrypt +- `--env-spec`: Allow an environment variable and constrain its value, e.g. `--env-spec 'PORT: int(1..=65535)'`; repeat for more variables. See [environment value specs](./security/cvm-boundaries.md#environment-value-specs). `deploy`, `update` and `update-env` keep these entries when they rewrite `allowed_envs` from an env file - `--no-instance-id`: Disable unique instance identification - `--no-storage-discard`: Keep deleted data-disk blocks instead of returning them to the host. Required by `deploy --disk-prealloc falloc|full`, and it also keeps filesystem allocation and deletion patterns from the host. The cost is that the image only ever grows: space freed inside the guest is never given back diff --git a/dstack/vmm/src/tests/test_vmm_cli.py b/dstack/vmm/src/tests/test_vmm_cli.py index 5715eae5a..f0b54d27f 100644 --- a/dstack/vmm/src/tests/test_vmm_cli.py +++ b/dstack/vmm/src/tests/test_vmm_cli.py @@ -215,6 +215,27 @@ def test_launch_token_hash_is_written_last(self) -> None: ) +class AllowedEnvsTests(unittest.TestCase): + """Verify value specs survive rewriting allowed_envs from an env file.""" + + def test_plain_names_follow_the_env_file(self) -> None: + """Rebuild entries without a spec from the env file.""" + merge = VMM_CLI.merge_allowed_envs + self.assertEqual(merge([], {"A": "1", "B": "2"}), ["A", "B"]) + self.assertEqual(merge(["A", "C"], ["B", "A"]), ["B", "A"]) + + def test_specs_are_kept(self) -> None: + """Keep entries with a spec, and stay stable when merged again.""" + merge = VMM_CLI.merge_allowed_envs + existing = ["PORT: int(1..=65535)", "OLD", "NET:/main|test/", "NET: /.{1,8}/"] + self.assertEqual( + merge(existing, ["TOKEN", "PORT"]), + ["PORT: int(1..=65535)", "NET:/main|test/", "NET: /.{1,8}/", "TOKEN"], + ) + merged = merge(existing, ["NET", "PORT", "TOKEN"]) + self.assertEqual(merge(merged, ["TOKEN", "NET", "PORT"]), merged) + + class LaunchTicketTests(unittest.TestCase): """Pin the hash the contracts allow; the KMS computes the same.""" diff --git a/dstack/vmm/src/vmm-cli.py b/dstack/vmm/src/vmm-cli.py index e1668c6b6..1a8a3ba1f 100755 --- a/dstack/vmm/src/vmm-cli.py +++ b/dstack/vmm/src/vmm-cli.py @@ -19,7 +19,7 @@ import tempfile import time import urllib.parse -from typing import Any, BinaryIO, Dict, List, Optional, Tuple, Union +from typing import Any, BinaryIO, Dict, Iterable, List, Optional, Tuple, Union # Optional cryptography imports - only needed for encrypted environment variables try: @@ -1077,7 +1077,7 @@ def create_app_compose(self, args) -> None: "key_provider_id": args.key_provider_id or "", "public_logs": args.public_logs, "public_sysinfo": args.public_sysinfo, - "allowed_envs": [k for k in envs.keys()], + "allowed_envs": merge_allowed_envs(args.env_spec, envs), "no_instance_id": args.no_instance_id, "secure_time": args.secure_time, } @@ -1624,6 +1624,17 @@ def format_table(rows, headers): return "\n".join(table) +def merge_allowed_envs(existing: List[str], names: Iterable[str]) -> List[str]: + """Return allowed_envs for the variables `names`. + + Entries of `existing` that carry a value spec (`NAME: spec`) are part of + the app's identity and are always kept; plain names follow `names`. + """ + specs = [entry for entry in existing if ":" in entry] + covered = {entry.split(":", 1)[0] for entry in specs} + return specs + [name for name in names if name not in covered] + + def parse_env_file(file_path: str) -> Dict[str, str]: """Parse an environment file into a dictionary of key-value pairs. @@ -2062,6 +2073,14 @@ def _patched_format_help(): compose_parser.add_argument( "--env-file", help="File with environment variables to encrypt", default=None ) + compose_parser.add_argument( + "--env-spec", + action="append", + default=[], + metavar="NAME: SPEC", + help="Allow an environment variable and constrain its value, " + "e.g. 'PORT: int(1..=65535)' (can be used multiple times)", + ) compose_parser.add_argument( "--no-instance-id", action="store_true", help="Disable instance ID" ) From 0ddb6fe4cda36db703392aa6d9da1d42a505f226 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 08:11:13 -0800 Subject: [PATCH 14/25] feat(vmm-ui): edit value specs and keep them on update Signed-off-by: Kevin Wang --- .../ui/src/components/EncryptedEnvEditor.ts | 34 ++++++------------- dstack/vmm/ui/src/composables/useVmManager.ts | 9 ++--- dstack/vmm/ui/src/lib/envEncryption.ts | 17 +++++++++- dstack/vmm/ui/src/styles/main.css | 2 +- dstack/vmm/ui/tests/envEncryption.test.cjs | 27 ++++++++++++++- 5 files changed, 59 insertions(+), 30 deletions(-) diff --git a/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts b/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts index 1a081bfdb..772492fdb 100644 --- a/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts +++ b/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts @@ -3,7 +3,7 @@ declare const FileReader: any; -type EnvVar = { key: string; value: string }; +type EnvVar = { key: string; value: string; spec?: string }; type ComponentInstance = { envVars: EnvVar[]; @@ -13,6 +13,7 @@ type ComponentInstance = { textContent: string; }; parseTextContent(): void; + replaceFromText(content: string): void; }; const EncryptedEnvEditorComponent = { @@ -58,6 +59,7 @@ const EncryptedEnvEditorComponent = {
+ @@ -105,9 +107,13 @@ const EncryptedEnvEditorComponent = { if (!content.trim()) { return; } - const lines = content.split('\n'); + this.replaceFromText(content); + }, + /** Replace the variables with `KEY=VALUE` lines, keeping the specs of the names that remain. */ + replaceFromText(this: ComponentInstance, content: string) { + const specs = new Map(this.envVars.map((env) => [env.key, env.spec])); this.envVars.splice(0, this.envVars.length); - for (const line of lines) { + for (const line of content.split('\n')) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('#')) { continue; @@ -121,7 +127,7 @@ const EncryptedEnvEditorComponent = { if (!key) { continue; } - this.envVars.push({ key, value }); + this.envVars.push({ key, value, spec: specs.get(key) }); } }, loadEnvFromFile(this: ComponentInstance, event: Event) { @@ -132,25 +138,7 @@ const EncryptedEnvEditorComponent = { } const reader = new FileReader(); reader.onload = (e: { target: { result: string } }) => { - const content = e.target.result || ''; - const lines = content.split('\n'); - this.envVars.splice(0, this.envVars.length); - for (const line of lines) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) { - continue; - } - const equalIndex = trimmed.indexOf('='); - if (equalIndex === -1) { - continue; - } - const key = trimmed.substring(0, equalIndex).trim(); - const value = trimmed.substring(equalIndex + 1).trim(); - if (!key) { - continue; - } - this.envVars.push({ key, value }); - } + this.replaceFromText(e.target.result || ''); }; reader.readAsText(file); if (input) { diff --git a/dstack/vmm/ui/src/composables/useVmManager.ts b/dstack/vmm/ui/src/composables/useVmManager.ts index 89d598b54..1608fcb80 100644 --- a/dstack/vmm/ui/src/composables/useVmManager.ts +++ b/dstack/vmm/ui/src/composables/useVmManager.ts @@ -4,7 +4,7 @@ declare const Vue: any; const { ref, computed, watch, onMounted } = Vue; import type { vmm as VmmTypes } from '../proto/vmm_rpc'; -import { encryptEnvPayload } from '../lib/envEncryption'; +import { encryptEnvPayload, mergeAllowedEnvs } from '../lib/envEncryption'; // Types based on Rust definitions type VmConfiguration = VmmTypes.IVmConfiguration; @@ -125,6 +125,7 @@ type VmListItem = { type EncryptedEnvEntry = { key: string; value: string; + spec?: string; }; type PortFormEntry = { @@ -1013,7 +1014,7 @@ type CreateVmPayloadSource = { key_provider_id: vmForm.value.key_provider === 'kms' || vmForm.value.key_provider === 'local' ? vmForm.value.key_provider_id : '', - allowed_envs: vmForm.value.encryptedEnvs.map((env) => env.key), + allowed_envs: mergeAllowedEnvs([], vmForm.value.encryptedEnvs), no_instance_id: !vmForm.value.gateway_enabled, secure_time: false, storage_discard: vmForm.value.storage_discard, @@ -1080,8 +1081,8 @@ type CreateVmPayloadSource = { appCompose.manifest_version = targetManifestVersion; } if (updateDialog.value.resetSecrets) { - // Update allowed_envs with the new environment variable keys - appCompose.allowed_envs = updateDialog.value.encryptedEnvs.map(env => env.key); + // Update allowed_envs with the new environment variable keys, keeping value specs + appCompose.allowed_envs = mergeAllowedEnvs(currentAppCompose.allowed_envs || [], updateDialog.value.encryptedEnvs); const launchToken = updateDialog.value.encryptedEnvs.find((env) => env.key === 'APP_LAUNCH_TOKEN'); if (launchToken) { diff --git a/dstack/vmm/ui/src/lib/envEncryption.ts b/dstack/vmm/ui/src/lib/envEncryption.ts index c4159b8f0..eae1fe919 100644 --- a/dstack/vmm/ui/src/lib/envEncryption.ts +++ b/dstack/vmm/ui/src/lib/envEncryption.ts @@ -6,13 +6,27 @@ import { Aes256Gcm, CipherSuite, HkdfSha256 } from '@hpke/core'; import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519'; import type { vmm as VmmTypes } from '../proto/vmm_rpc'; -export type EnvEntry = { key: string; value: string }; +export type EnvEntry = { key: string; value: string; spec?: string }; type EnvPayload = { sealed_env?: Uint8Array; encrypted_env?: Uint8Array }; type KeyClient = { getSealedEnvPubKey(request: VmmTypes.IAppId): Promise; getAppEnvEncryptPubKey(request: VmmTypes.IAppId): Promise; }; +/** + * allowed_envs for `envs`. Entries with a value spec (`NAME: spec`), whether + * already in `existing` or given by `envs`, are part of the app's identity and + * are always kept; plain names follow `envs`. + */ +export function mergeAllowedEnvs(existing: string[], envs: EnvEntry[]): string[] { + const nameOf = (entry: string) => entry.split(':', 1)[0]; + const given = envs.filter((env) => env.spec?.trim()).map((env) => `${env.key}: ${env.spec!.trim()}`); + const replaced = new Set(given.map(nameOf)); + const specs = [...existing.filter((entry) => entry.includes(':') && !replaced.has(nameOf(entry))), ...given]; + const covered = new Set(specs.map(nameOf)); + return [...specs, ...envs.map((env) => env.key).filter((key) => !covered.has(key))]; +} + /** Keep key retrieval on the authenticated, same-origin VMM transport. */ export async function encryptEnvPayload( client: KeyClient, @@ -21,6 +35,7 @@ export async function encryptEnvPayload( encryptLegacy: (envs: EnvEntry[], key: Uint8Array) => Promise, supportsSealedEnv: boolean, ): Promise { + envs = envs.map(({ key, value }) => ({ key, value })); const legacyPayload = async () => { const legacy = await client.getAppEnvEncryptPubKey({ app_id: appId }); return { encrypted_env: await encryptLegacy(envs, legacy.public_key) }; diff --git a/dstack/vmm/ui/src/styles/main.css b/dstack/vmm/ui/src/styles/main.css index 3f4f51be2..99a7199a9 100644 --- a/dstack/vmm/ui/src/styles/main.css +++ b/dstack/vmm/ui/src/styles/main.css @@ -1596,7 +1596,7 @@ h1, h2, h3, h4, h5, h6 { } .encrypted-env-row { - grid-template-columns: 200px 1fr auto; + grid-template-columns: 200px 1fr 1fr auto; } .encrypted-env-actions { diff --git a/dstack/vmm/ui/tests/envEncryption.test.cjs b/dstack/vmm/ui/tests/envEncryption.test.cjs index bc3af9cf0..d5c37a0f1 100644 --- a/dstack/vmm/ui/tests/envEncryption.test.cjs +++ b/dstack/vmm/ui/tests/envEncryption.test.cjs @@ -9,7 +9,7 @@ const { runInNewContext } = require('node:vm'); const { webcrypto } = require('node:crypto'); const { CipherSuite, Aes256Gcm, HkdfSha256 } = require('@hpke/core'); const { DhkemX25519HkdfSha256 } = require('@hpke/dhkem-x25519'); -const { encryptEnvPayload } = require('../build/ts/lib/envEncryption.js'); +const { encryptEnvPayload, mergeAllowedEnvs } = require('../build/ts/lib/envEncryption.js'); const { RpcError } = require('../build/ts/lib/vmmRpcClient.js'); const { vmm } = require('../build/ts/proto/vmm_rpc.js'); const { prpc } = require('../build/ts/proto/prpc.js'); @@ -59,6 +59,31 @@ test('seals JSON bytes with HPKE, binds epoch, and rejects tampering', async () } }); +test('value specs go to allowed_envs and never into the encrypted payload', async () => { + const withSpecs = [{ key: 'PORT', value: '8080', spec: ' int(1..=65535) ' }, { key: 'TOKEN', value: 't', spec: '' }]; + assert.deepEqual(mergeAllowedEnvs([], withSpecs), ['PORT: int(1..=65535)', 'TOKEN']); + assert.deepEqual(mergeAllowedEnvs([], envs), ['GREETING']); + const existing = ['OLD', 'NET:/main|test/', 'PORT: int', 'PORT: int(1..)']; + assert.deepEqual(mergeAllowedEnvs(existing, withSpecs), ['NET:/main|test/', 'PORT: int(1..=65535)', 'TOKEN']); + assert.deepEqual( + mergeAllowedEnvs(existing, [{ key: 'TOKEN', value: 't' }, { key: 'PORT', value: '1' }]), + ['NET:/main|test/', 'PORT: int', 'PORT: int(1..)', 'TOKEN'], + ); + + const { pair, response } = await recipient(); + const payload = await encryptEnvPayload({ + getSealedEnvPubKey: async () => response, + getAppEnvEncryptPubKey: noLegacy, + }, withSpecs, appId, noLegacy, true); + assert.deepEqual(await open(pair, payload.sealed_env), { env: withSpecs.map(({ key, value }) => ({ key, value })) }); + let legacyEnvs; + await encryptEnvPayload({ + getSealedEnvPubKey: noLegacy, + getAppEnvEncryptPubKey: async () => ({ public_key: new Uint8Array(32) }), + }, withSpecs, appId, async (given) => { legacyEnvs = given; return new Uint8Array(); }, false); + assert.deepEqual(legacyEnvs, withSpecs.map(({ key, value }) => ({ key, value }))); +}); + test('old or unknown images use legacy encryption even with a capable KMS', async () => { for (const capability of [undefined, false]) { const payload = await encryptEnvPayload({ From 74179a384913a1ccf16c66e93342f297c9f39b4b Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 08:11:13 -0800 Subject: [PATCH 15/25] docs: mention deployment tooling for environment value specs Signed-off-by: Kevin Wang --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ebfebc3d..4aaed0d8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`allowed_envs` entries can constrain values.** An entry may be `NAME: spec`, such as `PORT: int(1..=65535)` or `NETWORK: /mainnet|testnet/`, and the guest refuses to boot when a value does not match. `dstack-util validate-env` - applies the same specs from an `init_script`. See + applies the same specs from an `init_script`. `vmm-cli compose --env-spec` + and the VMM web UI set them, and the VMM rejects malformed `int` and + `float` specs at deployment. See [Environment value specs](docs/security/cvm-boundaries.md#environment-value-specs). ### Security From 32a2497e49667fcfc52150bb241c3a18623a3630 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 19:15:17 -0800 Subject: [PATCH 16/25] feat(dstack-util): add import-env Copies variables from the env object of the user config into the env file, by name or with --all. Each must be in allowed_envs and match its specs, so an init_script needs one line to take values such as API keys from the unmeasured user config. Signed-off-by: Kevin Wang --- CHANGELOG.md | 3 +- docs/security/cvm-boundaries.md | 6 +++ dstack/dstack-util/src/main.rs | 67 +++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4aaed0d8d..110803e88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`allowed_envs` entries can constrain values.** An entry may be `NAME: spec`, such as `PORT: int(1..=65535)` or `NETWORK: /mainnet|testnet/`, and the guest refuses to boot when a value does not match. `dstack-util validate-env` - applies the same specs from an `init_script`. `vmm-cli compose --env-spec` + applies the same specs from an `init_script`, and `dstack-util import-env` + takes variables from `.user-config` under them. `vmm-cli compose --env-spec` and the VMM web UI set them, and the VMM rejects malformed `int` and `float` specs at deployment. See [Environment value specs](docs/security/cvm-boundaries.md#environment-value-specs). diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 31615320c..da73db42e 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -156,6 +156,12 @@ PORT=$PORT dstack-util validate-env --allow-unlisted 'PORT: int(1024..=65535)' | dstack-util validate-env --compose /dstack/app-compose.json --allow-unlisted --env-file /dstack/.host-shared/.user-config || exit 1 ``` +`dstack-util import-env` is the shorthand for the common case: it copies variables from the `env` object of `.user-config` into `.decrypted-env.json`, so the app receives them like encrypted environment variables. Name the variables, or pass `--all` for every variable under `env`. Each one must be in `allowed_envs` and match its specs there; a named variable that `env` lacks counts as empty. + +```bash +dstack-util import-env RPC_API_KEY +``` + `app-compose.service` passes `--compose /dstack/app-compose.json` to `dstack-util exec-with-env`, so an `init_script` that rewrites `.decrypted-env.json` cannot hand the application a variable that is not in `allowed_envs` or a value that breaks a spec there. Guests older than 0.6.7 treat `NAME: spec` as a name that no variable can have, so they drop the variable rather than deliver it unchecked. diff --git a/dstack/dstack-util/src/main.rs b/dstack/dstack-util/src/main.rs index da9de2178..bc596429e 100644 --- a/dstack/dstack-util/src/main.rs +++ b/dstack/dstack-util/src/main.rs @@ -108,6 +108,8 @@ enum Commands { ExecWithEnv(ExecWithEnvArgs), /// Check environment variables of this process against value specs ValidateEnv(ValidateEnvArgs), + /// Copy environment variables from `env` in the user config into the env file + ImportEnv(ImportEnvArgs), } #[derive(Parser)] @@ -139,8 +141,34 @@ struct ExecWithEnvArgs { command: Vec, } +#[derive(Parser)] +struct ImportEnvArgs { + /// Import every variable under `env` in the user config + #[arg(long, conflicts_with = "names")] + all: bool, + /// User config holding the variables under `env` [default: .user-config in the host-shared dir] + #[arg(long)] + user_config: Option, + /// JSON object of variables to merge into [default: .decrypted-env.json in the host-shared dir] + #[arg(long)] + env_file: Option, + /// App compose file whose `allowed_envs` permits and constrains the variables + /// [default: app-compose.json in the host-shared dir] + #[arg(long)] + compose: Option, + /// Variables to import + #[arg(required_unless_present = "all")] + names: Vec, +} + type Envs = std::collections::BTreeMap; +#[derive(serde::Deserialize, Default)] +struct UserConfig { + #[serde(default)] + env: Envs, +} + fn load_envs(path: &Path) -> Result { utils::deserialize_json_file(path) .with_context(|| format!("failed to load env from {}", path.display())) @@ -173,6 +201,44 @@ fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { parse_env_file::check_env(&allowed, |name| envs.get(name).cloned()) } +fn cmd_import_env(args: ImportEnvArgs) -> Result<()> { + use dstack_types::shared_filenames::{ + host_shared_dir, APP_COMPOSE, DECRYPTED_ENV_JSON, USER_CONFIG, + }; + + let shared = host_shared_dir(); + let user_config = args.user_config.unwrap_or_else(|| shared.join(USER_CONFIG)); + let env_file = args + .env_file + .unwrap_or_else(|| shared.join(DECRYPTED_ENV_JSON)); + let compose = args.compose.unwrap_or_else(|| shared.join(APP_COMPOSE)); + + // The VMM writes no user config file for an empty user config. + let mut source = match fs::read_to_string(&user_config) { + Ok(config) => { + serde_json::from_str::(&config) + .with_context(|| format!("failed to parse {}", user_config.display()))? + .env + } + Err(err) if err.kind() == std::io::ErrorKind::NotFound => Envs::new(), + Err(err) => return Err(err.into()), + }; + let names = match args.all { + true => source.keys().cloned().collect(), + false => args.names, + }; + let mut allowed = parse_env_file::parse_allowed_envs(&load_allowed_envs(&compose)?)?; + parse_env_file::check_names(&allowed, &names)?; + allowed.retain(|name, _| names.contains(name)); + + let mut envs = load_envs(&env_file)?; + envs.extend(names.iter().filter_map(|name| source.remove_entry(name))); + parse_env_file::check_env(&allowed, |name| envs.get(name).cloned())?; + let json = serde_json::to_vec(&envs).context("failed to serialize env")?; + safe_write_with_mode(&env_file, json, 0o600) + .with_context(|| format!("failed to write {}", env_file.display())) +} + #[derive(Parser)] /// Hex encode data struct HexCommand { @@ -1759,6 +1825,7 @@ async fn main() -> Result<()> { } Commands::ExecWithEnv(args) => cmd_exec_with_env(args)?, Commands::ValidateEnv(args) => cmd_validate_env(args)?, + Commands::ImportEnv(args) => cmd_import_env(args)?, } Ok(()) From 8bd38b3092e91345925336261e08f62e1f52e033 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 20:08:44 -0800 Subject: [PATCH 17/25] fix(value-spec): check entry names and report empty integer ranges Signed-off-by: Kevin Wang --- dstack/value-spec/src/lib.rs | 64 ++++++++++++++++++++++++++++------ dstack/vmm/src/main_service.rs | 43 +++++++++++++++-------- 2 files changed, 81 insertions(+), 26 deletions(-) diff --git a/dstack/value-spec/src/lib.rs b/dstack/value-spec/src/lib.rs index 2d6850db9..0432cc76d 100644 --- a/dstack/value-spec/src/lib.rs +++ b/dstack/value-spec/src/lib.rs @@ -75,10 +75,11 @@ use winnow::error::{ContextError, ErrMode}; use winnow::token::{one_of, rest}; use winnow::{ModalResult, Parser}; -/// The error returned when a spec fails to parse. +/// The error returned when a spec or a `NAME: spec` entry fails to parse. #[derive(Debug, Error)] -#[error("invalid value spec at offset {offset}: {message}")] +#[error("invalid {what} at offset {offset}: {message}")] pub struct ParseError { + what: &'static str, offset: usize, message: String, } @@ -99,17 +100,24 @@ enum Kind { /// Splits a `NAME: spec` entry into the name and the text of its spec. The /// whitespace after the colon is optional, and an entry without a colon is a -/// bare name. -pub fn split_named(entry: &str) -> (&str, Option<&str>) { - match entry.split_once(':') { - Some((name, spec)) => (name, Some(spec.trim_start())), - None => (entry, None), +/// bare name. A name that carries a spec must be `[A-Za-z_][A-Za-z0-9_]*`. +pub fn split_named(entry: &str) -> Result<(&str, Option<&str>), ParseError> { + let Some((name, spec)) = entry.split_once(':') else { + return Ok((entry, None)); + }; + let is_valid = |(i, c): (usize, char)| { + c == '_' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit()) + }; + match name.char_indices().find(|&at| !is_valid(at)) { + Some((offset, _)) => Err(ParseError::name(offset)), + None if name.is_empty() => Err(ParseError::name(0)), + None => Ok((name, Some(spec.trim_start()))), } } /// Parses a `NAME: spec` entry into the name and its spec. pub fn parse_named(entry: &str) -> Result<(&str, Option), ParseError> { - let (name, spec) = split_named(entry); + let (name, spec) = split_named(entry)?; Ok((name, spec.map(str::parse).transpose()?)) } @@ -119,6 +127,16 @@ const MAX_REGEX_SIZE: usize = 10 << 20; type Range = (Bound, Bound); +impl ParseError { + fn name(offset: usize) -> Self { + Self { + what: "name", + offset, + message: "expected `[A-Za-z_][A-Za-z0-9_]*` before the `:`".into(), + } + } +} + type Number = fn(&mut &str) -> ModalResult; impl ValueSpec { @@ -141,15 +159,14 @@ impl FromStr for ValueSpec { fn from_str(s: &str) -> Result { if s.len() > MAX_SPEC_LEN { return Err(ParseError { + what: "value spec", offset: MAX_SPEC_LEN, message: format!("spec is longer than {MAX_SPEC_LEN} bytes"), }); } let spec = alt(( regex.map(Kind::Regex), - ranges("int", int) - .verify(|ranges: &Vec<_>| ranges.iter().all(has_int)) - .map(Kind::Int), + preceded(peek("int"), cut_err(ints)).map(Kind::Int), ranges("float", decimal).map(Kind::Float), fail.context(Expected(Description("`int`, `float` or `/regex/`"))), )); @@ -158,6 +175,7 @@ impl FromStr for ValueSpec { .map(|kind| Self { kind, optional }) .parse(s) .map_err(|e| ParseError { + what: "value spec", offset: e.offset(), message: e.inner().to_string(), }) @@ -224,6 +242,16 @@ fn range<'a, T: Clone + PartialOrd>( .context(Expected(Description("number or non-empty range"))) } +fn ints(input: &mut &str) -> ModalResult>> { + let ranges = ranges("int", int).parse_next(input)?; + match ranges.iter().all(has_int) { + true => Ok(ranges), + false => fail + .context(Expected(Description("ranges that contain an integer"))) + .parse_next(input), + } +} + /// Whether any integer lies in the range, which `1<..<2` has none of. fn has_int((start, end): &Range) -> bool { let first = match *start { @@ -557,9 +585,21 @@ mod tests { assert_eq!(name("PORT:int").unwrap(), ("PORT", true)); assert_eq!(name("PORT: int(1..=65535)?").unwrap(), ("PORT", true)); assert_eq!(name("URL: /https://.*/").unwrap(), ("URL", true)); + assert_eq!(name("not a name").unwrap(), ("not a name", false)); for entry in ["A:", "A: ", "A: int ", "A:int:int", "A: string"] { assert!(name(entry).is_err(), "{entry:?} should fail"); } + for (entry, offset) in [ + ("A : int", 1), + (" A: int", 0), + (": int", 0), + ("1A: int", 0), + ("A-B: int", 1), + ] { + let error = name(entry).unwrap_err(); + assert_eq!(error.offset, offset, "{entry:?}"); + assert!(error.to_string().starts_with("invalid name at offset")); + } } #[test] @@ -796,6 +836,8 @@ mod tests { assert_eq!(error("int(1..=x)").offset, 8); assert_eq!(error("int(1|a)").offset, 6); assert_eq!(error("/(/").offset, 1); + assert_eq!(error("int(1<..<2)").offset, 11); + assert!(error("int(1<..<2)").message.contains("contain an integer")); let message = error("string").to_string(); assert!( message.starts_with("invalid value spec at offset 0: "), diff --git a/dstack/vmm/src/main_service.rs b/dstack/vmm/src/main_service.rs index 027b3a102..56f723abf 100644 --- a/dstack/vmm/src/main_service.rs +++ b/dstack/vmm/src/main_service.rs @@ -369,7 +369,7 @@ pub fn create_manifest_from_vm_config( let swtpm = needs_swtpm(key_provider, simulated_tee); let disk_prealloc = disk_prealloc_from_vm_config(&request, cvm_config)?; validate_disk_prealloc_against_compose(disk_prealloc, &request.compose_file)?; - validate_allowed_envs(&request.compose_file)?; + validate_allowed_envs(&allowed_envs_from_compose(&request.compose_file)?)?; Ok(Manifest { id, @@ -463,20 +463,31 @@ fn validate_disk_prealloc_against_compose( /// Catch mistyped `allowed_envs` value specs before the guest fails on them at /// boot. Regex specs are left to the guest: compiling one is too costly to do /// for as many entries as a compose file can hold. -fn validate_allowed_envs(compose_file: &str) -> Result<()> { - let compose: serde_json::Value = - serde_json::from_str(compose_file).context("invalid app compose JSON")?; - let entries = compose.get("allowed_envs").and_then(|v| v.as_array()); - for entry in entries.into_iter().flatten().filter_map(|v| v.as_str()) { - let (_, spec) = value_spec::split_named(entry); - if let Some(spec) = spec.filter(|spec| !spec.starts_with('/')) { - spec.parse::() - .with_context(|| format!("invalid allowed_envs entry {entry:?}"))?; - } +fn validate_allowed_envs(entries: &[String]) -> Result<()> { + for entry in entries { + let check = || { + let (_, spec) = value_spec::split_named(entry)?; + match spec.filter(|spec| !spec.starts_with('/')) { + Some(spec) => spec.parse::().map(drop), + None => Ok(()), + } + }; + check().with_context(|| format!("invalid allowed_envs entry {entry:?}"))?; } Ok(()) } +fn allowed_envs_from_compose(compose_file: &str) -> Result> { + #[derive(serde::Deserialize)] + struct Compose { + #[serde(default)] + allowed_envs: Vec, + } + let compose: Compose = + serde_json::from_str(compose_file).context("invalid app compose JSON")?; + Ok(compose.allowed_envs) +} + /// Read `storage_discard` out of app-compose. Everything else in the document /// stays opaque, and a missing field means the app-compose default, which is /// discard enabled. @@ -1174,13 +1185,13 @@ impl VmmRpc for RpcHandler { // touching the host, so a rejected update changes nothing. let new_id = if !request.compose_file.is_empty() { // check the compose file is valid - let _app_compose: AppCompose = + let app_compose: AppCompose = serde_json::from_str(&request.compose_file).context("Invalid compose file")?; if !self.compose_file_path(&request.id)?.exists() { bail!("The instance {} not found", request.id); } validate_disk_prealloc_against_compose(manifest.disk_prealloc, &request.compose_file)?; - validate_allowed_envs(&request.compose_file)?; + validate_allowed_envs(&app_compose.allowed_envs)?; app_id_of(&request.compose_file) } else { Default::default() @@ -1471,9 +1482,9 @@ impl VmmRpc for RpcHandler { async fn get_compose_hash(self, request: VmConfiguration) -> Result { validate_label(&request.name)?; // check the compose file is valid - let _app_compose: AppCompose = + let app_compose: AppCompose = serde_json::from_str(&request.compose_file).context("Invalid compose file")?; - validate_allowed_envs(&request.compose_file)?; + validate_allowed_envs(&app_compose.allowed_envs)?; let hash = hex_sha256(&request.compose_file); Ok(RpcComposeHash { hash }) } @@ -1787,6 +1798,8 @@ mod tests { "PORT: integer", "PORT:", "PORT: int(5..=1)", + "PORT : int", + "PORT : /.*/", ] { let err = format!("{:#}", create(&["TOKEN", bad]).unwrap_err()); assert!(err.contains("invalid allowed_envs entry"), "{err}"); From e863f066159cc2d2697b86682231ce7a160825f0 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 20:08:44 -0800 Subject: [PATCH 18/25] fix(dstack-util): keep .decrypted-env in sync on import-env Signed-off-by: Kevin Wang --- docs/security/cvm-boundaries.md | 6 +++--- dstack/dstack-util/src/main.rs | 13 ++++++++++--- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index da73db42e..8b26bb68b 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -133,7 +133,7 @@ This file is not measured to RTMRs, and the envelope is not bound to an instance #### Environment value specs -Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional. The CVM refuses to boot when the value of `NAME` does not match the spec. A variable that is not set counts as empty, so `NAME` is required unless its spec accepts the empty string, as one ending in `?` does. A spec is one of: +Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional, and `NAME` must be `[A-Za-z_][A-Za-z0-9_]*` with nothing between it and the colon. The CVM refuses to boot when the value of `NAME` does not match the spec. A variable that is not set counts as empty, so `NAME` is required unless its spec accepts the empty string, as one ending in `?` does. A spec is one of: | Spec | Accepts | |------|---------| @@ -153,10 +153,10 @@ A range is `start..=end` or `start.., - /// JSON object of variables to merge into [default: .decrypted-env.json in the host-shared dir] + /// JSON object of variables to merge into [default: .decrypted-env.json in the host-shared + /// dir, with .decrypted-env beside it rewritten to match] #[arg(long)] env_file: Option, /// App compose file whose `allowed_envs` permits and constrains the variables @@ -203,11 +204,12 @@ fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { fn cmd_import_env(args: ImportEnvArgs) -> Result<()> { use dstack_types::shared_filenames::{ - host_shared_dir, APP_COMPOSE, DECRYPTED_ENV_JSON, USER_CONFIG, + host_shared_dir, APP_COMPOSE, DECRYPTED_ENV, DECRYPTED_ENV_JSON, USER_CONFIG, }; let shared = host_shared_dir(); let user_config = args.user_config.unwrap_or_else(|| shared.join(USER_CONFIG)); + let shell_env_file = args.env_file.is_none().then(|| shared.join(DECRYPTED_ENV)); let env_file = args .env_file .unwrap_or_else(|| shared.join(DECRYPTED_ENV_JSON)); @@ -236,7 +238,12 @@ fn cmd_import_env(args: ImportEnvArgs) -> Result<()> { parse_env_file::check_env(&allowed, |name| envs.get(name).cloned())?; let json = serde_json::to_vec(&envs).context("failed to serialize env")?; safe_write_with_mode(&env_file, json, 0o600) - .with_context(|| format!("failed to write {}", env_file.display())) + .with_context(|| format!("failed to write {}", env_file.display()))?; + if let Some(path) = shell_env_file { + safe_write_with_mode(&path, parse_env_file::convert_env_to_str(&envs), 0o600) + .with_context(|| format!("failed to write {}", path.display()))?; + } + Ok(()) } #[derive(Parser)] From 9ee741291a07a3633c6438cf8ebbc39f58528c4e Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 20:08:44 -0800 Subject: [PATCH 19/25] feat(vmm): let vmm-cli and the web UI remove value specs Signed-off-by: Kevin Wang --- docs/vmm-cli-user-guide.md | 2 +- dstack/vmm/src/tests/test_vmm_cli.py | 5 ++++ dstack/vmm/src/vmm-cli.py | 25 ++++++++++++++++--- dstack/vmm/ui/src/composables/useVmManager.ts | 18 ++++++++++--- dstack/vmm/ui/src/lib/envEncryption.ts | 23 +++++++++-------- dstack/vmm/ui/tests/envEncryption.test.cjs | 17 ++++++------- 6 files changed, 62 insertions(+), 28 deletions(-) diff --git a/docs/vmm-cli-user-guide.md b/docs/vmm-cli-user-guide.md index 03c25bf6f..9326f92c8 100644 --- a/docs/vmm-cli-user-guide.md +++ b/docs/vmm-cli-user-guide.md @@ -238,7 +238,7 @@ First, create an application composition file that describes your application: - `--public-logs`: Make logs publicly accessible - `--public-sysinfo`: Make system info publicly accessible - `--env-file`: File with environment variables to encrypt -- `--env-spec`: Allow an environment variable and constrain its value, e.g. `--env-spec 'PORT: int(1..=65535)'`; repeat for more variables. See [environment value specs](./security/cvm-boundaries.md#environment-value-specs). `deploy`, `update` and `update-env` keep these entries when they rewrite `allowed_envs` from an env file +- `--env-spec`: Allow an environment variable and constrain its value, e.g. `--env-spec 'PORT: int(1..=65535)'`; repeat for more variables. See [environment value specs](./security/cvm-boundaries.md#environment-value-specs). `deploy`, `update` and `update-env` keep these entries when they rewrite `allowed_envs` from an env file; pass `--drop-env-spec NAME` to `update` or `update-env` to remove them - `--no-instance-id`: Disable unique instance identification - `--no-storage-discard`: Keep deleted data-disk blocks instead of returning them to the host. Required by `deploy --disk-prealloc falloc|full`, and it also keeps filesystem allocation and deletion patterns from the host. The cost is that the image only ever grows: space freed inside the guest is never given back diff --git a/dstack/vmm/src/tests/test_vmm_cli.py b/dstack/vmm/src/tests/test_vmm_cli.py index f0b54d27f..90ef38a9d 100644 --- a/dstack/vmm/src/tests/test_vmm_cli.py +++ b/dstack/vmm/src/tests/test_vmm_cli.py @@ -232,6 +232,11 @@ def test_specs_are_kept(self) -> None: merge(existing, ["TOKEN", "PORT"]), ["PORT: int(1..=65535)", "NET:/main|test/", "NET: /.{1,8}/", "TOKEN"], ) + self.assertEqual( + merge(existing, ["TOKEN", "PORT"], ["NET", "TOKEN"]), + ["PORT: int(1..=65535)", "TOKEN"], + ) + self.assertEqual(merge(existing, [], ["PORT", "NET"]), []) merged = merge(existing, ["NET", "PORT", "TOKEN"]) self.assertEqual(merge(merged, ["TOKEN", "NET", "PORT"]), merged) diff --git a/dstack/vmm/src/vmm-cli.py b/dstack/vmm/src/vmm-cli.py index 1a8a3ba1f..45ecc8809 100755 --- a/dstack/vmm/src/vmm-cli.py +++ b/dstack/vmm/src/vmm-cli.py @@ -1248,6 +1248,7 @@ def update_vm( image: Optional[str] = None, app_compose: Optional[str] = None, env_file: Optional[str] = None, + drop_env_specs: Iterable[str] = (), user_config: Optional[str] = None, ports: Optional[List[str]] = None, no_ports: bool = False, @@ -1624,13 +1625,29 @@ def format_table(rows, headers): return "\n".join(table) -def merge_allowed_envs(existing: List[str], names: Iterable[str]) -> List[str]: +def add_drop_env_spec_argument(parser: argparse.ArgumentParser) -> None: + """Add the option that removes value specs kept in allowed_envs.""" + parser.add_argument( + "--drop-env-spec", + action="append", + default=[], + metavar="NAME", + help="With --env-file, remove the value specs of an environment variable " + "from allowed_envs (can be used multiple times)", + ) + + +def merge_allowed_envs( + existing: List[str], names: Iterable[str], drop: Iterable[str] = () +) -> List[str]: """Return allowed_envs for the variables `names`. Entries of `existing` that carry a value spec (`NAME: spec`) are part of - the app's identity and are always kept; plain names follow `names`. + the app's identity and are kept unless `drop` names them; plain names + follow `names`. """ - specs = [entry for entry in existing if ":" in entry] + drop = set(drop) + specs = [e for e in existing if ":" in e and e.split(":", 1)[0] not in drop] covered = {entry.split(":", 1)[0] for entry in specs} return specs + [name for name in names if name not in covered] @@ -2332,6 +2349,7 @@ def _patched_format_help(): update_parser.add_argument( "--env-file", help="File with environment variables to encrypt" ) + add_drop_env_spec_argument(update_parser) update_parser.add_argument("--user-config", help="Path to user config file") update_parser.add_argument( "--net", @@ -2534,6 +2552,7 @@ def _patched_format_help(): image=args.image, app_compose=args.compose and read_utf8(args.compose), env_file=args.env_file, + drop_env_specs=args.drop_env_spec, user_config=user_config_content, ports=args.port, no_ports=args.no_ports if hasattr(args, "no_ports") else False, diff --git a/dstack/vmm/ui/src/composables/useVmManager.ts b/dstack/vmm/ui/src/composables/useVmManager.ts index 1608fcb80..049689858 100644 --- a/dstack/vmm/ui/src/composables/useVmManager.ts +++ b/dstack/vmm/ui/src/composables/useVmManager.ts @@ -4,7 +4,7 @@ declare const Vue: any; const { ref, computed, watch, onMounted } = Vue; import type { vmm as VmmTypes } from '../proto/vmm_rpc'; -import { encryptEnvPayload, mergeAllowedEnvs } from '../lib/envEncryption'; +import { allowedEnvsOf, encryptEnvPayload, specEntries } from '../lib/envEncryption'; // Types based on Rust definitions type VmConfiguration = VmmTypes.IVmConfiguration; @@ -1014,7 +1014,7 @@ type CreateVmPayloadSource = { key_provider_id: vmForm.value.key_provider === 'kms' || vmForm.value.key_provider === 'local' ? vmForm.value.key_provider_id : '', - allowed_envs: mergeAllowedEnvs([], vmForm.value.encryptedEnvs), + allowed_envs: allowedEnvsOf(vmForm.value.encryptedEnvs), no_instance_id: !vmForm.value.gateway_enabled, secure_time: false, storage_discard: vmForm.value.storage_discard, @@ -1081,8 +1081,8 @@ type CreateVmPayloadSource = { appCompose.manifest_version = targetManifestVersion; } if (updateDialog.value.resetSecrets) { - // Update allowed_envs with the new environment variable keys, keeping value specs - appCompose.allowed_envs = mergeAllowedEnvs(currentAppCompose.allowed_envs || [], updateDialog.value.encryptedEnvs); + // Update allowed_envs with the new environment variable keys and value specs + appCompose.allowed_envs = allowedEnvsOf(updateDialog.value.encryptedEnvs); const launchToken = updateDialog.value.encryptedEnvs.find((env) => env.key === 'APP_LAUNCH_TOKEN'); if (launchToken) { @@ -1127,6 +1127,16 @@ type CreateVmPayloadSource = { { deep: true }, ); + // Show the value specs of the current compose so they can be kept, edited or removed. + watch( + () => updateDialog.value.resetSecrets, + (resetSecrets) => { + if (resetSecrets && updateDialog.value.encryptedEnvs.length === 0) { + updateDialog.value.encryptedEnvs = specEntries(updateDialog.value.vm?.appCompose?.allowed_envs || []); + } + }, + ); + watch( [ () => updateDialog.value.dockerComposeFile, diff --git a/dstack/vmm/ui/src/lib/envEncryption.ts b/dstack/vmm/ui/src/lib/envEncryption.ts index eae1fe919..25e0986e3 100644 --- a/dstack/vmm/ui/src/lib/envEncryption.ts +++ b/dstack/vmm/ui/src/lib/envEncryption.ts @@ -13,20 +13,21 @@ type KeyClient = { getAppEnvEncryptPubKey(request: VmmTypes.IAppId): Promise; }; -/** - * allowed_envs for `envs`. Entries with a value spec (`NAME: spec`), whether - * already in `existing` or given by `envs`, are part of the app's identity and - * are always kept; plain names follow `envs`. - */ -export function mergeAllowedEnvs(existing: string[], envs: EnvEntry[]): string[] { - const nameOf = (entry: string) => entry.split(':', 1)[0]; - const given = envs.filter((env) => env.spec?.trim()).map((env) => `${env.key}: ${env.spec!.trim()}`); - const replaced = new Set(given.map(nameOf)); - const specs = [...existing.filter((entry) => entry.includes(':') && !replaced.has(nameOf(entry))), ...given]; - const covered = new Set(specs.map(nameOf)); +/** allowed_envs for `envs`: `NAME: spec` for each variable with a value spec, the plain name otherwise. */ +export function allowedEnvsOf(envs: EnvEntry[]): string[] { + const specs = envs.filter((env) => env.spec?.trim()).map((env) => `${env.key}: ${env.spec!.trim()}`); + const covered = new Set(envs.filter((env) => env.spec?.trim()).map((env) => env.key)); return [...specs, ...envs.map((env) => env.key).filter((key) => !covered.has(key))]; } +/** The `NAME: spec` entries of `allowedEnvs` as variables without a value, to edit or remove. */ +export function specEntries(allowedEnvs: string[]): EnvEntry[] { + return allowedEnvs.filter((entry) => entry.includes(':')).map((entry) => { + const at = entry.indexOf(':'); + return { key: entry.slice(0, at), value: '', spec: entry.slice(at + 1).trim() }; + }); +} + /** Keep key retrieval on the authenticated, same-origin VMM transport. */ export async function encryptEnvPayload( client: KeyClient, diff --git a/dstack/vmm/ui/tests/envEncryption.test.cjs b/dstack/vmm/ui/tests/envEncryption.test.cjs index d5c37a0f1..f637d0c71 100644 --- a/dstack/vmm/ui/tests/envEncryption.test.cjs +++ b/dstack/vmm/ui/tests/envEncryption.test.cjs @@ -9,7 +9,7 @@ const { runInNewContext } = require('node:vm'); const { webcrypto } = require('node:crypto'); const { CipherSuite, Aes256Gcm, HkdfSha256 } = require('@hpke/core'); const { DhkemX25519HkdfSha256 } = require('@hpke/dhkem-x25519'); -const { encryptEnvPayload, mergeAllowedEnvs } = require('../build/ts/lib/envEncryption.js'); +const { allowedEnvsOf, encryptEnvPayload, specEntries } = require('../build/ts/lib/envEncryption.js'); const { RpcError } = require('../build/ts/lib/vmmRpcClient.js'); const { vmm } = require('../build/ts/proto/vmm_rpc.js'); const { prpc } = require('../build/ts/proto/prpc.js'); @@ -61,14 +61,13 @@ test('seals JSON bytes with HPKE, binds epoch, and rejects tampering', async () test('value specs go to allowed_envs and never into the encrypted payload', async () => { const withSpecs = [{ key: 'PORT', value: '8080', spec: ' int(1..=65535) ' }, { key: 'TOKEN', value: 't', spec: '' }]; - assert.deepEqual(mergeAllowedEnvs([], withSpecs), ['PORT: int(1..=65535)', 'TOKEN']); - assert.deepEqual(mergeAllowedEnvs([], envs), ['GREETING']); - const existing = ['OLD', 'NET:/main|test/', 'PORT: int', 'PORT: int(1..)']; - assert.deepEqual(mergeAllowedEnvs(existing, withSpecs), ['NET:/main|test/', 'PORT: int(1..=65535)', 'TOKEN']); - assert.deepEqual( - mergeAllowedEnvs(existing, [{ key: 'TOKEN', value: 't' }, { key: 'PORT', value: '1' }]), - ['NET:/main|test/', 'PORT: int', 'PORT: int(1..)', 'TOKEN'], - ); + assert.deepEqual(allowedEnvsOf(withSpecs), ['PORT: int(1..=65535)', 'TOKEN']); + assert.deepEqual(allowedEnvsOf(envs), ['GREETING']); + const existing = ['OLD', 'NET:/main|test:x/', 'PORT: int(1..)']; + const kept = specEntries(existing); + assert.deepEqual(kept, [{ key: 'NET', value: '', spec: '/main|test:x/' }, { key: 'PORT', value: '', spec: 'int(1..)' }]); + assert.deepEqual(allowedEnvsOf(kept), ['NET: /main|test:x/', 'PORT: int(1..)']); + assert.deepEqual(allowedEnvsOf(kept.slice(1)), ['PORT: int(1..)']); const { pair, response } = await recipient(); const payload = await encryptEnvPayload({ From 4fd8e19519c9d57806803c3aaa56aeae3e1353e6 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 20:29:54 -0800 Subject: [PATCH 20/25] fix(dstack-util): leave unset env variables to the check before the app starts The boot-time check ran before any init_script, so a variable with a spec could never be supplied by import-env. import-env now refuses to replace a different value and applies the encrypted env limits, and validate-env rejects non-UTF-8 variables instead of checking a lossy copy. Signed-off-by: Kevin Wang --- CHANGELOG.md | 4 + docs/security/cvm-boundaries.md | 4 +- dstack/dstack-util/src/main.rs | 29 +++++-- dstack/dstack-util/src/parse_env_file.rs | 100 +++++++++++++++-------- dstack/dstack-util/src/system_setup.rs | 1 - formal/DstackFormal/Guest/EnvFile.lean | 31 +++---- 6 files changed, 112 insertions(+), 57 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 110803e88..7bbbc23c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 `update --compose`. `update --kms-encrypt-url` encrypts `--env-file` without replacing the VM's KMS URLs, which `--kms-url` does. +- **`app-compose.service` rejects environment variables outside + `allowed_envs`.** It used to pass on whatever `.decrypted-env.json` held, so + an `init_script` that adds variables to that file must now have them listed + in `allowed_envs`. - **Go SDK module moves to `github.com/Dstack-TEE/dstack/sdk/go/dstack`.** `go get` now targets the module rooted at the `dstack` package, so pkg.go.dev lists it under its product name instead of "go". The `dstack` package import diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md index 8b26bb68b..de1608a09 100644 --- a/docs/security/cvm-boundaries.md +++ b/docs/security/cvm-boundaries.md @@ -133,7 +133,7 @@ This file is not measured to RTMRs, and the envelope is not bound to an instance #### Environment value specs -Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional, and `NAME` must be `[A-Za-z_][A-Za-z0-9_]*` with nothing between it and the colon. The CVM refuses to boot when the value of `NAME` does not match the spec. A variable that is not set counts as empty, so `NAME` is required unless its spec accepts the empty string, as one ending in `?` does. A spec is one of: +Since 0.6.7, an `allowed_envs` entry may be `NAME: spec`, such as `PORT: int(1..=65535)`; the space after the colon is optional, and `NAME` must be `[A-Za-z_][A-Za-z0-9_]*` with nothing between it and the colon. The CVM refuses to boot when the encrypted environment gives `NAME` a value that does not match the spec. Before the application starts, after every `init_script` has run, a variable that is still not set counts as empty, so `NAME` is required unless its spec accepts the empty string, as one ending in `?` does. This last check is made by `app-compose.service`; a program that reads `.decrypted-env` on its own does not get it. A spec is one of: | Spec | Accepts | |------|---------| @@ -156,7 +156,7 @@ PORT=$PORT dstack-util validate-env --allow-unlisted 'PORT: int(1024..=65535)' | dstack-util validate-env --compose /dstack/app-compose.json --env-file env.json || exit 1 ``` -`dstack-util import-env` is the shorthand for the common case: it copies variables from the `env` object of `.user-config` into `.decrypted-env.json` and `.decrypted-env`, so the app receives them like encrypted environment variables. Name the variables, or pass `--all` for every variable under `env`. Each one must be in `allowed_envs` and match its specs there; a named variable that `env` lacks counts as empty. +`dstack-util import-env` is the shorthand for the common case: it copies variables from the `env` object of `.user-config` into `.decrypted-env.json` and `.decrypted-env`, so the app receives them like encrypted environment variables. Name the variables, or pass `--all` for every variable under `env`. Each one must be in `allowed_envs` and match its specs there; a named variable that `env` lacks counts as empty. A variable the encrypted environment already set to a different value is an error, and the size limits of the encrypted environment apply. ```bash dstack-util import-env RPC_API_KEY diff --git a/dstack/dstack-util/src/main.rs b/dstack/dstack-util/src/main.rs index de8de98cd..5732bfb39 100644 --- a/dstack/dstack-util/src/main.rs +++ b/dstack/dstack-util/src/main.rs @@ -2,7 +2,7 @@ // // SPDX-License-Identifier: Apache-2.0 -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use clap::{Parser, Subcommand}; use dstack_attest::emit_runtime_event; use dstack_types::{KeyProvider, KeyProviderKind}; @@ -182,13 +182,20 @@ fn load_allowed_envs(path: &Path) -> Result> { } fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { + let mut not_utf8 = Vec::new(); let envs = match &args.env_file { Some(path) => load_envs(path)?, None => std::env::vars_os() - .map(|(name, value)| { - let name = name.to_string_lossy().into_owned(); - (name, value.to_string_lossy().into_owned()) - }) + .filter_map( + |(name, value)| match (name.into_string(), value.into_string()) { + (Ok(name), Ok(value)) => Some((name, value)), + (name, _) => { + not_utf8 + .push(name.unwrap_or_else(|name| name.to_string_lossy().into_owned())); + None + } + }, + ) .collect(), }; let mut entries = args.specs; @@ -196,6 +203,10 @@ fn cmd_validate_env(args: ValidateEnvArgs) -> Result<()> { entries.extend(load_allowed_envs(compose)?); } let allowed = parse_env_file::parse_allowed_envs(&entries)?; + let checked = |name: &&String| !args.allow_unlisted || allowed.contains_key(*name); + if let Some(name) = not_utf8.iter().find(checked) { + bail!("env {name} is not valid UTF-8"); + } if !args.allow_unlisted { parse_env_file::check_names(&allowed, envs.keys())?; } @@ -234,7 +245,13 @@ fn cmd_import_env(args: ImportEnvArgs) -> Result<()> { allowed.retain(|name, _| names.contains(name)); let mut envs = load_envs(&env_file)?; - envs.extend(names.iter().filter_map(|name| source.remove_entry(name))); + for (name, value) in names.iter().filter_map(|name| source.remove_entry(name)) { + if envs.get(&name).is_some_and(|existing| *existing != value) { + bail!("env {name} is already set to a different value"); + } + envs.insert(name, value); + } + parse_env_file::check_limits(&envs)?; parse_env_file::check_env(&allowed, |name| envs.get(name).cloned())?; let json = serde_json::to_vec(&envs).context("failed to serialize env")?; safe_write_with_mode(&env_file, json, 0o600) diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index fc7e4e21c..6890b6a2e 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -87,28 +87,25 @@ pub fn check_names<'a>( } } -pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result> { - const MAX_ITEMS: usize = 1024; - const MAX_TOTAL_SIZE: usize = 1024 * 1024; +const MAX_ITEMS: usize = 1024; +const MAX_TOTAL_SIZE: usize = 1024 * 1024; - let data: Data = serde_json::from_slice(env_json).context("Failed to parse env")?; +struct Limits { + key_regex: regex::Regex, + total_size: usize, +} - if data.env.len() > MAX_ITEMS { - bail!("Too many environment variables: {}", data.env.len()); +impl Limits { + fn new() -> Result { + const KEY_REGEX: &str = r"^[a-zA-Z_][a-zA-Z0-9_]*$"; + Ok(Self { + key_regex: regex::Regex::new(KEY_REGEX) + .context("Failed to compile environment key validation regex")?, + total_size: 0, + }) } - const KEY_REGEX: &str = r"^[a-zA-Z_][a-zA-Z0-9_]*$"; - let key_regex = regex::Regex::new(KEY_REGEX) - .context("Failed to compile environment key validation regex")?; - - let mut env = BTreeMap::new(); - let mut total_size = 0; - - for Pair { key, value } in data.env { - if !allowed.contains_key(&key) { - warn!("Skipping unauthorized environment variable: {key}"); - continue; - } + fn add(&mut self, key: &str, value: &str) -> Result<()> { // Check key length (common Linux limit is 255) if key.len() > 255 { bail!("Environment variable name too long: {}", key); @@ -120,17 +117,54 @@ pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result MAX_TOTAL_SIZE { + self.total_size += key.len() + value.len(); + if self.total_size > MAX_TOTAL_SIZE { bail!("Environment variables total size too large"); } + Ok(()) + } +} + +/// Applies the limits of [`parse_env`] to variables that did not come through it. +pub fn check_limits(env: &BTreeMap) -> Result<()> { + if env.len() > MAX_ITEMS { + bail!("Too many environment variables: {}", env.len()); + } + let mut limits = Limits::new()?; + env.iter() + .try_for_each(|(key, value)| limits.add(key, value)) +} + +/// Keeps the variables `allowed` names and checks their values against its +/// specs. A variable that is absent is not checked here: an `init_script` may +/// still supply it, and [`check_env`] runs before the app starts. +pub fn parse_env(env_json: &[u8], allowed: &AllowedEnvs) -> Result> { + let data: Data = serde_json::from_slice(env_json).context("Failed to parse env")?; + + if data.env.len() > MAX_ITEMS { + bail!("Too many environment variables: {}", data.env.len()); + } + + let mut limits = Limits::new()?; + let mut env = BTreeMap::new(); + + for Pair { key, value } in data.env { + if !allowed.contains_key(&key) { + warn!("Skipping unauthorized environment variable: {key}"); + continue; + } + limits.add(&key, &value)?; env.insert(key, value); } - check_env(allowed, |name| env.get(name).cloned())?; + for (name, value) in &env { + if !allowed[name].iter().all(|spec| spec.matches(value)) { + bail!("value of env {name} does not match its spec"); + } + } Ok(env) } @@ -201,19 +235,19 @@ mod tests { } #[test] - fn unset_variables_count_as_empty() { - let allowed = ["PORT: int(1..=65535)?", "NET: /(main|test)?/", "ANY"]; + fn absent_variables_are_left_to_check_env() { + let allowed = ["PORT: int(1..=65535)", "NET: /main|test/", "ANY"]; assert!(parse(&allowed, &[("OTHER", "1")]).unwrap().is_empty()); - assert!(parse(&allowed, &[("PORT", ""), ("ANY", "")]).is_ok()); + assert!(parse(&allowed, &[("PORT", "")]).is_err()); + assert!(parse(&["PORT: int(1..=65535)?"], &[("PORT", "")]).is_ok()); + } - for (allowed, name) in [ - ("PORT: int(1..=65535)", "PORT"), - ("NET: /main|test/", "NET"), - ] { - let err = parse(&[allowed], &[]).unwrap_err().to_string(); - assert!(err.contains(&format!("env {name} is not set")), "{err}"); - assert!(parse(&[allowed], &[(name, "")]).is_err()); - } + #[test] + fn limits_apply_outside_parse_env() { + let env = |key: &str, value: String| BTreeMap::from([(key.to_string(), value)]); + assert!(check_limits(&env("A", "x".repeat(128 * 1024))).is_ok()); + assert!(check_limits(&env("A", "x".repeat(128 * 1024 + 1))).is_err()); + assert!(check_limits(&env("A B", String::new())).is_err()); } #[test] diff --git a/dstack/dstack-util/src/system_setup.rs b/dstack/dstack-util/src/system_setup.rs index be4fb9807..74edaa8e5 100644 --- a/dstack/dstack-util/src/system_setup.rs +++ b/dstack/dstack-util/src/system_setup.rs @@ -3440,7 +3440,6 @@ impl Stage1<'_> { let (decrypted_env, sealed) = if self.shared.sealed_env.is_none() && self.shared.encrypted_env.is_empty() { info!("No encrypted env, using default"); - crate::parse_env_file::check_env(&allowed_envs, |_| None)?; (Default::default(), Vec::new()) } else { info!("Processing encrypted env"); diff --git a/formal/DstackFormal/Guest/EnvFile.lean b/formal/DstackFormal/Guest/EnvFile.lean index d876805ee..d314ce132 100644 --- a/formal/DstackFormal/Guest/EnvFile.lean +++ b/formal/DstackFormal/Guest/EnvFile.lean @@ -281,12 +281,13 @@ unset. -/ def valueOf (name : List Char) (env : List (List Char × List Char)) : List Char := (env.reverse.lookup name).getD [] -/-- `parse_env`: the loop, then `check_env` over the allowed `names`. -/ -def parseEnv (allowed : List Char → Bool) (names : List (List Char)) +/-- `parse_env`: the loop, then the spec check of every variable that is set. +A variable that is absent is left to `check_env`, which runs before the app. -/ +def parseEnv (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) (pairs : List (List Char × List Char)) : Option (List (List Char × List Char)) := (parseEnvGo allowed 0 pairs).bind fun env => - if names.all (fun name => matchesSpecs name (valueOf name env)) then some env else none + if env.all (fun kv => matchesSpecs kv.1 (valueOf kv.1 env)) then some env else none theorem parseEnvGo_spec (allowed : List Char → Bool) : ∀ (total : Nat) (pairs out : List (List Char × List Char)), parseEnvGo allowed total pairs = some out → @@ -323,40 +324,40 @@ theorem parseEnvGo_spec (allowed : List Char → Bool) : exact ⟨hs.cons _, hp⟩ /-- Every accepted entry is allowed, has a valid key and respects the limits, -and every allowed name's value matches its specs. -/ -theorem parseEnv_spec (allowed : List Char → Bool) (names : List (List Char)) +and the value of every variable that is set matches its specs. -/ +theorem parseEnv_spec (allowed : List Char → Bool) (matchesSpecs : List Char → List Char → Bool) (pairs out : List (List Char × List Char)) - (h : parseEnv allowed names matchesSpecs pairs = some out) : + (h : parseEnv allowed matchesSpecs pairs = some out) : out.Sublist pairs ∧ (∀ kv ∈ out, allowed kv.1 = true ∧ validKey kv.1 = true ∧ kv.1.length ≤ 255 ∧ kv.2.length ≤ 128 * 1024) ∧ - ∀ name ∈ names, matchesSpecs name (valueOf name out) = true := by + ∀ kv ∈ out, matchesSpecs kv.1 (valueOf kv.1 out) = true := by unfold parseEnv at h cases hg : parseEnvGo allowed 0 pairs with | none => simp [hg] at h | some env => simp only [hg, Option.bind_some] at h - by_cases hc : names.all (fun name => matchesSpecs name (valueOf name env)) = true + by_cases hc : env.all (fun kv => matchesSpecs kv.1 (valueOf kv.1 env)) = true · simp only [hc, ite_true, Option.some.injEq] at h subst h obtain ⟨hs, hp⟩ := parseEnvGo_spec allowed 0 pairs env hg - exact ⟨hs, hp, fun name hn => List.all_eq_true.mp hc name hn⟩ + exact ⟨hs, hp, fun kv hkv => List.all_eq_true.mp hc kv hkv⟩ · simp [hc] at h /-- Unauthorized keys are skipped, not rejected. -/ -example : parseEnv (fun k => k == "A".toList) [] (fun _ _ => true) +example : parseEnv (fun k => k == "A".toList) (fun _ _ => true) [("B".toList, []), ("A".toList, "1".toList)] = some [("A".toList, "1".toList)] := by decide /-- A value failing its specs is an error, not a skip. -/ -example : parseEnv (fun _ => true) ["B".toList] (fun _ v => v == "1".toList) +example : parseEnv (fun _ => true) (fun k v => k != "B".toList || v == "1".toList) [("A".toList, "1".toList), ("B".toList, "2".toList)] = none := by decide -/-- An unset variable is checked as the empty value. -/ -example : parseEnv (fun _ => true) ["B".toList] (fun _ v => !v.isEmpty) - [("A".toList, "1".toList)] = none := by decide +/-- An absent variable is not checked here. -/ +example : (parseEnv (fun _ => true) (fun k v => k != "B".toList || !v.isEmpty) + [("A".toList, "1".toList)]).isSome = true := by decide /-- The last duplicate is the one checked. -/ -example : (parseEnv (fun _ => true) ["A".toList] (fun _ v => v == "2".toList) +example : (parseEnv (fun _ => true) (fun _ v => v == "2".toList) [("A".toList, "1".toList), ("A".toList, "2".toList)]).isSome = true := by decide end DstackFormal.Guest.EnvFile From 8f0ee40db47b41a28ecced5a1f78b1810f26f2df Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 20:29:54 -0800 Subject: [PATCH 21/25] fix(vmm): keep the order of allowed_envs and check --env-spec arguments The web UI keeps variables with a spec when a file or text replaces the list. Signed-off-by: Kevin Wang --- docs/vmm-cli-user-guide.md | 2 +- dstack/vmm/src/tests/test_vmm_cli.py | 12 ++++++- dstack/vmm/src/vmm-cli.py | 36 ++++++++++++++----- .../ui/src/components/EncryptedEnvEditor.ts | 22 ++---------- dstack/vmm/ui/src/lib/envEncryption.ts | 26 ++++++++++++-- dstack/vmm/ui/tests/envEncryption.test.cjs | 8 ++++- 6 files changed, 72 insertions(+), 34 deletions(-) diff --git a/docs/vmm-cli-user-guide.md b/docs/vmm-cli-user-guide.md index 9326f92c8..ea2787398 100644 --- a/docs/vmm-cli-user-guide.md +++ b/docs/vmm-cli-user-guide.md @@ -238,7 +238,7 @@ First, create an application composition file that describes your application: - `--public-logs`: Make logs publicly accessible - `--public-sysinfo`: Make system info publicly accessible - `--env-file`: File with environment variables to encrypt -- `--env-spec`: Allow an environment variable and constrain its value, e.g. `--env-spec 'PORT: int(1..=65535)'`; repeat for more variables. See [environment value specs](./security/cvm-boundaries.md#environment-value-specs). `deploy`, `update` and `update-env` keep these entries when they rewrite `allowed_envs` from an env file; pass `--drop-env-spec NAME` to `update` or `update-env` to remove them +- `--env-spec`: Allow an environment variable, as `NAME`, or also constrain its value, as `NAME: SPEC`, e.g. `--env-spec 'PORT: int(1..=65535)'`; repeat for more variables. See [environment value specs](./security/cvm-boundaries.md#environment-value-specs). `deploy`, `update` and `update-env` keep these entries when they rewrite `allowed_envs` from an env file; pass `--drop-env-spec NAME` to `update` or `update-env` to remove them - `--no-instance-id`: Disable unique instance identification - `--no-storage-discard`: Keep deleted data-disk blocks instead of returning them to the host. Required by `deploy --disk-prealloc falloc|full`, and it also keeps filesystem allocation and deletion patterns from the host. The cost is that the image only ever grows: space freed inside the guest is never given back diff --git a/dstack/vmm/src/tests/test_vmm_cli.py b/dstack/vmm/src/tests/test_vmm_cli.py index 90ef38a9d..6fd5e0b0b 100644 --- a/dstack/vmm/src/tests/test_vmm_cli.py +++ b/dstack/vmm/src/tests/test_vmm_cli.py @@ -222,7 +222,7 @@ def test_plain_names_follow_the_env_file(self) -> None: """Rebuild entries without a spec from the env file.""" merge = VMM_CLI.merge_allowed_envs self.assertEqual(merge([], {"A": "1", "B": "2"}), ["A", "B"]) - self.assertEqual(merge(["A", "C"], ["B", "A"]), ["B", "A"]) + self.assertEqual(merge(["A", "C"], ["B", "A"]), ["A", "B"]) def test_specs_are_kept(self) -> None: """Keep entries with a spec, and stay stable when merged again.""" @@ -232,6 +232,8 @@ def test_specs_are_kept(self) -> None: merge(existing, ["TOKEN", "PORT"]), ["PORT: int(1..=65535)", "NET:/main|test/", "NET: /.{1,8}/", "TOKEN"], ) + unchanged = ["TOKEN", "PORT: int(1..)", "OTHER"] + self.assertEqual(merge(unchanged, ["OTHER", "TOKEN"]), unchanged) self.assertEqual( merge(existing, ["TOKEN", "PORT"], ["NET", "TOKEN"]), ["PORT: int(1..=65535)", "TOKEN"], @@ -240,6 +242,14 @@ def test_specs_are_kept(self) -> None: merged = merge(existing, ["NET", "PORT", "TOKEN"]) self.assertEqual(merge(merged, ["TOKEN", "NET", "PORT"]), merged) + def test_env_spec_arguments_are_checked(self) -> None: + """Accept a bare name or a name with a spec, and nothing else.""" + for entry in ["TOKEN", "_A1", "PORT: int(1..=65535)", "NET:/a|b/"]: + self.assertEqual(VMM_CLI.env_spec(entry), entry) + for entry in ["", "PORT int", "PORT : int", "1A", "A-B", "PORT:", "PORT: "]: + with self.assertRaises(argparse.ArgumentTypeError): + VMM_CLI.env_spec(entry) + class LaunchTicketTests(unittest.TestCase): """Pin the hash the contracts allow; the KMS computes the same.""" diff --git a/dstack/vmm/src/vmm-cli.py b/dstack/vmm/src/vmm-cli.py index 45ecc8809..0e9b4082d 100755 --- a/dstack/vmm/src/vmm-cli.py +++ b/dstack/vmm/src/vmm-cli.py @@ -1077,7 +1077,9 @@ def create_app_compose(self, args) -> None: "key_provider_id": args.key_provider_id or "", "public_logs": args.public_logs, "public_sysinfo": args.public_sysinfo, - "allowed_envs": merge_allowed_envs(args.env_spec, envs), + "allowed_envs": merge_allowed_envs( + args.env_spec, [*(s for s in args.env_spec if ":" not in s), *envs] + ), "no_instance_id": args.no_instance_id, "secure_time": args.secure_time, } @@ -1637,19 +1639,34 @@ def add_drop_env_spec_argument(parser: argparse.ArgumentParser) -> None: ) +def env_spec(entry: str) -> str: + """Check an `--env-spec` argument: `NAME` or `NAME: SPEC`.""" + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*(:\s*\S.*)?", entry): + raise argparse.ArgumentTypeError( + f"expected NAME or 'NAME: SPEC', with NAME a valid variable name: {entry!r}" + ) + return entry + + def merge_allowed_envs( existing: List[str], names: Iterable[str], drop: Iterable[str] = () ) -> List[str]: - """Return allowed_envs for the variables `names`. + """Return allowed_envs for the variables `names`, in the order of `existing`. Entries of `existing` that carry a value spec (`NAME: spec`) are part of the app's identity and are kept unless `drop` names them; plain names - follow `names`. + follow `names`, and new ones go last. """ - drop = set(drop) - specs = [e for e in existing if ":" in e and e.split(":", 1)[0] not in drop] - covered = {entry.split(":", 1)[0] for entry in specs} - return specs + [name for name in names if name not in covered] + names, drop = list(names), set(drop) + + def keep(entry: str) -> bool: + if ":" in entry: + return entry.split(":", 1)[0] not in drop + return entry in names + + kept = [entry for entry in existing if keep(entry)] + covered = {entry.split(":", 1)[0] for entry in kept} + return kept + [name for name in names if name not in covered] def parse_env_file(file_path: str) -> Dict[str, str]: @@ -2094,8 +2111,9 @@ def _patched_format_help(): "--env-spec", action="append", default=[], - metavar="NAME: SPEC", - help="Allow an environment variable and constrain its value, " + type=env_spec, + metavar="NAME[: SPEC]", + help="Allow an environment variable and optionally constrain its value, " "e.g. 'PORT: int(1..=65535)' (can be used multiple times)", ) compose_parser.add_argument( diff --git a/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts b/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts index 772492fdb..31bab8648 100644 --- a/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts +++ b/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: © 2025 Phala Network // SPDX-License-Identifier: Apache-2.0 +const { replaceEnvs } = require('../lib/envEncryption'); + declare const FileReader: any; type EnvVar = { key: string; value: string; spec?: string }; @@ -109,26 +111,8 @@ const EncryptedEnvEditorComponent = { } this.replaceFromText(content); }, - /** Replace the variables with `KEY=VALUE` lines, keeping the specs of the names that remain. */ replaceFromText(this: ComponentInstance, content: string) { - const specs = new Map(this.envVars.map((env) => [env.key, env.spec])); - this.envVars.splice(0, this.envVars.length); - for (const line of content.split('\n')) { - const trimmed = line.trim(); - if (!trimmed || trimmed.startsWith('#')) { - continue; - } - const equalIndex = trimmed.indexOf('='); - if (equalIndex === -1) { - continue; - } - const key = trimmed.substring(0, equalIndex).trim(); - const value = trimmed.substring(equalIndex + 1).trim(); - if (!key) { - continue; - } - this.envVars.push({ key, value, spec: specs.get(key) }); - } + this.envVars.splice(0, this.envVars.length, ...replaceEnvs(this.envVars, content)); }, loadEnvFromFile(this: ComponentInstance, event: Event) { const input = event.target as HTMLInputElement | null; diff --git a/dstack/vmm/ui/src/lib/envEncryption.ts b/dstack/vmm/ui/src/lib/envEncryption.ts index 25e0986e3..58199fc2f 100644 --- a/dstack/vmm/ui/src/lib/envEncryption.ts +++ b/dstack/vmm/ui/src/lib/envEncryption.ts @@ -13,11 +13,31 @@ type KeyClient = { getAppEnvEncryptPubKey(request: VmmTypes.IAppId): Promise; }; -/** allowed_envs for `envs`: `NAME: spec` for each variable with a value spec, the plain name otherwise. */ +/** allowed_envs for `envs`, in their order: `NAME: spec` for a variable with a value spec, the plain name otherwise. */ export function allowedEnvsOf(envs: EnvEntry[]): string[] { - const specs = envs.filter((env) => env.spec?.trim()).map((env) => `${env.key}: ${env.spec!.trim()}`); const covered = new Set(envs.filter((env) => env.spec?.trim()).map((env) => env.key)); - return [...specs, ...envs.map((env) => env.key).filter((key) => !covered.has(key))]; + const entries = envs.flatMap((env) => { + if (env.spec?.trim()) return [`${env.key}: ${env.spec.trim()}`]; + return covered.has(env.key) ? [] : [env.key]; + }); + return [...new Set(entries)]; +} + +/** `envs` replaced by `KEY=VALUE` lines. Variables with a value spec stay, without a value if no line names them. */ +export function replaceEnvs(envs: EnvEntry[], content: string): EnvEntry[] { + const lines = content.split('\n').map((line) => line.trim()) + .filter((line) => !line.startsWith('#') && line.indexOf('=') > 0) + .map((line) => ({ key: line.slice(0, line.indexOf('=')).trim(), value: line.slice(line.indexOf('=') + 1).trim() })) + .filter((line) => line.key); + const withSpec = envs.filter((env) => env.spec?.trim()); + const named = new Set(lines.map((line) => line.key)); + return [ + ...lines.flatMap((line) => { + const rows = withSpec.filter((env) => env.key === line.key); + return rows.length ? rows.map((env) => ({ ...env, value: line.value })) : [line]; + }), + ...withSpec.filter((env) => !named.has(env.key)).map((env) => ({ ...env, value: '' })), + ]; } /** The `NAME: spec` entries of `allowedEnvs` as variables without a value, to edit or remove. */ diff --git a/dstack/vmm/ui/tests/envEncryption.test.cjs b/dstack/vmm/ui/tests/envEncryption.test.cjs index f637d0c71..a56fa0947 100644 --- a/dstack/vmm/ui/tests/envEncryption.test.cjs +++ b/dstack/vmm/ui/tests/envEncryption.test.cjs @@ -9,7 +9,7 @@ const { runInNewContext } = require('node:vm'); const { webcrypto } = require('node:crypto'); const { CipherSuite, Aes256Gcm, HkdfSha256 } = require('@hpke/core'); const { DhkemX25519HkdfSha256 } = require('@hpke/dhkem-x25519'); -const { allowedEnvsOf, encryptEnvPayload, specEntries } = require('../build/ts/lib/envEncryption.js'); +const { allowedEnvsOf, encryptEnvPayload, replaceEnvs, specEntries } = require('../build/ts/lib/envEncryption.js'); const { RpcError } = require('../build/ts/lib/vmmRpcClient.js'); const { vmm } = require('../build/ts/proto/vmm_rpc.js'); const { prpc } = require('../build/ts/proto/prpc.js'); @@ -68,6 +68,12 @@ test('value specs go to allowed_envs and never into the encrypted payload', asyn assert.deepEqual(kept, [{ key: 'NET', value: '', spec: '/main|test:x/' }, { key: 'PORT', value: '', spec: 'int(1..)' }]); assert.deepEqual(allowedEnvsOf(kept), ['NET: /main|test:x/', 'PORT: int(1..)']); assert.deepEqual(allowedEnvsOf(kept.slice(1)), ['PORT: int(1..)']); + assert.deepEqual(allowedEnvsOf([{ key: 'A', value: '' }, ...kept, { key: 'PORT', value: '' }]), ['A', 'NET: /main|test:x/', 'PORT: int(1..)']); + assert.deepEqual(replaceEnvs([...kept, { key: 'OLD', value: 'o' }], '# c\nTOKEN=t=1\n PORT = 80 \nbad\n=x'), [ + { key: 'TOKEN', value: 't=1' }, + { key: 'PORT', value: '80', spec: 'int(1..)' }, + { key: 'NET', value: '', spec: '/main|test:x/' }, + ]); const { pair, response } = await recipient(); const payload = await encryptEnvPayload({ From 15aa4d53a70d6a1a02de42b832c1a967bae91c03 Mon Sep 17 00:00:00 2001 From: Kevin Wang Date: Wed, 25 Nov 2026 20:34:52 -0800 Subject: [PATCH 22/25] fix(vmm): leave variables listed only for their spec unset The web UI no longer encrypts an empty value for them or hashes it as the launch token, and vmm-cli update reports --drop-env-spec without --env-file. Signed-off-by: Kevin Wang --- CHANGELOG.md | 4 +++- dstack/dstack-util/src/parse_env_file.rs | 2 +- dstack/vmm/src/vmm-cli.py | 2 ++ dstack/vmm/ui/src/components/EncryptedEnvEditor.ts | 2 +- dstack/vmm/ui/src/composables/useVmManager.ts | 4 ++-- dstack/vmm/ui/src/lib/envEncryption.ts | 3 ++- dstack/vmm/ui/tests/envEncryption.test.cjs | 8 +++++--- formal/DstackFormal/Guest/EnvFile.lean | 3 ++- 8 files changed, 18 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bbbc23c1..d254f54c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,7 +45,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`app-compose.service` rejects environment variables outside `allowed_envs`.** It used to pass on whatever `.decrypted-env.json` held, so an `init_script` that adds variables to that file must now have them listed - in `allowed_envs`. + in `allowed_envs`. An `allowed_envs` entry that contains a `:` must now be + a valid `NAME: spec`; such an entry used to be a name no variable could + have, and now stops the boot. - **Go SDK module moves to `github.com/Dstack-TEE/dstack/sdk/go/dstack`.** `go get` now targets the module rooted at the `dstack` package, so pkg.go.dev lists it under its product name instead of "go". The `dstack` package import diff --git a/dstack/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index 6890b6a2e..688eb782c 100644 --- a/dstack/dstack-util/src/parse_env_file.rs +++ b/dstack/dstack-util/src/parse_env_file.rs @@ -132,7 +132,7 @@ impl Limits { /// Applies the limits of [`parse_env`] to variables that did not come through it. pub fn check_limits(env: &BTreeMap) -> Result<()> { if env.len() > MAX_ITEMS { - bail!("Too many environment variables: {}", env.len()); + bail!("too many environment variables: {}", env.len()); } let mut limits = Limits::new()?; env.iter() diff --git a/dstack/vmm/src/vmm-cli.py b/dstack/vmm/src/vmm-cli.py index 0e9b4082d..d3b976e40 100755 --- a/dstack/vmm/src/vmm-cli.py +++ b/dstack/vmm/src/vmm-cli.py @@ -1274,6 +1274,8 @@ def update_vm( "--env-file requires --kms-encrypt-url or --kms-url to encrypt " "environment variables" ) + if drop_env_specs and not env_file: + raise Exception("--drop-env-spec requires --env-file") updates = [] diff --git a/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts b/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts index 31bab8648..342bec2f0 100644 --- a/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts +++ b/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts @@ -60,7 +60,7 @@ const EncryptedEnvEditorComponent = {
- +