Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
2c797be
feat(value-spec): add a spec language for validating string values
kvinwang Nov 25, 2026
6d5e14c
feat(dstack-util): validate env values against specs in allowed_envs
kvinwang Nov 25, 2026
967353c
feat(dstack-util): add validate-env subcommand
kvinwang Nov 25, 2026
e4fdafe
feat(value-spec): accept the empty string with a trailing ?
kvinwang Nov 25, 2026
c70fdd5
feat(dstack-util): check env values against specs in exec-with-env
kvinwang Nov 25, 2026
15c2412
docs: add environment value specs to the changelog
kvinwang Nov 25, 2026
73c5cf1
feat(dstack-util): allow whitespace before the spec in allowed_envs
kvinwang Nov 25, 2026
6868d78
feat(value-spec): bound spec length and pin the regex size limit
kvinwang Nov 25, 2026
83e28d4
feat(dstack-util): treat an unset env variable as empty when checking…
kvinwang Nov 25, 2026
3b1831c
feat(dstack-util): reject env variables outside allowed_envs
kvinwang Nov 26, 2026
0e246f1
refactor(value-spec): parse NAME: spec entries in the crate
kvinwang Nov 25, 2026
2edb069
feat(vmm): reject malformed allowed_envs specs at deployment
kvinwang Nov 25, 2026
7ef065b
feat(vmm-cli): add --env-spec and keep specs when rewriting allowed_envs
kvinwang Nov 25, 2026
0ddb6fe
feat(vmm-ui): edit value specs and keep them on update
kvinwang Nov 25, 2026
74179a3
docs: mention deployment tooling for environment value specs
kvinwang Nov 25, 2026
32a2497
feat(dstack-util): add import-env
kvinwang Nov 26, 2026
8bd38b3
fix(value-spec): check entry names and report empty integer ranges
kvinwang Nov 26, 2026
e863f06
fix(dstack-util): keep .decrypted-env in sync on import-env
kvinwang Nov 26, 2026
9ee7412
feat(vmm): let vmm-cli and the web UI remove value specs
kvinwang Nov 26, 2026
4fd8e19
fix(dstack-util): leave unset env variables to the check before the a…
kvinwang Nov 26, 2026
8f0ee40
fix(vmm): keep the order of allowed_envs and check --env-spec arguments
kvinwang Nov 26, 2026
15aa4d5
fix(vmm): leave variables listed only for their spec unset
kvinwang Nov 26, 2026
1bf0ce7
fix(dstack-util): check env only on app start and cap spec entry names
kvinwang Nov 26, 2026
3819464
fix(dstack-util): reject mistyped validate-env arguments and hint at …
kvinwang Nov 26, 2026
7606192
refactor(vmm): drop --drop-env-spec now that update keeps allowed_envs
kvinwang Nov 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,14 @@ 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`, 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).

### Security

Expand All @@ -34,6 +42,12 @@ 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`. 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
Expand Down
41 changes: 38 additions & 3 deletions docs/security/cvm-boundaries.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand Down Expand Up @@ -126,11 +126,46 @@ 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
- Final result is stored as /dstack/.host-shared/.decrypted-env.json and passed to app-compose.service through `dstack-util exec-with-env`
- 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 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.

#### 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_]*`, at most 255 bytes, 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 |
|------|---------|
| `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 |
| `int(1..=65535)?` | the empty string, or integers from 1 to 65535 |

A range is `start..=end` or `start..<end`; a `<` after `start` excludes it, and either side may be omitted. Numbers must be canonical (no `+`, leading zeros, exponent or whitespace) and at most 64 bytes. Regexes use the Rust `regex` syntax. A trailing `?` makes any spec accept the empty string as well. A spec is at most 4096 bytes. In a regex, `\d` and `\w` also match non-ASCII digits and letters; write `[0-9]` and `[A-Za-z0-9_]` for ASCII only. A name listed more than once must match every spec given for it.

`dstack-util validate-env` applies specs to values an `init_script` takes from unmeasured sources such as `.user-config`. It checks `NAME: spec` arguments, plus the `allowed_envs` specs of an app compose file given with `--compose`, the same way the boot does. Values come from the command's environment, or from a JSON object of names to string values given with `--env-file`; names without a spec are not checked. The arguments and `allowed_envs` together are also the list of permitted names: any other variable in the environment or the `--env-file` is an error unless `--allow-unlisted` is given. A bare `NAME` argument permits a variable without constraining it, and must itself be a valid variable name, so a mistyped `:` is an error. Only take specs from measured input: the arguments in `init_script` or `/dstack/app-compose.json`.

```bash
PORT=$(jq -r .port /dstack/.host-shared/.user-config)
PORT=$PORT dstack-util validate-env --allow-unlisted 'PORT: int(1024..=65535)' || exit 1

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. 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
```

`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.

### .user-config
This is an optional application-specific configuration file that applications inside the CVM can access. dstack OS simply stores it at /dstack/.host-shared/.user-config without any measurement or additional processing, unless `requirements.launch_token_hash` is set in app-compose.json — in that case the guest reads the launch token from JSON path `dstack.launch_token` in this file and fails closed at boot, before key provisioning, unless its SHA-256 matches the pinned hash.

Expand Down
1 change: 1 addition & 0 deletions docs/vmm-cli-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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). Variables of `--env-file` that no `--env-spec` names are allowed without a spec
- `--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

Expand Down
25 changes: 25 additions & 0 deletions dstack/Cargo.lock

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

4 changes: 4 additions & 0 deletions dstack/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ members = [
"nvidia-attest-proxy",
"verifier",
"size-parser",
"value-spec",
"crates/dstack-cli-core",
"crates/dstack-cli",
"crates/dstack-volume",
Expand Down Expand Up @@ -130,6 +131,7 @@ serde-duration = { path = "serde-duration" }
dstack-mr = { path = "dstack-mr" }
dstack-verifier = { path = "verifier", default-features = false }
size-parser = { path = "size-parser" }
value-spec = { path = "value-spec" }
nvattest = { path = "nvattest" }
wavekv = "2.2"
vfio-ioctls = { git = "https://github.com/kvinwang/vfio.git", rev = "1b560c2", default-features = false }
Expand Down Expand Up @@ -301,6 +303,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"
Expand Down
1 change: 1 addition & 0 deletions dstack/dstack-util/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ cc-eventlog.workspace = true
safe-write.workspace = true
errify.workspace = true
base64.workspace = true
value-spec.workspace = true

[dev-dependencies]
rand.workspace = true
166 changes: 162 additions & 4 deletions dstack/dstack-util/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -106,18 +106,171 @@ enum Commands {
GpuInfo,
/// Exec a command with extra environment variables from a JSON object file
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)]
struct ValidateEnvArgs {
/// App compose file whose `allowed_envs` specs also apply
#[arg(long)]
compose: Option<PathBuf>,
/// JSON object mapping variable names to values, checked instead of the environment
#[arg(long)]
env_file: Option<PathBuf>,
/// 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", value_parser = env_spec)]
specs: Vec<String>,
}

#[derive(Parser)]
struct ExecWithEnvArgs {
/// JSON object mapping variable names to values
#[arg(long)]
env_file: PathBuf,
/// App compose file; variables must be in its `allowed_envs` and match the specs there
#[arg(long)]
compose: Option<PathBuf>,
/// Command to exec, with its arguments
#[arg(last = true, required = true)]
command: Vec<String>,
}

#[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<PathBuf>,
/// 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<PathBuf>,
/// App compose file whose `allowed_envs` permits and constrains the variables
/// [default: app-compose.json in the host-shared dir]
#[arg(long)]
compose: Option<PathBuf>,
/// Variables to import
#[arg(required_unless_present = "all")]
names: Vec<String>,
}

type Envs = std::collections::BTreeMap<String, String>;

#[derive(serde::Deserialize, Default)]
struct UserConfig {
#[serde(default)]
env: Envs,
}

fn load_envs(path: &Path) -> Result<Envs> {
utils::deserialize_json_file(path)
.with_context(|| format!("failed to load env from {}", path.display()))
}

fn load_allowed_envs(path: &Path) -> Result<Vec<String>> {
let compose: utils::AppCompose = utils::deserialize_json_file(path)
.with_context(|| format!("failed to load app compose from {}", path.display()))?;
Ok(compose.allowed_envs)
}

/// A bare name on the command line must be a variable name too, so that a mistyped
/// `:` is not taken as a name that no variable has.
fn env_spec(entry: &str) -> Result<String, value_spec::ParseError> {
let (name, _) = value_spec::split_named(entry)?;
value_spec::check_name(name)?;
Ok(entry.into())
}

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()
.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;
if let Some(compose) = &args.compose {
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);
Comment thread
kvinwang marked this conversation as resolved.
Resolved
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())?;
}
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, 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));
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::<UserConfig>(&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)?;
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)
.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)]
/// Hex encode data
struct HexCommand {
Expand Down Expand Up @@ -734,9 +887,12 @@ 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<String, String> =
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 = 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")?;
let err = std::process::Command::new(program)
.args(program_args)
Expand Down Expand Up @@ -1700,6 +1856,8 @@ async fn main() -> Result<()> {
gpu_info::cmd_gpu_info()?;
}
Commands::ExecWithEnv(args) => cmd_exec_with_env(args)?,
Commands::ValidateEnv(args) => cmd_validate_env(args)?,
Commands::ImportEnv(args) => cmd_import_env(args)?,
}

Ok(())
Expand Down
Loading
Loading