diff --git a/CHANGELOG.md b/CHANGELOG.md index c30ac68fe6..5f87e8e785 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/vmm-cli-user-guide.md b/docs/vmm-cli-user-guide.md index 332d2cc1ae..7b347e58cb 100644 --- a/docs/vmm-cli-user-guide.md +++ b/docs/vmm-cli-user-guide.md @@ -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 diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index e3fb8a84a1..ba2db1d165 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/dstack-util/src/parse_env_file.rs b/dstack/dstack-util/src/parse_env_file.rs index b0762326e6..fc7e4e21c3 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 ca62b3c099..2d6850db90 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)); diff --git a/dstack/vmm/Cargo.toml b/dstack/vmm/Cargo.toml index dd4f91d546..a49e01c91a 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 a35dfc6144..027b3a1023 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 diff --git a/dstack/vmm/src/tests/test_vmm_cli.py b/dstack/vmm/src/tests/test_vmm_cli.py index c437ca7f47..2eed1c4619 100644 --- a/dstack/vmm/src/tests/test_vmm_cli.py +++ b/dstack/vmm/src/tests/test_vmm_cli.py @@ -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.""" diff --git a/dstack/vmm/src/vmm-cli.py b/dstack/vmm/src/vmm-cli.py index 83bc00c742..f526675cbd 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, } @@ -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 @@ -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 @@ -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. @@ -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" ) diff --git a/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts b/dstack/vmm/ui/src/components/EncryptedEnvEditor.ts index 1a081bfdbc..772492fdbc 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 89d598b542..1608fcb80a 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 c4159b8f0c..eae1fe919b 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 3f4f51be24..99a7199a93 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 bc3af9cf04..d5c37a0f1b 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({