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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,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).

### Changed
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 @@ -237,6 +237,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

Expand Down
1 change: 1 addition & 0 deletions dstack/Cargo.lock

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

10 changes: 2 additions & 8 deletions dstack/dstack-util/src/parse_env_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,8 @@ pub type AllowedEnvs = BTreeMap<String, Vec<ValueSpec>>;
pub fn parse_allowed_envs(entries: &[String]) -> Result<AllowedEnvs> {
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)
Expand Down
28 changes: 28 additions & 0 deletions dstack/value-spec/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ValueSpec>), 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;
Expand Down Expand Up @@ -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));
Expand Down
1 change: 1 addition & 0 deletions dstack/vmm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions dstack/vmm/src/main_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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::<value_spec::ValueSpec>()
.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.
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 })
}
Expand Down Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions dstack/vmm/src/tests/test_vmm_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,25 @@ def test_launch_ticket_is_sent_and_removed(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:
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:
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."""

Expand Down
31 changes: 27 additions & 4 deletions dstack/vmm/src/vmm-cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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,
}
Expand Down Expand Up @@ -1248,7 +1248,9 @@ def update_vm_env(
except json.JSONDecodeError:
app_compose = {}
compose_changed = False
allowed_envs = list(envs.keys())
allowed_envs = merge_allowed_envs(
app_compose.get("allowed_envs") or [], envs
)
if app_compose.get("allowed_envs") != allowed_envs:
app_compose["allowed_envs"] = allowed_envs
compose_changed = True
Expand Down Expand Up @@ -1426,7 +1428,9 @@ def update_vm(
except json.JSONDecodeError:
app_compose = {}
compose_changed = False
allowed_envs = list(envs.keys())
allowed_envs = merge_allowed_envs(
app_compose.get("allowed_envs") or [], envs
)
if app_compose.get("allowed_envs") != allowed_envs:
app_compose["allowed_envs"] = allowed_envs
compose_changed = True
Expand Down Expand Up @@ -1716,6 +1720,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.

Expand Down Expand Up @@ -2146,6 +2161,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"
)
Expand Down
34 changes: 11 additions & 23 deletions dstack/vmm/ui/src/components/EncryptedEnvEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[];
Expand All @@ -13,6 +13,7 @@ type ComponentInstance = {
textContent: string;
};
parseTextContent(): void;
replaceFromText(content: string): void;
};

const EncryptedEnvEditorComponent = {
Expand Down Expand Up @@ -58,6 +59,7 @@ const EncryptedEnvEditorComponent = {
<div v-for="(env, index) in envVars" :key="index" class="encrypted-env-row">
<input type="text" v-model="env.key" placeholder="Variable name" required>
<input type="password" v-model="env.value" placeholder="Value" required>
<input type="text" v-model="env.spec" placeholder="Value spec (optional), e.g. int(1..=65535)">
<button type="button" class="action-btn danger" @click="removeEnv(index)">
Remove
</button>
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down
9 changes: 5 additions & 4 deletions dstack/vmm/ui/src/composables/useVmManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -125,6 +125,7 @@ type VmListItem = {
type EncryptedEnvEntry = {
key: string;
value: string;
spec?: string;
};

type PortFormEntry = {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading