Skip to content
Merged
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- `vmm-cli compose --init-script` sets `init_script` in the app compose file.

### Security

- **Sysbox is updated to 0.7.2.** It fixes read-only bind mounts being made
Expand All @@ -17,6 +21,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Changed

- **`vmm-cli update --compose` takes an app compose file.** It sends the
`app-compose.json` written by `vmm-cli compose` unchanged instead of a Docker
Compose file patched into the stored one, and `--prelaunch-script` and
`--swap` are gone from `update`: run `compose` again to change them.
`update --env-file` no longer rewrites `allowed_envs` or `launch_token_hash`
and refuses variables the compose does not allow or an `APP_LAUNCH_TOKEN` it
does not pin; render them with `compose --env-file`, which now also writes
`launch_token_hash`, changing the compose hash when the env file sets
`APP_LAUNCH_TOKEN`. `update-env` and
`update-app-compose` are removed in favor of `update --env-file` and
`update --compose`.
`update --kms-encrypt-url` encrypts `--env-file` without replacing the VM's
KMS URLs, which `--kms-url` does.
- **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
25 changes: 5 additions & 20 deletions docs/vmm-cli-user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ First, create an application composition file that describes your application:
- `--name`: Friendly name for your application
- `--docker-compose`: Path to your Docker Compose file
- `--prelaunch-script`: Optional script to run before starting containers. It runs after dockerd, so containers restored by a Docker restart policy may already be running; do not put security gates here (see [security best practices](./security/security-best-practices.md#security-semantics-must-not-depend-on-pre_launch_script-running-first))
- `--init-script`: Optional Bash script to run before dockerd starts. Repeat it for up to 5 scripts, which run in order; several scripts set `manifest_version` to `"3"`, which guests before 0.6.0 reject. For a one-line script, Bash process substitution saves a file: `--init-script <(echo 'sysctl -w net.core.somaxconn=4096')`
- `--kms`: Enable Key Management Service for secrets
- `--gateway`: Enable dstack-gateway for external access
- `--local-key-provider`: Use local key provider
Expand Down Expand Up @@ -560,18 +561,6 @@ CLI accepts, whatever root epoch the response claims.

### Updating Running VMs

#### Update Environment Variables

```bash
./vmm-cli.py update-env <vm-id> --env-file ./new-secrets.env
```

#### Update Application Compose

```bash
./vmm-cli.py update-app-compose <vm-id> ./new-app-compose.json
```

#### Update User Configuration

```bash
Expand Down Expand Up @@ -600,9 +589,7 @@ Use the all-in-one `update` command to update multiple VM aspects in a single op

# Update application configuration
./vmm-cli.py update <vm-id> \
--compose ./new-docker-compose.yml \
--prelaunch-script ./setup.sh \
--swap 4G \
--compose ./new-app-compose.json \
--env-file ./new-secrets.env \
--user-config ./new-config.json

Expand All @@ -623,17 +610,15 @@ Use the all-in-one `update` command to update multiple VM aspects in a single op
--vcpu 8 \
--memory 16G \
--disk 200G \
--compose ./new-docker-compose.yml \
--prelaunch-script ./init.sh \
--swap 8G \
--compose ./new-app-compose.json \
--env-file ./new-secrets.env \
--port tcp:8080:80 \
--ppcie
```

**Available Options:**
- **Resource changes** (requires VM to be stopped): `--vcpu`, `--memory`, `--disk`, `--image`
- **Application updates**: `--compose` (docker-compose file), `--prelaunch-script`, `--swap`, `--env-file`, `--user-config`
- **Application updates**: `--compose` (an app-compose.json made by `compose`, sent unchanged), `--env-file`, `--user-config`. To change the Docker Compose file, scripts or swap, run `compose` again and pass its output. `--env-file` refuses variables missing from the compose's `allowed_envs` and an `APP_LAUNCH_TOKEN` that does not match its `launch_token_hash`; pass a compose made with the same `--env-file`
- **Networking** (mutually exclusive):
- `--port <mapping>` (can be used multiple times)
- `--no-ports` (remove all port mappings)
Expand All @@ -643,7 +628,7 @@ Use the all-in-one `update` command to update multiple VM aspects in a single op
- `--ppcie` (attach all available GPUs)
- `--no-gpus` (detach all GPUs)
- _No GPU flag: GPU configuration remains unchanged_
- **KMS**: `--kms-url` (for environment encryption)
- **KMS**: `--kms-url` replaces the VM's KMS URLs and also encrypts `--env-file`; `--kms-encrypt-url` only encrypts `--env-file` and leaves the KMS URLs as they are

**Notes:**
- Resource changes (vCPU, memory, disk, image) require the VM to be stopped
Expand Down
2 changes: 1 addition & 1 deletion dstack/gateway/docs/cluster-deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ BOOTNODE_URL=https://gateway-2.example.com:19702
EOF

# Update and restart
vmm-cli.py --url <vmm-url> update-env --env-file updated.env <vm-id>
vmm-cli.py --url <vmm-url> update <vm-id> --env-file updated.env --kms-encrypt-url <kms-url>
vmm-cli.py --url <vmm-url> stop <vm-id>
vmm-cli.py --url <vmm-url> start <vm-id>
```
Expand Down
147 changes: 143 additions & 4 deletions dstack/vmm/src/tests/test_vmm_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
import argparse
import base64
import contextlib
import hashlib
import importlib.util
import io
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import Mock, patch
Expand Down Expand Up @@ -76,6 +78,142 @@ def test_launch_ticket_is_sent_and_removed(self) -> None:
[params["launch_ticket"] for _, params in calls], ["t" * 32, ""]
)

def test_compose_is_sent_as_is_with_env(self) -> None:
"""Send the rendered compose unchanged, refusing envs it does not allow."""
cli = VMM_CLI.VmmCLI("http://127.0.0.1:8080")
cli.rpc_call = Mock(return_value={"found": True, "info": {"app_id": "app"}})
cli.encrypt_env_payload = Mock(return_value={"encrypted_env": "00"})
cli.image_supports_sealed_env = Mock(return_value=False)
compose = '{"allowed_envs": ["A"]}'

with (
patch.object(VMM_CLI, "parse_env_file", return_value={"A": "1"}),
contextlib.redirect_stdout(io.StringIO()),
):
cli.update_vm(
"vm", app_compose=compose, env_file="env", kms_urls=["https://kms"]
)
method, payload = cli.rpc_call.call_args.args
self.assertEqual(method, "UpgradeApp")
self.assertEqual(payload["compose_file"], compose)
self.assertEqual(payload["encrypted_env"], "00")
with self.assertRaisesRegex(Exception, "A not in allowed_envs"):
cli.update_vm("vm", env_file="env", kms_urls=["https://kms"])
cli.update_vm(
"vm",
app_compose='{"allowed_envs": ["A: int"]}',
env_file="env",
kms_urls=["https://kms"],
)

def test_env_only_update_keeps_compose_and_kms_urls(self) -> None:
"""Send neither a compose nor KMS URLs when only the env changes."""
cli = VMM_CLI.VmmCLI("http://127.0.0.1:8080")
info = {
"app_id": "app",
"configuration": {"compose_file": '{"allowed_envs": ["A"]}'},
}
cli.rpc_call = Mock(return_value={"found": True, "info": info})
cli.encrypt_env_payload = Mock(return_value={"encrypted_env": "00"})
cli.image_supports_sealed_env = Mock(return_value=False)

with (
patch.object(VMM_CLI, "parse_env_file", return_value={"A": "1"}),
contextlib.redirect_stdout(io.StringIO()),
):
cli.update_vm("vm", env_file="env", kms_encrypt_url="https://kms")

self.assertEqual(cli.encrypt_env_payload.call_args.args[2], "https://kms")
self.assertEqual(
cli.rpc_call.call_args.args,
("UpgradeApp", {"id": "vm", "encrypted_env": "00"}),
)

def test_launch_token_must_match_compose(self) -> None:
"""Refuse an APP_LAUNCH_TOKEN the compose does not pin."""
cli = VMM_CLI.VmmCLI("http://127.0.0.1:8080")
cli.rpc_call = Mock(return_value={"found": True, "info": {"app_id": "app"}})
cli.encrypt_env_payload = Mock(return_value={})
cli.image_supports_sealed_env = Mock(return_value=False)
token_hash = hashlib.sha256(b"token").hexdigest()

def update(token: str) -> None:
compose = {
"allowed_envs": ["APP_LAUNCH_TOKEN"],
"launch_token_hash": token_hash,
}
with patch.object(
VMM_CLI, "parse_env_file", return_value={"APP_LAUNCH_TOKEN": token}
):
cli.update_vm(
"vm",
app_compose=json.dumps(compose),
env_file="env",
kms_urls=["https://kms"],
)

with contextlib.redirect_stdout(io.StringIO()):
update("token")
with self.assertRaisesRegex(Exception, "launch_token_hash"):
update("other")


class ComposeTests(unittest.TestCase):
"""Verify the app compose written by `compose`."""

def compose(self, *scripts: str, env: str = "") -> dict:
"""Run `compose` with these init scripts and env file, return the result."""
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
(tmp / "docker-compose.yaml").write_text("services: {}")
(tmp / ".env").write_text(env)
paths = []
for i, script in enumerate(scripts):
paths.append(tmp / f"init{i}.sh")
paths[-1].write_text(script)
args = argparse.Namespace(
name="app",
docker_compose=tmp / "docker-compose.yaml",
env_file=tmp / ".env",
kms=bool(env),
gateway=False,
local_key_provider=False,
key_provider_id=None,
key_provider=None,
public_logs=False,
public_sysinfo=False,
no_instance_id=False,
secure_time=False,
no_storage_discard=False,
prelaunch_script=None,
init_script=paths,
swap=None,
event_log_version=None,
output=tmp / "app-compose.json",
)
with contextlib.redirect_stdout(io.StringIO()):
VMM_CLI.VmmCLI("http://127.0.0.1:8080").create_app_compose(args)
return json.loads(args.output.read_text())

def test_init_script_shape_follows_manifest_version(self) -> None:
"""Write one script as a v2 string and several as a v3 array."""
self.assertNotIn("init_script", self.compose())
one = self.compose("echo a")
self.assertEqual((one["manifest_version"], one["init_script"]), (2, "echo a"))
two = self.compose("echo a", "echo b")
self.assertEqual(
(two["manifest_version"], two["init_script"]), ("3", ["echo a", "echo b"])
)

def test_launch_token_hash_is_written_last(self) -> None:
"""Pin APP_LAUNCH_TOKEN after every other field, where jq would add it."""
compose = self.compose("echo a", env="APP_LAUNCH_TOKEN=token\nA=1\n")
self.assertEqual(compose["allowed_envs"], ["APP_LAUNCH_TOKEN", "A"])
self.assertEqual(
list(compose.items())[-1],
("launch_token_hash", hashlib.sha256(b"token").hexdigest()),
)


class LaunchTicketTests(unittest.TestCase):
"""Pin the hash the contracts allow; the KMS computes the same."""
Expand Down Expand Up @@ -361,7 +499,9 @@ def rpc(method, params=None):
"app_id": self.app_id,
"configuration": {
"image": "new",
"compose_file": '{"kms_enabled":true}',
"compose_file": json.dumps(
{"allowed_envs": list(self.envs)}
),
},
},
}
Expand All @@ -388,9 +528,9 @@ def rpc(method, params=None):
self.assertNotIn("sealed_env", payload)
self.cli.client.request.assert_not_called()

def test_create_update_and_update_env_send_only_the_negotiated_field(self):
def test_create_and_update_send_only_the_negotiated_field(self):
"""Use the selected ciphertext field consistently across CLI commands."""
compose = json.dumps({"kms_enabled": True})
compose = json.dumps({"kms_enabled": True, "allowed_envs": list(self.envs)})
args = argparse.Namespace(
compose="compose.json",
env_file="env",
Expand Down Expand Up @@ -449,7 +589,6 @@ def rpc(method, params=None):
lambda: self.cli.update_vm(
"vm", env_file="env", kms_urls=args.kms_url
),
lambda: self.cli.update_vm_env("vm", self.envs, args.kms_url),
]:
with self.subTest(capability=capability, action=action):
self.cli.rpc_call.reset_mock()
Expand Down
Loading
Loading