diff --git a/.agent/CODING_TASTE.md b/.agent/CODING_TASTE.md new file mode 100644 index 0000000000..f29a14bcff --- /dev/null +++ b/.agent/CODING_TASTE.md @@ -0,0 +1,310 @@ +# Coding Taste Guide + +Conventions and design taste for contributing code and PRs to dstack. The first half is +distilled from the project's code-review history and security-advisory responses — PR +numbers reference the real discussions where each rule was set. The second half — project +structure, design patterns, readability — is distilled from the codebase itself, with file +references pointing at canonical examples. When in doubt, read the cited example. + +The short version: dstack review optimizes for **small maintainable surface area, backward +compatibility, security reasoned from the threat model, and claims backed by evidence**. +Speculative complexity gets rejected; pragmatic imperfection is accepted when the risk is +quantified and bounded. + +## API and interface design + +- **Use builder patterns for argument lists that will grow.** A function taking positional + bools (`get_tls_key(None, None, true, true, true)`) breaks every caller when a parameter + is added and is unreadable at the call site. Use a config struct with `bon::Builder` + and defaults, so adding a field is non-breaking (#161 has the full rationale). +- **Prefer generics over dynamic typing.** `send_rpc_request` + instead of passing `serde_json::Value` around (#161). +- **Use `anyhow::Error`, not `Box`** (#161). +- **Every new API endpoint is a liability** — another path to audit, keep in sync with policy + changes, and reason about in security reviews. Converge on one model instead of forking + parallel paths (a separate `GetAppKeyAmd` was rejected on these grounds, #630). When an + existing API is the wrong shape, add a purpose-built one rather than overloading a return + value (`is_app_allowed` returning policy → add `auth_api.get_app_policy` instead, #538). +- **Names must say what the thing does.** `GetQuote` for an app key → `AttestAppKey` + (#360). An RPC named `ComposeHash` that returns an `app_id` is wrong (#181). +- **Avoid enums in protobuf APIs** that surface as JSON — proto has no way to express + snake_case serde renaming, so use strings (#241). +- **SDK parity is mandatory.** A new guest-agent API means updating the Rust, Python, Go, + and JS SDKs. A `Sign()` needs a `Verify()` counterpart (#360). Keep names and semantics + consistent across language implementations — renaming the `dstack-sdk` crate was rejected + for exactly this reason (#161, #272). + +## Backward compatibility + +This is close to absolute. Assume any observable behavior is load-bearing. + +- **Never change key derivation, hashes, or measurements** without a migration story. + Cryptographic-hygiene improvements (domain-separated KDF contexts, salt changes) have + been rejected because they'd silently change all derived keys in existing deployments + (see the responses in #605, #552). Compatibility special cases are acceptable — all-zero + `mr_config_id` means "unset" to avoid breaking old quotes (#559). +- **Pin encodings that feed key derivation.** When a derived secret depended on a library's + DER serialization, the fix was a fixed, dstack-defined layout plus a regression test + proving old and new outputs are identical (#553 → #603). +- **Wire formats and URL schemes are frozen.** `*-8080-h2` was rejected as breaking; + keep deprecated aliases (`TappdClient`) alongside new clients (#292, #306). +- **New endpoints ship behind a config gate**, so operators opt in and existing deployments + are unaffected (metrics endpoint in #657). + +## Security reasoning + +Argue from dstack's threat model, not from generic best practices. + +- **Attestation is the trust boundary — not TLS, not the network, not URLs.** Endpoints + (KMS URL, PCCS, registry) are untrusted transport; the remote party's identity is verified + cryptographically (RA-TLS quote verification, Intel signatures, image digests). Proposals + to "measure the URL" or pin transport add no security and reduce flexibility (#615, #616). +- **Runtime config measured into RTMRs beats compile-time cargo features.** Features are + additive and invisible at runtime; a measured config flag is auditable by any verifier. + This is the project's standard response to `#[cfg(feature = "dev-mode")]`-style gating + proposals (#608, #609). +- **The CVM is single-tenant.** All containers in a CVM share one trust domain; file + permissions between them are not a security boundary. Don't add intra-CVM isolation + machinery (#606, #617). +- **Fail closed on unknown variants.** A Go `switch` on a string type without a `default` + silently passes validation for new types — Rust exhaustive `match` is the model; in other + languages, add the explicit error case (#512). +- **Validate early with explicit checks.** Constraints enforced implicitly deep in the stack + (a `try_into::<[u8; 20]>()`) should also be checked explicitly at the entry point with a + clear error (#554 → #604). +- **Cheap, bounded hardening is always welcome** even when no realistic attack exists: + 0600 file permissions, a 16 KiB cap on decompressed cert extensions, `MAX_LEN` bounds on + length-prefixed decoding, path normalization before deletion (#557, #566, #567, #558). + The line: hardening with no downside → yes; complexity for a hypothetical attacker who + already breached the trust boundary → no. +- **Attestation payloads need content-type discipline.** Prefix `report_data` so external + verifiers can parse it unambiguously (#360, the `dip1:` proposal in #330). Don't spam + runtime events — "emitting many events in the application is a disaster for the verifier; + in most scenarios, you only need report_data" (#273). + +## Performance and pragmatism + +- **Quantify before adding machinery.** A bounded channel + semaphore was rejected because + the computed worst case was ~80 KB of memory and tens of tasks: "not adding speculative + complexity now… easy to add later without API changes" (#361 replies). If you propose a + limit, pool, or backpressure mechanism, bring the numbers that make it necessary. +- **Never block the hot path.** No blocking commands or syscalls under a lock (`wg show` + under `ProxyState` — #740); no `reqwest::blocking` inside async contexts spawning nested + runtimes (#750); reuse clients/resolvers instead of constructing per-connection (#741). + Snapshot behind `Arc` instead of cloning big maps while holding a lock (#740). +- **Caches are bounded and TTL'd** (moka with size limits, TTL-aware DNS caching; #741, #750). +- **Know your data structures.** Don't linear-scan something that's already a map (#33). +- **Dependencies: judge by maturity and removability, not fashion.** An archived-but-mature + crate is fine if dropping it later is a one-line change (#207 on jemallocator). + +## Code organization + +- **Workspace-managed dependencies.** Declare versions in `dstack/Cargo.toml`, reference + with `foo.workspace = true` (#161, #360). +- **One source of truth.** Shared logic used by two components lives in one crate + (`dstack-mr::sev` used by both KMS and verifier). Duplicated blocks get extracted — + contract logic into `_registerApp` (#182), repeated fetch/parse into `http_get`/`http_post` + helpers that unify error context in one place (#525), shared lookup between `list_vms` + and `get_vm` (#33). Duplicated magic numbers become constants (#541). +- **Generic mechanics go in small reusable crates; domain logic stays in the service.** + `TtlCell` owns caching/refresh mechanics; the gateway only defines how to fetch + WireGuard handshakes (#740). +- **Delete, don't accumulate.** Remove functions that lost their purpose (#538), stray + `println!` debugging (#525), obsolete Dockerfiles superseded by better infrastructure + (#311). Avoid `unsafe` when a safe construction exists (#360). +- **Config over hardcoding.** Defaults belong in the embedded base config layer + (`load_config` figment merge), not scattered in code (#646). Operator-facing values — + DNS servers, TTLs, ports — are configurable, never hardcoded (#409, #436). + +## Errors and logging + +- **Lowercase log and error messages** — `bail!("failed to connect to server")`, never + capitalized (`.cursorrules`, enforced). +- **Errors speak the caller's language.** If the caller passed raw bytes, the size-limit + error talks about bytes — not the hex-encoded internal representation (#47). +- **Include actionable context, bounded.** URL, status, and response body truncated to + ~512 bytes so an HTML error page can't blow up the logs (#525). +- **Don't skip silently.** If code ignores malformed input to stay lenient, log a warning — + silent skips hide corruption (#541). + +## Scope and diffs + +- **One concern per PR.** Unrelated changes get called out immediately ("It shouldn't be + in this PR", #301). +- **Never remove existing behavior without saying why** ("Why removing the entire resizing + logic?", #251). +- **`cargo fmt` and clippy-clean before pushing**; preserve surrounding blank-line structure + rather than reflowing untouched code (#251). + +## Commits and PR descriptions + +Commits are **subject-only conventional commits**, one logical change each: +`fix(gateway): reuse app address DNS resolver`, `refactor(snp): split ovmf parsing helpers`, +`test: add SEV-SNP verifier fixture`. Big features arrive as a stack of small, +independently-readable commits (see the #703 follow-up series). Lowercase after the colon. + +PR descriptions follow **Problem → Fix**, and the problem section names the root cause, +not just the symptom: + +- Lead with what's broken and why, with the failing behavior shown concretely (error + output, wrong digest, stale tag) — see #722, #723, #654. +- Explain the mechanism: #688 traces a package drift to deb822 sources on trixie bypassing + the snapshot pin, then fixes the cause instead of bumping pinned versions — "the version + bumps only paper over a bug". +- **State how you verified it, specifically.** Not "tested locally" but "verified inside + both `rust:1.92.0` (trixie) and `debian:bookworm`: `apt-get update` only contacts + `snapshot.debian.org`" (#688), or a full end-to-end deployment table with real endpoints + and observed client IPs (#361). For infra/measurement changes, capture fixtures from real + CVMs (#678). +- Use evidence when making performance or behavioral claims: measurements, strace output, + before/after tables (#410 is the canonical example — IPI counts, futex timing, per-config + pull times). +- When choosing between designs, show the alternatives and the trade-offs briefly, then + commit to one (#353's stateful-RPC vs URL-flag comparison). + +## Responding to review + +- **When you fix it:** reply "Addressed in ``" plus one sentence on what changed — + precise enough that the reviewer needn't re-read the diff (#740, #678). +- **When you disagree:** push back with numbered, quantified reasons grounded in the threat + model or measured behavior, and end with a decision: "Going to leave this as-is" (#361), + "we do not think the security benefit justifies that operational cost" (#552). Never + silently ignore a comment. +- **When the reviewer is right:** say so plainly — "Good catch — updated the doc to spell + out the difference" (#678) — and fix it in the same round. + +--- + +# How the code itself is written + +## Tooling constraints (non-negotiable) + +- **CI rejects `.unwrap()` and `.expect()` in non-test code**: clippy runs with + `-D clippy::unwrap_used -D clippy::expect_used` (`.github/workflows/rust.yml`). The house + replacement for "this cannot fail" is the `or-panic` crate with a terse lowercase reason: + `self.state.lock().or_panic("mutex poisoned")`. Tests are exempt and unwrap freely. +- **Stock `cargo fmt`** — there is no rustfmt.toml, clippy.toml, or `[workspace.lints]`. + Toolchain is pinned in `rust-toolchain.toml`. +- **Every source file starts with a 3-line SPDX header** (REUSE-compliant). +- `.cursorrules`: log and error messages start lowercase. The old code is ~50/50 on this; + new code must follow the rule, but don't mass-fix existing strings in unrelated diffs. + +## Project structure + +- **One workspace, ~54 crates, every dependency version declared once** in root + `[workspace.dependencies]` (grouped under comment banners: `# Core dependencies`, + `# Cryptography/Security`, …) and consumed via `foo.workspace = true`. Internal RPC + crates live at `/rpc` but are aliased to `dstack--rpc` package names. +- **Extract a crate when a utility is reusable across binaries, independently publishable, + or has a distinct dependency footprint — and keep it tiny.** `serde-duration` is 54 + lines; `cached-cell` is one `TtlCell` (263 lines); `load_config` is one function. + Otherwise stay a module: `ra-tls` keeps cert/kdf/oids as sibling modules. The `dstack-` + name prefix is reserved for published or product-facing crates. +- **All four services share one bootstrap skeleton**: clap `Args { config: Option }` + → `load_config` figment layering (Rocket defaults → embedded default TOML via + `include_str!` → `/etc//` → cwd → `--config` file) → tracing `EnvFilter` defaulting + to `info` → `rocket::custom(figment)` mounting `ra_rpc::prpc_routes!` → `anyhow::Result` + main. Each defines `app_version()` from `CARGO_PKG_VERSION` + `git_version!` and attaches + an `X-App-Version` response header. Follow this skeleton exactly when adding a service. +- **Module layout**: the core RPC surface lives in `main_service.rs` (or `rpc_service.rs` + in guest-agent). When a module grows subordinate concerns, promote it to `foo.rs` + a + `foo/` directory of submodules (`dstack/gateway/src/proxy.rs` + `proxy/{sni,tls_terminate,...}`). + Core files routinely run 800–1500+ lines before splitting — don't over-fragment into + many small files. +- **Config conventions**: each service embeds its default TOML (`include_str!`), extracts + the app config from the `[core]` section, and adding an option means: add a field with + `#[serde(default)]` (or `default = "default_true"` free fns), then document it with a + comment in the embedded TOML. Variant config uses `#[serde(tag = "type")]` enums. + +## Design patterns + +- **Shared state is a `Clone` newtype over `Arc` with `Deref`**: `KmsState { + inner: Arc }`, `Proxy { _inner: Arc }`. Immutable-after-boot + state needs no lock; mutable parts sit behind a std `Mutex` (not tokio, not parking_lot) + accessed through a `fn lock(&self)` helper that `or_panic`s. Critical sections are + short and block-scoped — snapshot what you need, drop the guard, then do the work. +- **RPC handler pattern**: a per-request `RpcHandler` struct holds a clone of the state + plus request auth context (`attestation`, `remote_app_id`). It implements the generated + `*Rpc` trait (methods take `self` by value, return `anyhow::Result`) plus + `RpcCall::construct`. Method bodies start with `ensure_*` guard calls; the ra-rpc + layer maps any `Err` to HTTP 400 with the `{err:#}` context chain — handlers never build + HTTP responses. Multiple handlers over one state model multiple trust surfaces + (internal/external/admin/guest-api). +- **Builder-config-then-convert**: structs with several optional fields get + `#[derive(bon::Builder)]` with `#[builder(default = ...)]` field defaults, and a + conversion to the live object (`RaClientConfig::builder()...build().into_client()`). + Constructors: `new` for the common case, named alternates (`from_parts`, `load`, + `new_mtls`) for the rest. +- **Static dispatch over trait objects**: closed sets of implementations are enums — + hand-rolled (`CertRequestClient::{Local, Kms}`, `KeyProvider::{None,Local,Tpm,Kms}`) or + via `enum_dispatch` (`Dns01Client`). `dyn` is reserved for user-supplied callbacks + (`Box`). Traits define a minimal required core and layer + convenience as default methods (`CertExt`, `Csr`). +- **Wire format ≠ public type**: on-wire layouts get their own mirror structs with a + `version` field and explicit `From` conversions (`CborTdxOsImageMeasurement`). Formats + that must evolve are versioned enums (`VersionedAttestation::{V0,V1}`) with sniffing + decoders and upcast methods. Anything decoded from untrusted input carries an explicit + size bound (`VecOf`, `MAX_ATTESTATION_BYTES`). +- **Serde house rules**: byte fields are hex via `use serde_human_bytes as hex_bytes;` + + `#[serde(with = "hex_bytes")]`; large blobs are `serde_human_bytes::base64`. Renames keep + `#[serde(alias = "old_name")]`. New fields use `#[serde(default, + skip_serializing_if = ...)]` so legacy configs serialize byte-identically. Enums are + strings with `rename_all = "snake_case"`. +- **Feature flags gate capabilities, not variants**: `quote` threads through the + attestation stack to separate quote *generation* (needs TDX device) from verification; + `serde`/`std` are optional on leaf type crates (`no_std_check` compile-guards the SDK + types). Defaults are what the main binaries need. + +## Readability and idioms + +- **Import for readability, not minimum path length.** Import specific types and + frequently repeated operations when their short names remain unambiguous + (`TcpListener::bind`, `timeout`, `Command::new`). Keep qualifiers that carry useful + semantic context (`serde_json::from_slice`, `tokio::spawn`, `anyhow::bail!`). Follow + the surrounding module when either form is equally clear. +- **Errors**: `anyhow` everywhere in services — `thiserror` only in library crates whose + callers match on error variants. `bail!` inside an `if` is the guard idiom; **`ensure!` + is never used in this codebase** (0 occurrences) and reads as foreign. `let ... else + { bail!("...") }` is the standard Option guard. `.context("static string")` by default; + `.with_context(|| format!(...))` only when interpolating runtime values. Non-fatal + errors are logged, not propagated: `if let Err(err) = ... { warn!("...: {err:?}") }`. + The error binding is named `err`, logged as `{err:?}` internally or `{err:#}` when + surfaced to users. Use `fs_err as fs` instead of `std::fs`. +- **Naming**: validation guards are `ensure_*` returning `Result` and bailing inside + (`ensure_attested`, `ensure_admin`, `ensure_app_boot_allowed`); conditional actions take + `_if_needed`/`_if_exists` suffixes (`renew_cert_if_needed`); the common verb prefixes + are `get_`, `verify_`, `parse_`, `build_`, `derive_`. Descriptive names, minimal + abbreviation. +- **Functions are 20–40 lines, guard-clause style, shallow nesting.** When a wrapper needs + cleanup or retry around a `?`-heavy core, split into `foo` + `foo_inner` (`renew_inner`, + `handle_prpc_impl`). Iterator chains for pure transforms; plain `for` loops when the body + awaits or side-effects; `match` over if-let chains at 3+ arms. +- **Comments are earned.** They explain threat models, compat rationale, and protocol + steps — not mechanics: the 20-line doc on `platform_instance_binding()` explaining + VM-clone identity attacks (`dstack-util/src/system_setup.rs`), numbered step comments in + ACME flows (`certbot/src/acme_client.rs`). Field-level doc comments on config/wire + structs explain semantics and compat implications (`dstack-types/src/lib.rs`). TODO is + rare (4 in the tree); never leave commented-out code. +- **Formatting details**: inline format args for simple identifiers (`bail!("invalid app + id: {app_id}")`), positional `{}` only for expressions. Derives in the order `Debug, + Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize`. `pub(crate)` for + intra-crate visibility (258 uses; `pub(super)` nearly never). Pragmatic `.clone()` of + `Arc`s/`String`s is normal — don't contort code to avoid a clone off the hot path. +- **`unsafe` is FFI-only** (~15 sites: ioctl/flock/daemon/fd-borrowing). Business logic + never needs it; if you think it does, redesign (see #360: "avoid unnecessary unsafe"). +- **Docs discipline scales with audience**: `ra-tls` enforces `#![deny(missing_docs)]`; + published crates get READMEs and doctests; internal crates get module-level `//!` docs + stating the responsibility split (see `cached-cell`). + +## Testing + +- **Inline `#[cfg(test)] mod tests` is the default**; `tests/` directories only when + fixtures or integration binaries are involved. Plain `#[test]` preferred; `#[tokio::test]` + when async is unavoidable. +- **Golden vectors over mocks**: real captured binary fixtures embedded with + `include_bytes!("../samples/...")`, asserted against inline hex literals or `insta` + snapshots (`dstack/cc-eventlog`, `dstack/dstack-attest/tests/`). Fixture provenance gets its own + README (`sev_snp_fixture.README.md`). When changing an encoding, add a regression test + proving old and new outputs match (#603). +- **Test names are snake_case behavior statements**: `enforces_ttl`, + `returns_empty_before_first_set`, `http_transport_honors_requested_method`. diff --git a/.agent/GPU_TEE_DEPLOYMENT.md b/.agent/GPU_TEE_DEPLOYMENT.md new file mode 100644 index 0000000000..ff664eaea6 --- /dev/null +++ b/.agent/GPU_TEE_DEPLOYMENT.md @@ -0,0 +1,235 @@ +# GPU TEE Deployment Guide + +Learnings from deploying GPU workloads to Phala Cloud TEE infrastructure. + +## Instance Types + +Query available instance types: +```bash +curl -s "https://cloud-api.phala.network/api/v1/instance-types" | jq +``` + +### CPU-only (Intel TDX) +- `tdx.small` through `tdx.8xlarge` + +### GPU (H200 + TDX) +- `h200.small` — Single H200 GPU, suitable for inference +- `h200.16xlarge` — Multi-GPU for larger workloads +- `h200.8x.large` — High-memory configuration + +## Deployment Commands + +### GPU Deployment +```bash +phala deploy -n my-app -c docker-compose.yaml \ + --instance-type h200.small \ + --region US-EAST-1 \ + --image dstack-nvidia-dev-0.5.4.1 +``` + +Key flags: +- `--instance-type h200.small` — Required for GPU access +- `--image dstack-nvidia-dev-0.5.4.1` — NVIDIA development image with GPU drivers +- `--region US-EAST-1` — Region with GPU nodes (gpu-use2) + +### Debugging +```bash +# Check CVM status +phala cvms list + +# View serial logs (boot + container output) +phala cvms serial-logs --tail 100 + +# Delete CVM +phala cvms delete --force +``` + +## Docker Compose GPU Configuration + +GPU devices must be explicitly reserved in docker-compose.yaml: + +```yaml +services: + my-gpu-app: + image: my-image + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] +``` + +Without the `deploy.resources.reservations.devices` section, the container will fail with: +``` +libcuda.so.1: cannot open shared object file: No such file or directory +``` + +## vLLM Example + +Working docker-compose.yaml for vLLM inference: + +```yaml +services: + vllm: + image: vllm/vllm-openai:latest + volumes: + - /var/run/dstack.sock:/var/run/dstack.sock + environment: + - NVIDIA_VISIBLE_DEVICES=all + - HF_TOKEN=${HF_TOKEN:-} + ports: + - "8000:8000" + command: > + --model Qwen/Qwen2.5-1.5B-Instruct + --host 0.0.0.0 + --port 8000 + --max-model-len 4096 + --gpu-memory-utilization 0.8 + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] +``` + +## Endpoint URLs + +After deployment, the app is accessible at: +``` +https://-.dstack-pha-.phala.network +``` + +Example for vLLM on port 8000: +```bash +# List models +curl https://-8000.dstack-pha-use2.phala.network/v1/models + +# Chat completion +curl -X POST https://-8000.dstack-pha-use2.phala.network/v1/chat/completions \ + -H "Content-Type: application/json" \ + -d '{"model": "Qwen/Qwen2.5-1.5B-Instruct", "messages": [{"role": "user", "content": "Hello"}]}' +``` + +## vllm-proxy (Response Signing) + +vllm-proxy provides response signing and attestation for vLLM inference. It sits between clients and vLLM, signing responses with TEE-derived keys. + +### Configuration + +**IMPORTANT**: The authentication environment variable is `TOKEN`, not `AUTH_TOKEN`. + +```yaml +services: + vllm: + image: vllm/vllm-openai:latest + environment: + - NVIDIA_VISIBLE_DEVICES=all + command: > + --model Qwen/Qwen2.5-1.5B-Instruct + --host 0.0.0.0 + --port 8000 + --max-model-len 4096 + --gpu-memory-utilization 0.8 + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: all + capabilities: [gpu] + + proxy: + image: phalanetwork/vllm-proxy:v0.2.18 + volumes: + - /var/run/dstack.sock:/var/run/dstack.sock # Required for TEE key derivation + environment: + - VLLM_BASE_URL=http://vllm:8000 + - MODEL_NAME=Qwen/Qwen2.5-1.5B-Instruct + - TOKEN=your-secret-token # NOT AUTH_TOKEN + ports: + - "8000:8000" + depends_on: + - vllm +``` + +### API Endpoints + +```bash +# List models (no auth required) +curl https:///v1/models + +# Chat completion (requires auth) +curl -X POST https:///v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your-secret-token" \ + -d '{"model": "Qwen/Qwen2.5-1.5B-Instruct", "messages": [{"role": "user", "content": "Hello"}]}' + +# Get response signature +curl https:///v1/signature/ \ + -H "Authorization: Bearer your-secret-token" + +# Attestation report +curl https:///v1/attestation/report \ + -H "Authorization: Bearer your-secret-token" +``` + +### Tested Configuration + +- Image: `phalanetwork/vllm-proxy:v0.2.18` +- Instance: `h200.small` +- Region: `US-EAST-1` +- Model: `Qwen/Qwen2.5-1.5B-Instruct` + +### vllm-proxy Issues + +**"Invalid token" error**: +- Check that you're using `TOKEN` environment variable, not `AUTH_TOKEN` +- Verify the token value matches your request header + +**"All connection attempts failed" from proxy**: +- vLLM is still loading the model (takes 1-2 minutes after container starts) +- Wait for vLLM to show "Uvicorn running on" in serial logs + +**NVML error on attestation**: +- GPU confidential computing attestation may not be fully available +- This doesn't affect inference or response signing + +## Common Issues + +### "No available resources match your requirements" +- GPU nodes are limited. Wait for other CVMs to finish or try a different region. +- Ensure you're using the correct instance type (`h200.small`). + +### Container crashes with GPU errors +- Add `deploy.resources.reservations.devices` section to docker-compose.yaml. +- Verify using NVIDIA development image (`dstack-nvidia-dev-*`). + +### Image pull takes too long +- Large images (5GB+ for vLLM) take 3-5 minutes to download and extract. +- Check serial logs for progress. + +## Testing Workflow + +1. Deploy: `phala deploy -n test -c docker-compose.yaml --instance-type h200.small --region US-EAST-1 --image dstack-nvidia-dev-0.5.4.1` +2. Wait for status: `phala cvms list` (wait for "running") +3. Check logs: `phala cvms serial-logs --tail 100` +4. Test API: `curl https://-.dstack-pha-use2.phala.network/...` +5. Cleanup: `phala cvms delete --force` + +## GPU Wrapper Script + +For repeated GPU deployments, use a wrapper script: + +```bash +#!/bin/bash +# phala-gpu.sh +source "$(dirname "$0")/.env" +export PHALA_CLOUD_API_KEY=$PHALA_CLOUD_API_GPU +phala "$@" +``` + +This allows maintaining separate API keys for CPU and GPU workspaces. diff --git a/.agent/WRITING_GUIDE.md b/.agent/WRITING_GUIDE.md new file mode 100644 index 0000000000..aaf28fef03 --- /dev/null +++ b/.agent/WRITING_GUIDE.md @@ -0,0 +1,137 @@ +# Documentation Writing Guide + +Guidelines for writing dstack documentation, README, and marketing content. + +## Writing Style + +- **Don't over-explain** why a framework is needed — assert the solution, hint at alternatives being insufficient +- **Avoid analogies as taglines** (e.g., "X for Y") — if it's a new category, don't frame it as a better version of something else +- **Problem → Solution flow** without explicit labels like "The problem:" or "The solution:" +- **Demonstrate features through actions**, not parenthetical annotations + - Bad: "Generates quotes (enabling *workload identity*)" + - Good: "Generates TDX attestation quotes so users can verify exactly what's running" + +## Procedural Documentation (Guides & Tutorials) + +### Test Before You Document +- **Run every command** before documenting it — reading code is not enough +- Commands may prompt for confirmation, require undocumented env vars, or fail silently +- Create a test environment and execute the full flow end-to-end + +### Show What Success Looks Like +- **Add sample outputs** after commands so users can verify they're on track +- For deployment commands, show the key values users need to note (addresses, IDs) +- For validation commands, show both success and failure outputs + +### Environment Variables +- **List all required env vars explicitly** — don't assume users will discover them +- If multiple tools use similar-but-different var names, clarify which is which +- Show the export pattern once, then reference it in subsequent commands + +### Avoid Expert Blind Spots +- If you say "add the hash", explain how to compute the hash +- If you reference a file, explain where to find it +- If a value comes from a previous step, remind users which step + +### Cross-Reference Related Docs +- Link to prerequisite guides (don't repeat content) +- Link to detailed guides for optional deep-dives +- Use anchor links for specific sections when possible + +## Security Documentation + +### Trust Model Framing + +**Distinguish trust from verification:** +- "Trust" = cannot be verified, must assume correct (e.g., hardware) +- "Verify" = can be cryptographically proven (e.g., measured software) + +**Correct framing:** +- Bad: "You must trust the OS" (when it's verifiable) +- Good: "The OS is measured during boot and recorded in the attestation quote. You verify it by..." + +### Limitations: Be Honest, Not Alarmist + +State limitations plainly without false mitigations: +- Bad: "X is a single point of failure. Mitigate by running your own X." +- Good: "X is protected by [mechanism]. Like all [category] systems, [inherent limitation]. We are developing [actual solution] to address this." + +Don't suggest mitigations that don't actually help. If something is an inherent limitation of the technology, say so. + +## Documentation Quality Checklist + +From doc-requirements.md: + +1. **No bullet point walls** — Max 3-5 bullets before breaking with prose +2. **No redundancy** — Don't present same info from opposite perspectives +3. **Conversational language** — Write like explaining to a peer +4. **Short paragraphs** — Max 4 sentences per paragraph +5. **Lead with key takeaway** — First sentence tells reader why this matters +6. **Active voice** — "TEE encrypts memory" not "Memory is encrypted by TEE" +7. **Minimal em-dashes** — Max 1-2 per page, replace with "because", "so", or separate sentences + +### Redundancy Patterns to Avoid + +These often say the same thing: +- "What we protect against" + "What you don't need to trust" +- "Security guarantees" + "What attestation proves" + +Combine into single sections. One detailed explanation, brief references elsewhere. + +## README Structure + +### Order Matters +- **Quick Start before Prerequisites** — Lead with what it does, not setup +- **How It Works after Quick Start** — Users want to run it first, understand later +- Cleanup at the end, Further Reading last + +### Don't Duplicate +- Link to conceptual docs instead of repeating content +- If an overview README duplicates an example README, cut the overview +- One detailed explanation, brief references elsewhere + +### Remove Unrealistic Sections +- If most users can't actually do something (e.g., run locally without special hardware), don't include it +- Don't document workflows that require resources users don't have + +### Match the Workflow to the User +- Use tools your audience already knows (e.g., Jupyter for ML practitioners) +- Prefer official/existing images when they exist — don't reinvent +- Make the correct path the default, mention alternatives briefly + +## Code Examples + +### Question Every Snippet +- Does this code actually demonstrate something meaningful? +- Would a reader understand what it does without the prose? +- `do_thing(b"magic-string")` means nothing — show real use or remove it + +### Diagrams +- Mermaid over ASCII art — GitHub renders it nicely +- Keep diagrams simple — 3-5 nodes max +- Label edges with actions, not just arrows + +## Conciseness + +### Less is More +- 30 lines beats 150 if it says the same thing +- Cut sections that don't help users accomplish their goal +- Tables for reference, prose for explanation — don't over-table + +### Performance and Benchmarks +- One memorable number + link to full report +- Don't overwhelm with data the reader didn't ask for + +### Reader-First Writing +- Ask "what does the reader want to know?" not "what do I want to say?" +- If a section answers a question nobody asked, cut it + +## Maintenance + +### Consistency Checks +- After terminology changes, grep for related terms across all files +- Use correct industry/vendor terminology (e.g., "Confidential Computing" not "Encrypted Computing") + +### Clean Up Old Files +- When approach changes, delete orphaned files (old scripts, Dockerfiles) +- Don't leave artifacts from previous implementations diff --git a/.claude/agents/sdk-sync-checker.md b/.claude/agents/sdk-sync-checker.md new file mode 100644 index 0000000000..4e4050109e --- /dev/null +++ b/.claude/agents/sdk-sync-checker.md @@ -0,0 +1,76 @@ +--- +name: protobuf-sdk-validator +description: Validates that SDK implementations are synchronized with Protocol Buffer schema definitions. Use when protobuf files change, SDKs need verification, or you suspect schema drift. +tools: Bash, Glob, Grep, Read, TodoWrite +model: sonnet +color: yellow +--- + +You validate SDK implementations against protobuf schemas to ensure synchronization. + +## Process + +### 1. Discovery +- Find all `.proto` files in `dstack/guest-agent/rpc/proto/` +- Identify SDK implementations in `sdk/` (python, go, rust, js, curl docs) +- Extract services, RPCs, and message types from proto files + +### 2. Extract Schema +For each message type, extract: +- Field names, types, and numbers +- Required/optional/repeated modifiers +- Nested types and enums +- Service method signatures + +### 3. Compare SDKs +For each SDK, verify message/response types contain: +- All proto fields (accounting for naming conventions) +- Correct type mappings (bytes→hex string, string→string, repeated→array) +- Proper optionality markers + +### 4. Report + +```markdown +# SDK Sync Report + +## Summary +Status: ✅/❌ | Protos: X | SDKs: Y | Issues: Z + +## Findings + +### [SDK Name] (path/to/file.ext) +| Proto Message | Status | Missing Fields | +|---------------|--------|----------------| +| MessageName | ❌ | field1, field2 | + +Details: +- ❌ MessageName.field1: missing (proto line X, expected in SDK) +- ❌ MessageName.field2: missing (proto line Y, expected in SDK) + +## Action Items +1. [SDK]: Add field X to MessageY (file.ext:lineN) +2. [SDK]: Fix type mismatch for field Z +``` + +## Type Mappings +- `bytes` → hex `string` (Python/Go/JS/Rust), `string` JSON (cURL docs) +- `string` → `string` (all) +- `repeated X` → array/list/vec (language-specific) +- `int32/uint32` → number/int types + +## Naming Conventions +- Python: `snake_case` +- Go: `PascalCase` (exported fields) +- Rust: `snake_case` +- JavaScript: `camelCase` +- cURL docs: `snake_case` (JSON wire format) + +## Locations +- Protos: `dstack/guest-agent/rpc/proto/*.proto` +- Python: `sdk/python/src/dstack_sdk/dstack_client_v0.py`, `dstack_client_v1.py` +- Go: `sdk/go/dstack/client_v0.go`, `client_v1.go` +- Rust: `sdk/rust/types/src/dstack_v0.rs`, `dstack_v1.rs` +- JS: `sdk/js/src/client-v0.ts`, `client-v1.ts` +- Docs: `sdk/curl/api.md`, `sdk/curl/api-tappd.md` + +Focus on API surface differences. Provide specific file paths and line numbers. diff --git a/.cursorrules b/.cursorrules index be2db83689..b03e196fc7 100644 --- a/.cursorrules +++ b/.cursorrules @@ -1 +1 @@ -Don't capitalize the first letter for log messages and error messages. \ No newline at end of file +Don't capitalize the first letter for log messages and error messages. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..49ad1be77a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +# Weekly version updates, one grouped PR per directory for minor and patch +# bumps; major bumps arrive as their own PRs. The cooldown keeps freshly +# published releases out for a week. Security updates bypass both. +version: 2 + +updates: + - package-ecosystem: cargo + directories: ["/dstack", "/sdk/rust"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + cargo: + update-types: ["minor", "patch"] + + - package-ecosystem: gomod + directories: ["/sdk/go", "/sdk/go/*"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + gomod: + update-types: ["minor", "patch"] + + - package-ecosystem: bun + directories: ["/sdk/js", "/dstack/kms/auth-eth"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + bun: + update-types: ["minor", "patch"] + + - package-ecosystem: npm + directories: ["/dstack/vmm/ui", "/sdk/verifier-wasm"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + npm: + update-types: ["minor", "patch"] + + - package-ecosystem: pip + directories: ["/sdk/python", "/dstack/vmm", "/dstack/python/ct_monitor"] + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + pip: + update-types: ["minor", "patch"] + + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + cooldown: + default-days: 7 + groups: + github-actions: + update-types: ["minor", "patch"] diff --git a/.github/scripts/cargo-publish-idempotent.sh b/.github/scripts/cargo-publish-idempotent.sh new file mode 100755 index 0000000000..118b10da60 --- /dev/null +++ b/.github/scripts/cargo-publish-idempotent.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 +# +# Wraps `cargo publish -p $1` so that "already exists on crates.io" is treated +# as success. Lets a partially-failed release be retried by pushing the same +# tag, without getting stuck on the first crate. + +set -euo pipefail + +crate=${1:?missing crate name} + +if output=$(cargo publish --manifest-path sdk/rust/Cargo.toml -p "$crate" 2>&1); then + echo "$output" + exit 0 +fi + +echo "$output" + +if grep -q "already exists on crates.io index" <<<"$output"; then + echo "::notice::$crate is already published at this version; treating as success" + exit 0 +fi + +exit 1 diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock new file mode 100644 index 0000000000..9bb8607152 --- /dev/null +++ b/.github/workflows/actions.lock @@ -0,0 +1,401 @@ +# This file is machine-generated by `gh actions-lock`. +# Do not edit by hand; run `gh actions-lock` to update. +# Docs: https://gh.io/actions-lockfile +version: 'v0.0.3' +workflows: + '.github/workflows/docker-build-check.yml': + - 'actions/checkout@v5' + - 'docker/build-push-action@v5' + - 'docker/setup-buildx-action@v3' + - 'foundry-rs/foundry-toolchain@v1' + '.github/workflows/foundry-test.yml': + - 'actions/checkout@v5' + - 'foundry-rs/foundry-toolchain@v1' + '.github/workflows/gateway-cluster-tests.yml': + - 'actions/cache@v4' + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/gateway-e2e-tests.yml': + - 'actions/cache@v4' + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/gateway-proxy-tests.yml': + - 'actions/cache@v4' + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/gateway-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/go-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff' + - 'dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + - 'swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0' + '.github/workflows/guest-os.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093' + - 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' + '.github/workflows/halmos.yml': + - 'actions/checkout@v5' + - 'foundry-rs/foundry-toolchain@v1' + '.github/workflows/js-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444' + - 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/key-recovery-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/kms-auth-eth.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6' + '.github/workflows/kms-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'foundry-rs/foundry-toolchain@908c540300062bd5a7e473851cdb4282204cee09' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/lean.yml': + - 'actions/checkout@v5' + - 'leanprover/lean-action@v1' + '.github/workflows/local-key-provider-release.yml': + - 'actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8' + - 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1' + - 'docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a' + - 'docker/login-action@dbcb813823bdd20940b903addbd779551569679f' + - 'docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e' + - 'softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64' + '.github/workflows/mkosi-build.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093' + - 'actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1' + - 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + '.github/workflows/plumber-check.yml': + - 'actions/checkout@v5' + - 'getplumber/plumber@v0.7.23' + '.github/workflows/prek-check.yml': + - 'actions/checkout@v5' + - 'actions/setup-go@v5' + - 'actions/setup-python@v5' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/python-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065' + - 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/qemu-acpi-differential.yml': + - 'actions/checkout@v5' + - 'actions/upload-artifact@v4' + - 'dtolnay/rust-toolchain@v1' + '.github/workflows/rust-sdk-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9' + '.github/workflows/rust.yml': + - 'actions/checkout@v5' + - 'dtolnay/rust-toolchain@v1' + - 'swatinem/rust-cache@v2' + '.github/workflows/sdk-compat.yaml': + - 'actions/checkout@v5' + - 'actions/setup-go@v5' + - 'actions/setup-node@v5' + - 'actions/setup-python@v5' + - 'dtolnay/rust-toolchain@v1' + - 'swatinem/rust-cache@v2' + '.github/workflows/sdk.yaml': + - 'actions/checkout@v5' + - 'actions/setup-python@v5' + - 'dtolnay/rust-toolchain@v1' + - 'swatinem/rust-cache@v2' + '.github/workflows/simulator-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + - 'swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6' + '.github/workflows/spdx-check.yml': + - 'actions/checkout@v5' + - 'fsfe/reuse-action@v5' + '.github/workflows/verifier-release.yml': + - 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018' + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9' + - 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/verifier-wasm-release.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444' + - 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + '.github/workflows/verifier-wasm.yml': + - 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + - 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093' + - 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444' + - 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02' + - 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6' + '.github/workflows/vmm-ui.yml': + - 'actions/checkout@v5' + - 'actions/setup-node@v5' + - 'actions/setup-python@v5' +dependencies: + 'actions/attest-build-provenance@36fa7d009e22618ca7cd599486979b8150596c74': + ref: 'predicate@1.1.4' + commit: 'sha1-36fa7d009e22618ca7cd599486979b8150596c74' + owner_id: 44036562 + repo_id: 760702757 + 'actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8': + ref: 'v4.2.2' + commit: 'sha1-4d101475d8b20a2381f78447822ac1eab6504dd8' + owner_id: 44036562 + repo_id: 760702757 + uses: + - 'actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d' + 'actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018': + ref: 'v1.4.4' + commit: 'sha1-ef244123eb79f2f7a7e75d99086184180e6d0018' + owner_id: 44036562 + repo_id: 760702757 + uses: + - 'actions/attest-build-provenance@36fa7d009e22618ca7cd599486979b8150596c74' + - 'actions/attest@67422f5511b7ff725f4dbd6fb9bd2cd925c65a8d' + 'actions/attest@508db95dd578ae2727ebd6217d5ba78e4fbda05d': + ref: 'v4.2.1' + commit: 'sha1-508db95dd578ae2727ebd6217d5ba78e4fbda05d' + owner_id: 44036562 + repo_id: 760701061 + 'actions/attest@67422f5511b7ff725f4dbd6fb9bd2cd925c65a8d': + ref: 'v1.4.1' + commit: 'sha1-67422f5511b7ff725f4dbd6fb9bd2cd925c65a8d' + owner_id: 44036562 + repo_id: 760701061 + 'actions/cache@caa296126883cff596d87d8935842f9db880ef25': + ref: 'v5.1.0' + commit: 'sha1-caa296126883cff596d87d8935842f9db880ef25' + owner_id: 44036562 + repo_id: 215566462 + 'actions/cache@v4': + ref: 'v4' + commit: 'sha1-0057852bfaa89a56745cba8c7296529d2fc39830' + owner_id: 44036562 + repo_id: 215566462 + 'actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1': + ref: 'v7.0.1' + commit: 'sha1-3d3c42e5aac5ba805825da76410c181273ba90b1' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09': + ref: 'v5.1.0' + commit: 'sha1-fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + owner_id: 44036562 + repo_id: 197814629 + 'actions/checkout@v5': + ref: 'v5' + commit: 'sha1-fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09' + owner_id: 44036562 + repo_id: 197814629 + 'actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093': + ref: 'v4.3.0' + commit: 'sha1-d3f86a106a0bac45b974a628896c90dbdf5c8093' + owner_id: 44036562 + repo_id: 192626254 + 'actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff': + ref: 'v5.6.0' + commit: 'sha1-40f1582b2485089dde7abd97c1529aa768e1baff' + owner_id: 44036562 + repo_id: 192624594 + 'actions/setup-go@v5': + ref: 'v5' + commit: 'sha1-40f1582b2485089dde7abd97c1529aa768e1baff' + owner_id: 44036562 + repo_id: 192624594 + 'actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444': + ref: 'v5.0.0' + commit: 'sha1-a0853c24544627f65ddf259abe73b1d18a591444' + owner_id: 44036562 + repo_id: 189476904 + 'actions/setup-node@v5': + ref: 'v5' + commit: 'sha1-a0853c24544627f65ddf259abe73b1d18a591444' + owner_id: 44036562 + repo_id: 189476904 + 'actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065': + ref: 'v5.6.0' + commit: 'sha1-a26af69be951a213d495a4c3e4e4022e16d87065' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405': + ref: 'v6.2.0' + commit: 'sha1-a309ff8b426b58ec0e2a45f0f869d46889d02405' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1': + ref: 'v6.3.0' + commit: 'sha1-ece7cb06caefa5fff74198d8649806c4678c61a1' + owner_id: 44036562 + repo_id: 192625525 + 'actions/setup-python@v5': + ref: 'v5' + commit: 'sha1-a26af69be951a213d495a4c3e4e4022e16d87065' + owner_id: 44036562 + repo_id: 192625525 + 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9': + ref: 'v7.0.2' + commit: 'sha1-cf430e030ddbb5b0abf93d22962f4752f3646cd9' + owner_id: 44036562 + repo_id: 192625955 + 'actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02': + ref: 'v4.6.2' + commit: 'sha1-ea165f8d65b6e75b540449e92b4886f43607fa02' + owner_id: 44036562 + repo_id: 192625955 + 'actions/upload-artifact@v4': + ref: 'v4' + commit: 'sha1-ea165f8d65b6e75b540449e92b4886f43607fa02' + owner_id: 44036562 + repo_id: 192625955 + 'docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8': + ref: 'v6.19.2' + commit: 'sha1-10e90e3645eae34f1e60eeb005ba3a3d33f178e8' + owner_id: 5429470 + repo_id: 241092383 + 'docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a': + ref: 'v7.3.0' + commit: 'sha1-53b7df96c91f9c12dcc8a07bcb9ccacbed38856a' + owner_id: 5429470 + repo_id: 241092383 + 'docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25': + ref: 'v5.4.0' + commit: 'sha1-ca052bb54ab0790a636c9b5f226502c73d547a25' + owner_id: 5429470 + repo_id: 241092383 + 'docker/build-push-action@v5': + ref: 'v5' + commit: 'sha1-ca052bb54ab0790a636c9b5f226502c73d547a25' + owner_id: 5429470 + repo_id: 241092383 + 'docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9': + ref: 'v3.7.0' + commit: 'sha1-c94ce9fb468520275223c153574b00df6fe4bcc9' + owner_id: 5429470 + repo_id: 287743349 + 'docker/login-action@dbcb813823bdd20940b903addbd779551569679f': + ref: 'v4.6.0' + commit: 'sha1-dbcb813823bdd20940b903addbd779551569679f' + owner_id: 5429470 + repo_id: 287743349 + 'docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e': + ref: 'v4.3.0' + commit: 'sha1-37fe631027851001ddb9b187196cc803df7f5f0e' + owner_id: 5429470 + repo_id: 288485773 + 'docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f': + ref: 'v3.12.0' + commit: 'sha1-8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + owner_id: 5429470 + repo_id: 288485773 + 'docker/setup-buildx-action@v3': + ref: 'v3' + commit: 'sha1-8d2750c68a42422c14e847fe6c8ac0403b4cbd6f' + owner_id: 5429470 + repo_id: 288485773 + 'dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8': + ref: 'v1' + commit: 'sha1-683b588c487a69d01f6c6ddf40f036ff682cc2c8' + owner_id: 1940490 + repo_id: 260749683 + 'dtolnay/rust-toolchain@v1': + ref: 'v1' + commit: 'sha1-683b588c487a69d01f6c6ddf40f036ff682cc2c8' + owner_id: 1940490 + repo_id: 260749683 + 'foundry-rs/foundry-toolchain@908c540300062bd5a7e473851cdb4282204cee09': + ref: 'v1.9.1' + commit: 'sha1-908c540300062bd5a7e473851cdb4282204cee09' + owner_id: 99892494 + repo_id: 448072613 + 'foundry-rs/foundry-toolchain@v1': + ref: 'v1' + commit: 'sha1-dba66c27052e63476d886f22216e119ba7e615bf' + owner_id: 99892494 + repo_id: 448072613 + 'fsfe/reuse-action@v5': + ref: 'v5' + commit: 'sha1-bb774aa972c2a89ff34781233d275075cbddf542' + owner_id: 27927890 + repo_id: 244390200 + 'getplumber/plumber@v0.7.23': + ref: 'v0.7.23' + commit: 'sha1-ec8cb3a7edd6a324b33e85109b627b2df6023d94' + owner_id: 255179076 + repo_id: 1137327132 + uses: + - 'actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9' + - 'github/codeql-action@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee' + 'github/codeql-action@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee': + ref: 'v4.39.0' + commit: 'sha1-6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee' + owner_id: 9919 + repo_id: 259445878 + 'leanprover/lean-action@v1': + ref: 'v1' + commit: 'sha1-ba3fdfe5c4476c925da13bf11a005ddb47e47aee' + owner_id: 7233018 + repo_id: 795738301 + uses: + - 'actions/cache@caa296126883cff596d87d8935842f9db880ef25' + 'oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6': + ref: 'v2.2.0' + commit: 'sha1-0c5077e51419868618aeaa5fe8019c62421857d6' + owner_id: 108928776 + repo_id: 512644635 + 'pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086': + ref: 'v1.14.3' + commit: 'sha1-7245906fb61fa33a13554f9d5fb856fe61758086' + owner_id: 647025 + repo_id: 178055147 + uses: + - 'actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405' + 'rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9': + ref: 'v1.0.6' + commit: 'sha1-3268eb413133e2960fa4ae0e963ca76380c54cd9' + owner_id: 5430905 + repo_id: 1008931044 + 'softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65': + ref: 'v2.6.2' + commit: 'sha1-3bb12739c298aeb8a4eeaf626c5b8d85266b0e65' + owner_id: 2242 + repo_id: 204253808 + 'softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64': + ref: 'v3.0.3' + commit: 'sha1-efb35369e0ad2afab669f228072c1b0d510eae64' + owner_id: 2242 + repo_id: 204253808 + 'swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6': + ref: 'v2.9.2' + commit: 'sha1-6323deb102c322ba6fcbdcafc7e3dddab59af2b6' + owner_id: 580492 + repo_id: 298565987 + 'swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0': + ref: 'v2.9.3' + commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' + owner_id: 580492 + repo_id: 298565987 + 'swatinem/rust-cache@v2': + ref: 'v2' + commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' + owner_id: 580492 + repo_id: 298565987 diff --git a/.github/workflows/docker-build-check.yml b/.github/workflows/docker-build-check.yml new file mode 100644 index 0000000000..7711e07268 --- /dev/null +++ b/.github/workflows/docker-build-check.yml @@ -0,0 +1,222 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Docker Build Check + +# Not a required status check, so a workflow-level filter is safe here: a pull +# request that skips it is not left waiting on a check that never arrives. What +# it verifies -- that the builder images still build and that their pinned +# package lists still match -- cannot change unless something under `dstack/` +# does. +on: + push: + branches: [ next, 'release/**' ] + paths: + - 'dstack/**' + - 'rust-toolchain.toml' + - '.github/workflows/docker-build-check.yml' + - '.github/workflows/kms-release.yml' + - '.github/workflows/gateway-release.yml' + - '.github/workflows/verifier-release.yml' + pull_request: + branches: [ next, 'release/**' ] + paths: + - 'dstack/**' + - 'rust-toolchain.toml' + - '.github/workflows/docker-build-check.yml' + - '.github/workflows/kms-release.yml' + - '.github/workflows/gateway-release.yml' + - '.github/workflows/verifier-release.yml' + +permissions: + contents: read + +env: + DSTACK_REV: ${{ github.event.pull_request.head.sha || github.sha }} + DSTACK_SRC_URL: ${{ github.event.pull_request.head.repo.clone_url || format('{0}/{1}', github.server_url, github.repository) }} + +# Builds go through the `docker` driver, i.e. the daemon's own BuildKit, rather +# than the `docker-container` builder setup-buildx creates by default. With a +# container builder every `--load` compresses the result into a tarball and +# imports it into the daemon; for the `*-builder` targets, which carry the Rust +# toolchain and the cargo target directory, that alone was two to three +# minutes. With the daemon's builder the image lands in the store directly, and +# the second build of the `*-builder` target is a cache hit on the first. +# +# No BuildKit layer cache (`cache-to: type=gha`). The source is cloned at +# DSTACK_REV inside the build, so the cargo layer misses on every commit, and +# `mode=max` still exported the whole builder stage to the Actions cache: about +# two and a half minutes per job, and most of the repository's 10 GB cache +# quota, which evicted the cargo caches the other workflows depend on. What it +# could have saved was the pinned-package install, roughly fifteen seconds. +jobs: + build-script-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + - name: Test release build orchestration + run: python3 -m unittest discover -s dstack/build/shared/tests -v + + gateway: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + with: + driver: docker + + - name: Build Gateway Docker image + uses: docker/build-push-action@v5 + with: + context: dstack/gateway/dstack-app/builder + push: false + load: true + tags: dstack-gateway-check:latest + provenance: false + build-contexts: | + build-shared=dstack/build/shared + build-args: | + DSTACK_REV=${{ env.DSTACK_REV }} + DSTACK_SRC_URL=${{ env.DSTACK_SRC_URL }} + + - name: Verify pinned packages + run: | + dstack/build/shared/verify-pinned-packages.sh dstack-gateway-check:latest \ + dstack/gateway/dstack-app/builder/shared/pinned-packages.txt + + - name: Build gateway-builder target + run: | + docker buildx build \ + --load \ + --target gateway-builder \ + --tag gateway-builder-check:latest \ + --provenance=false \ + --build-context build-shared=dstack/build/shared \ + --build-arg "DSTACK_REV=${DSTACK_REV}" \ + --build-arg "DSTACK_SRC_URL=${DSTACK_SRC_URL}" \ + dstack/gateway/dstack-app/builder + + - name: Verify builder pinned packages + run: | + dstack/build/shared/verify-pinned-packages.sh gateway-builder-check:latest \ + dstack/gateway/dstack-app/builder/shared/builder-pinned-packages.txt + + kms: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Checkout KMS contract dependencies + run: | + git submodule update --init --recursive --depth 1 -- \ + dstack/kms/auth-eth/lib/forge-std \ + dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable \ + dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + with: + driver: docker + + - name: Build KMS Docker image + uses: docker/build-push-action@v5 + with: + context: dstack/kms/dstack-app/builder + push: false + load: true + tags: dstack-kms-check:latest + provenance: false + build-contexts: | + build-shared=dstack/build/shared + build-args: | + DSTACK_REV=${{ env.DSTACK_REV }} + DSTACK_SRC_URL=${{ env.DSTACK_SRC_URL }} + + - name: Verify pinned packages + run: | + dstack/build/shared/verify-pinned-packages.sh dstack-kms-check:latest \ + dstack/kms/dstack-app/builder/shared/pinned-packages.txt + + - name: Build kms-builder target + run: | + docker buildx build \ + --load \ + --target kms-builder \ + --tag kms-builder-check:latest \ + --provenance=false \ + --build-context build-shared=dstack/build/shared \ + --build-arg "DSTACK_REV=${DSTACK_REV}" \ + --build-arg "DSTACK_SRC_URL=${DSTACK_SRC_URL}" \ + dstack/kms/dstack-app/builder + + - name: Verify builder pinned packages + run: | + dstack/build/shared/verify-pinned-packages.sh kms-builder-check:latest \ + dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Build KMS contracts + run: | + cd dstack/kms/auth-eth + forge build + + verifier: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + with: + driver: docker + + - name: Build Verifier Docker image + uses: docker/build-push-action@v5 + with: + context: dstack/verifier + file: dstack/verifier/builder/Dockerfile + push: false + load: true + tags: dstack-verifier-check:latest + provenance: false + build-contexts: | + build-shared=dstack/build/shared + build-args: | + DSTACK_REV=${{ env.DSTACK_REV }} + DSTACK_SRC_URL=${{ env.DSTACK_SRC_URL }} + + - name: Verify pinned packages (runtime) + run: | + dstack/build/shared/verify-pinned-packages.sh dstack-verifier-check:latest \ + dstack/verifier/builder/shared/pinned-packages.txt + + - name: Build verifier-builder target + run: | + docker buildx build \ + --load \ + --target verifier-builder \ + --tag verifier-builder-check:latest \ + --provenance=false \ + --file dstack/verifier/builder/Dockerfile \ + --build-context build-shared=dstack/build/shared \ + --build-arg "DSTACK_REV=${DSTACK_REV}" \ + --build-arg "DSTACK_SRC_URL=${DSTACK_SRC_URL}" \ + dstack/verifier + + - name: Verify builder pinned packages + run: | + dstack/build/shared/verify-pinned-packages.sh verifier-builder-check:latest \ + dstack/verifier/builder/shared/builder-pinned-packages.txt diff --git a/.github/workflows/foundry-test.yml b/.github/workflows/foundry-test.yml new file mode 100644 index 0000000000..cb6ae7cf3c --- /dev/null +++ b/.github/workflows/foundry-test.yml @@ -0,0 +1,75 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: KMS Auth-ETH Foundry Tests + +on: + push: + paths: + - 'dstack/kms/auth-eth/**' + - '.github/workflows/foundry-test.yml' + pull_request: + paths: + - 'dstack/kms/auth-eth/**' + - '.github/workflows/foundry-test.yml' + workflow_dispatch: + +permissions: + contents: read + +env: + FOUNDRY_PROFILE: ci + +jobs: + check: + name: Foundry project + runs-on: ubuntu-latest + defaults: + run: + working-directory: dstack/kms/auth-eth + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Checkout contract dependencies + working-directory: . + run: | + git submodule update --init --recursive --depth 1 -- \ + dstack/kms/auth-eth/lib/forge-std \ + dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable \ + dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + + - name: Show Forge version + run: | + forge --version + + - name: Run Forge fmt + run: | + forge fmt --check + id: fmt + + - name: Run Forge build + run: | + forge build --sizes + id: build + + - name: Install OpenZeppelin upgrades validator + # The upgrade-safety tests run `npx @openzeppelin/upgrades-core@^1.37.0`; + # warm the npx cache with that spec once so parallel tests reuse it. + # `npm install` here would also resolve the webhook server's + # package.json, which is managed by Bun. + run: npx --yes @openzeppelin/upgrades-core@^1.37.0 --help > /dev/null + + - name: Run Forge tests + # The upgrade-safety validator rejects a contract found in more than one + # build-info file. Since forge 1.8.4 `build --sizes` skips tests, so the + # test run would add a second build-info next to it. + run: | + forge clean + forge test --ffi -vvv + id: test diff --git a/.github/workflows/gateway-cluster-tests.yml b/.github/workflows/gateway-cluster-tests.yml new file mode 100644 index 0000000000..fb9cf58ed8 --- /dev/null +++ b/.github/workflows/gateway-cluster-tests.yml @@ -0,0 +1,145 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Gateway cluster tests + +# WaveKV replication between gateway nodes: push and periodic sync, anti-entropy +# repair, bootstrap after losing a store, partition recovery, node identity, and +# the admin RPCs that gate registration. Unit tests cover the store; this runs +# three real gateways and stops, wipes and restarts them. +# +# The nodes authenticate each other for real, so the cluster mTLS path is +# exercised rather than switched off -- which is what the process-based suite +# this replaces could not do. +on: + push: + branches: [ next, 'release/**' ] + paths: + - 'dstack/gateway/**' + - 'dstack/cert-client/**' + - 'dstack/ra-tls/**' + - 'dstack/guest-agent-simulator/**' + - 'sdk/simulator/**' + - 'dstack/crates/mock-attestation/**' + - '.github/workflows/gateway-cluster-tests.yml' + pull_request: + branches: [ next, 'release/**' ] + paths: + - 'dstack/gateway/**' + - 'dstack/cert-client/**' + - 'dstack/ra-tls/**' + - 'dstack/guest-agent-simulator/**' + - 'sdk/simulator/**' + - 'dstack/crates/mock-attestation/**' + - '.github/workflows/gateway-cluster-tests.yml' + +# Per workflow, not shared with the other two gateway suites. +# +# A group shared across all three does not serialise them, it drops one: a +# concurrency group holds a single *pending* run, so when the third workflow +# queued behind the first two, the one already waiting was cancelled -- +# silently, and reported as a cancelled run rather than a failure. The suites +# no longer need serialising anyway; each brings up its own attestation fixture +# under its own `FIXTURE_NS`, so there is nothing left to collide over. +# +# `cancel-in-progress` is the ordinary meaning here: a new push supersedes the +# run for the commit it replaced. +concurrency: + group: gateway-cluster-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + gateway-cluster: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + # 28 tests, most of which restart nodes and then wait out a 5s sync interval. + timeout-minutes: 60 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + targets: x86_64-unknown-linux-musl + + - name: Install musl toolchain + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools + + # The gateways create real WireGuard interfaces inside their containers. + - name: Record kernel capabilities + run: | + echo "kernel: $(uname -r)" + sudo modprobe wireguard 2>&1 || echo "no wireguard module available" + echo "wireguard loaded: $(lsmod | grep -c '^wireguard ' || true)" + + - name: Cache cargo + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + dstack/target + key: gateway-cluster-${{ runner.os }}-${{ hashFiles('dstack/Cargo.lock') }} + restore-keys: gateway-cluster-${{ runner.os }}- + + - name: Cluster suite + working-directory: dstack/gateway/test-run/cluster + run: ./run-cluster-tests.sh + + # The suite only materialises node logs for the two tests that assert on + # them, so the mounted directory is close to empty for any other failure. + # Pull them from the daemon instead, by compose service so the shared + # fixture's project-scoped names do not have to be guessed. + - name: Collect node logs on failure + if: failure() + working-directory: dstack/gateway/test-run/cluster + # The compose files require `${FIXTURE_NS:?}`, and the suite script + # exports it only to itself. Unset here, every `docker compose` call in + # this step -- not just the fixture one -- fails at interpolation, and + # the step still passes, so the artifact carries no container logs. + env: + FIXTURE_NS: dstack-fixture-cluster + run: | + mkdir -p run/logs + # By project, discovered from the daemon. A bare `docker compose` here + # addresses the project named after this directory (`cluster`), which + # no test ever uses -- every test runs under `cluster-`, so + # the loop that used `compose config --services` collected nothing. + docker ps -a --filter 'label=com.docker.compose.project' \ + --format '{{.Label "com.docker.compose.project"}}' \ + | grep -E '^cluster-' | sort -u | while read -r project; do + docker compose -p "$project" -f docker-compose.yml logs --no-color \ + > "run/logs/project-$project.log" 2>&1 || true + done + # The suite's own per-test dumps are root-owned inside the bind mount. + docker run --rm -v "$PWD/run:/r" alpine:latest chmod -R a+rX /r || true + # The attestation fixture is a project of its own now, so it is not in + # this suite's service list and its logs have to be asked for + # separately -- they are where a quote-verification failure explains + # itself. + docker compose -p "$FIXTURE_NS" -f ../attestation/fixture.yml logs \ + --no-color > "run/logs/fixture.log" 2>&1 || true + docker compose ps -a > run/logs/compose-ps.txt 2>&1 || true + + - name: Upload node logs on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: gateway-cluster-logs + path: dstack/gateway/test-run/cluster/run/logs/ + if-no-files-found: ignore + retention-days: 7 + + - name: Tear down + if: always() + working-directory: dstack/gateway/test-run/cluster + run: ./run-cluster-tests.sh down diff --git a/.github/workflows/gateway-e2e-tests.yml b/.github/workflows/gateway-e2e-tests.yml new file mode 100644 index 0000000000..4e65ddbfed --- /dev/null +++ b/.github/workflows/gateway-e2e-tests.yml @@ -0,0 +1,150 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Gateway e2e tests + +# The gateway's certbot/ACME half only exists as a whole: certificate issuance, +# cluster sync of the result, and the dns-persist-01 flow each depend on the +# ones before. Unit tests cover the pieces; this stands up three gateways, a +# Pebble CA, a mock Cloudflare DNS API and a mock attestation collateral +# service, and asserts on what the cluster actually converges to. +# +# The suite verifies peer quotes for real: the gateways check each other against +# development trust anchors derived from the simulator's seed, so it covers the +# cluster mTLS path that a harness with the checks switched off cannot reach. +on: + push: + branches: [ next, 'release/**' ] + paths: + - 'dstack/gateway/**' + - 'dstack/cert-client/**' + - 'dstack/certbot/**' + - 'dstack/ra-tls/**' + - 'dstack/guest-agent-simulator/**' + - 'sdk/simulator/**' + - 'dstack/crates/mock-attestation/**' + - 'tools/mock-cf-dns/**' + - '.github/workflows/gateway-e2e-tests.yml' + pull_request: + branches: [ next, 'release/**' ] + paths: + - 'dstack/gateway/**' + - 'dstack/cert-client/**' + - 'dstack/certbot/**' + - 'dstack/ra-tls/**' + - 'dstack/guest-agent-simulator/**' + - 'sdk/simulator/**' + - 'dstack/crates/mock-attestation/**' + - 'tools/mock-cf-dns/**' + - '.github/workflows/gateway-e2e-tests.yml' + +# Per workflow, not shared with the other two gateway suites. +# +# A group shared across all three does not serialise them, it drops one: a +# concurrency group holds a single *pending* run, so when the third workflow +# queued behind the first two, the one already waiting was cancelled -- +# silently, and reported as a cancelled run rather than a failure. The suites +# no longer need serialising anyway; each brings up its own attestation fixture +# under its own `FIXTURE_NS`, so there is nothing left to collide over. +# +# `cancel-in-progress` is the ordinary meaning here: a new push supersedes the +# run for the commit it replaced. +concurrency: + group: gateway-e2e-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + gateway-e2e: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + # A cold musl build dominates; the suite itself waits out real ACME orders + # and a 20s cluster-sync settle, so it is minutes rather than seconds. + timeout-minutes: 45 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + # run-e2e.sh builds a static gateway so the image can be alpine. + targets: x86_64-unknown-linux-musl + + - name: Install musl toolchain + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools + + # The gateways create real WireGuard interfaces inside their containers, + # so the host kernel has to offer the module. Record it: a run that failed + # because the runner image changed under us should say so plainly instead + # of looking like a gateway bug. + - name: Record kernel capabilities + run: | + echo "kernel: $(uname -r)" + sudo modprobe wireguard 2>&1 || echo "no wireguard module available" + echo "wireguard loaded: $(lsmod | grep -c '^wireguard ' || true)" + docker version --format 'docker: {{.Server.Version}}' + docker compose version + + - name: Cache cargo + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + dstack/target + key: gateway-e2e-${{ runner.os }}-${{ hashFiles('dstack/Cargo.lock') }} + restore-keys: gateway-e2e-${{ runner.os }}- + + # --keep-running so the containers survive for the log step below; the + # script's own EXIT trap would otherwise tear them down and leave nothing + # to collect from exactly the runs worth diagnosing. + - name: Gateway e2e suite + working-directory: dstack/gateway/test-run/e2e + run: ./run-e2e.sh --keep-running + + - name: Collect container logs on failure + if: failure() + working-directory: dstack/gateway/test-run/e2e + # The compose files require `${FIXTURE_NS:?}`, and the suite script + # exports it only to itself. Unset here, every `docker compose` call in + # this step -- not just the fixture one -- fails at interpolation, and + # the step still passes, so the artifact carries no container logs. + env: + FIXTURE_NS: dstack-fixture-e2e + run: | + # By compose service, not by container name: the shared attestation + # fixture deliberately does not pin one, so that more than one suite + # can be up at a time. + mkdir -p /tmp/gateway-e2e-logs + for svc in $(docker compose config --services); do + docker compose logs --no-color "$svc" > "/tmp/gateway-e2e-logs/$svc.log" 2>&1 || true + done + # The attestation fixture is a project of its own now, so it is not in + # this suite's service list and its logs have to be asked for + # separately -- they are where a quote-verification failure explains + # itself. + docker compose -p "$FIXTURE_NS" -f ../attestation/fixture.yml logs \ + --no-color > "/tmp/gateway-e2e-logs/fixture.log" 2>&1 || true + docker compose ps -a > /tmp/gateway-e2e-logs/compose-ps.txt 2>&1 || true + + - name: Tear down + if: always() + working-directory: dstack/gateway/test-run/e2e + run: ./run-e2e.sh down + + - name: Upload logs on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: gateway-e2e-logs + path: /tmp/gateway-e2e-logs/ + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/gateway-proxy-tests.yml b/.github/workflows/gateway-proxy-tests.yml new file mode 100644 index 0000000000..43569e41ee --- /dev/null +++ b/.github/workflows/gateway-proxy-tests.yml @@ -0,0 +1,144 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Gateway proxy tests + +# The gateway's proxy data path has two opt-in optimisations (`tcp_splice`, +# `ktls`) whose behaviour depends on kernel capabilities and on a per-connection +# gate. Unit tests cover the relay functions; this runs a real gateway process +# and asserts on what actually reaches the wire. +# +# The suite runs in containers. One of them has a seccomp profile that makes +# `setsockopt(IPPROTO_TCP, TCP_ULP)` fail, which is how the no-TLS-ULP fallback +# is exercised now -- the suite used to `rmmod tls`, which needed passwordless +# sudo, took the module from the whole host, and skipped itself whenever +# anything else was using TLS. +on: + push: + branches: [ next, 'release/**' ] + paths: + - 'dstack/gateway/**' + - 'dstack/vendor/ktls/**' + # The suite runs the gateway with attestation on, so it depends on the + # shared fixture: the simulator, the mock collateral service, and the + # fixture payloads baked into the simulator image. + - 'dstack/guest-agent-simulator/**' + - 'dstack/crates/mock-attestation/**' + - 'sdk/simulator/**' + - '.github/workflows/gateway-proxy-tests.yml' + pull_request: + branches: [ next, 'release/**' ] + paths: + - 'dstack/gateway/**' + - 'dstack/vendor/ktls/**' + # The suite runs the gateway with attestation on, so it depends on the + # shared fixture: the simulator, the mock collateral service, and the + # fixture payloads baked into the simulator image. + - 'dstack/guest-agent-simulator/**' + - 'dstack/crates/mock-attestation/**' + - 'sdk/simulator/**' + - '.github/workflows/gateway-proxy-tests.yml' + +# Per workflow, not shared with the other two gateway suites. +# +# A group shared across all three does not serialise them, it drops one: a +# concurrency group holds a single *pending* run, so when the third workflow +# queued behind the first two, the one already waiting was cancelled -- +# silently, and reported as a cancelled run rather than a failure. The suites +# no longer need serialising anyway; each brings up its own attestation fixture +# under its own `FIXTURE_NS`, so there is nothing left to collide over. +# +# `cancel-in-progress` is the ordinary meaning here: a new push supersedes the +# run for the commit it replaced. +concurrency: + group: gateway-proxy-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + proxy-integration: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + # Each of the ~25 arms restarts the gateway, and the idle-timeout arms wait + # out a real timeout. On top of that the suite now builds the shared + # attestation fixture, whose two images compile Rust from a cold docker cache + # on every run -- the cargo cache above does not reach inside a docker build. + timeout-minutes: 45 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + # The container image is built around a static binary. + targets: x86_64-unknown-linux-musl + + - name: Install musl toolchain + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends musl-tools + + - name: Cache cargo + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + dstack/target + key: gateway-proxy-${{ runner.os }}-${{ hashFiles('dstack/Cargo.lock') }} + restore-keys: gateway-proxy-${{ runner.os }}- + + - name: Record kernel capabilities + # The suite adapts to what the kernel offers, so the log needs to say + # what it had: a run that skipped kTLS looks the same as one that + # covered it otherwise. + run: | + echo "kernel: $(uname -r)" + # Without this the suite falls back to a dummy link and skips + # test_accel_status entirely -- including the only positive proof that + # splice engaged. The other two workflows already modprobe it. + sudo modprobe wireguard 2>&1 || echo "no wireguard module available" + sudo modprobe tls 2>&1 || echo "no TLS ULP available" + echo "tls module loaded: $(lsmod | grep -c '^tls ' || true)" + grep -B2 -A3 'gcm(aes)' /proc/crypto | grep -E '^(driver|priority)' \ + | paste - - | sort -u || true + + - name: Proxy integration tests + working-directory: dstack/gateway/test-run/proxy-e2e + run: ./run-proxy-tests.sh + + # No `docker compose logs` here: the suite is driven with `compose run + # --rm`, so its containers are deleted on exit and the script's own trap + # has already run `compose down -v`. Everything worth reading is in the + # bind-mounted work directory, which the suite made host-readable before + # exiting. + - name: Make suite logs readable + if: failure() + working-directory: dstack/gateway/test-run/proxy-e2e + run: | + mkdir -p run + docker run --rm -v "$PWD/run:/r" alpine:latest chmod -R a+rX /r || true + ls -R run || true + + - name: Upload logs on failure + if: failure() + uses: actions/upload-artifact@v4 + with: + name: gateway-proxy-test-logs + # Only the logs. The work directory also holds each arm's throwaway + # TLS key, and an artifact is the wrong place for key material even + # when it is disposable. + path: dstack/gateway/test-run/proxy-e2e/run/*/logs/ + if-no-files-found: ignore + retention-days: 7 + + - name: Tear down + if: always() + working-directory: dstack/gateway/test-run/proxy-e2e + run: ./run-proxy-tests.sh down diff --git a/.github/workflows/gateway-release.yml b/.github/workflows/gateway-release.yml new file mode 100644 index 0000000000..5a5ba067a6 --- /dev/null +++ b/.github/workflows/gateway-release.yml @@ -0,0 +1,131 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Gateway Release + +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the gateway-v prefix + required: true + type: string + push: + tags: + - 'gateway-v*' +permissions: + attestations: write + id-token: write + contents: write + packages: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + steps: + - name: Parse and check version + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/gateway-v*) VERSION=${GITHUB_REF#refs/tags/gateway-v} ;; + *) echo "Expected a gateway-v* tag" >&2; exit 1 ;; + esac + fi + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "Version must be a valid Docker tag" >&2 + exit 1 + fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "RELEASE_TAG=gateway-v$VERSION" >> "$GITHUB_ENV" + + - name: Reclaim runner disk space + run: | + sudo rm -rf \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /usr/local/.ghcup \ + /usr/local/lib/android \ + /usr/share/dotnet + df -h / + + # Manual runs rebuild an existing release tag, not the selected branch. + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false + + - name: Log in to GitHub Container Registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Resolve the revision to build + run: echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + # Release images are built through the same script contributors run by + # hand, so a published image can be reproduced and checked digest-for-digest. + # See the builder README for the reproduction recipe. + - name: Build and push Docker image + id: build-and-push + env: + PUSH: "1" + METADATA_FILE: ${{ runner.temp }}/build-metadata.json + GIT_REV: ${{ env.GIT_REV }} + IMAGE_VERSION: ${{ env.VERSION }} + IMAGE_NAME: ghcr.io/dstack-tee/dstack-gateway:${{ env.VERSION }} + IMAGE_SOURCE_URL: ${{ github.server_url }}/${{ github.repository }} + DSTACK_SRC_URL: ${{ github.server_url }}/${{ github.repository }}.git + run: | + dstack/gateway/dstack-app/builder/build-image.sh \ + "$IMAGE_NAME" + digest=$(jq -r '."containerimage.digest"' "$METADATA_FILE") + if [ -z "$digest" ] || [ "$digest" = null ]; then + echo "the build did not report an image digest" >&2 + exit 1 + fi + echo "digest=$digest" >> "$GITHUB_OUTPUT" + + - name: Verify anonymous pull access + env: + IMAGE_DIGEST: ${{ steps.build-and-push.outputs.digest }} + run: | + token=$(curl -fsSL \ + "https://ghcr.io/token?scope=repository:dstack-tee/dstack-gateway:pull" \ + | jq -er .token) + curl -fsSL -o /dev/null \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json" \ + "https://ghcr.io/v2/dstack-tee/dstack-gateway/manifests/$IMAGE_DIGEST" + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-name: "ghcr.io/dstack-tee/dstack-gateway" + subject-digest: ${{ steps.build-and-push.outputs.digest }} + push-to-registry: true + + - name: GitHub Release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + tag_name: ${{ env.RELEASE_TAG }} + target_commitish: ${{ env.GIT_REV }} + name: "Gateway Release v${{ env.VERSION }}" + body: | + ## Docker Image Information + + **Image**: `ghcr.io/dstack-tee/dstack-gateway:${{ env.VERSION }}` + + **Digest (SHA256)**: `${{ steps.build-and-push.outputs.digest }}` + + **Verification**: [Verify on Sigstore](https://search.sigstore.dev/?hash=${{ steps.build-and-push.outputs.digest }}) diff --git a/.github/workflows/go-sdk-release.yml b/.github/workflows/go-sdk-release.yml new file mode 100644 index 0000000000..99b3bbfc01 --- /dev/null +++ b/.github/workflows/go-sdk-release.yml @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Publish Go SDK +on: + push: + # sdk/go/v0.6.1 is special: it tags the package-less deprecation stub and + # must be pushed before the carved-out modules get theirs. + tags: ['sdk/go/dstack/v*', 'sdk/go/ratls/v*', 'sdk/go/v0.6.1'] + workflow_dispatch: + inputs: + module: + description: 'Module to (re)index on pkg.go.dev' + required: true + default: 'sdk/go/dstack' + type: choice + options: + - sdk/go + - sdk/go/dstack + - sdk/go/ratls + version: + description: 'Version, with the leading v (e.g. v0.6.1)' + required: true + +permissions: + contents: read + +jobs: + test: + # workflow_dispatch is only for re-indexing pkg.go.dev after a release, so + # it skips the gate. + if: github.event_name == 'push' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 + with: + toolchain: 1.92.0 + + # The simulator is built from the dstack workspace; without the cache + # this build is most of the job's wall time. + - name: Cache cargo + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2 + with: + workspaces: dstack + + - name: Install Go + uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5 + with: + # The `go` directive in the released sdk/go/dstack/go.mod. sdk/go/ratls + # and sdk/go/tappd ask for 1.24, so this one toolchain covers all + # three modules. + go-version: '1.25' + + - name: Go SDK tests against the simulator + run: | + set -Eeuo pipefail + source sdk/simulator/lifecycle.sh + trap 'simulator_print_logs' ERR + trap simulator_stop EXIT INT TERM + simulator_start + + unformatted=$(gofmt -l sdk/go) + if [ -n "$unformatted" ]; then + echo "::error::unformatted Go files: $unformatted" + exit 1 + fi + + # Each of the three directories under sdk/go is its own module + # (dstack, tappd, ratls), so they are vetted and tested separately. + pushd sdk/go/dstack + go vet ./... + go test -v . + popd + + pushd sdk/go/tappd + go vet ./... + go test -v . + popd + + pushd sdk/go/ratls + go vet ./... + # Compiling is as far as this goes: the test binary links against + # libdcap_qvl, which no CI job installs (run-tests.sh and the compat + # runner don't exercise ratls either). + go build ./... + popd + + release: + needs: test + # Without a status function the condition gets an implicit `success()`, + # which is false once `test` is skipped on workflow_dispatch. + if: ${{ !cancelled() && (github.event_name == 'workflow_dispatch' || needs.test.result == 'success') }} + runs-on: ubuntu-latest + permissions: + # The GitHub Release step creates the release. + contents: write + steps: + - name: Resolve module and version + id: meta + env: + MODULE_INPUT: ${{ github.event.inputs.module }} + VERSION_INPUT: ${{ github.event.inputs.version }} + run: | + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + module="$MODULE_INPUT" + version="$VERSION_INPUT" + else + tag="${GITHUB_REF_NAME}" + case "$tag" in + sdk/go/dstack/v*) module="sdk/go/dstack" ;; + sdk/go/ratls/v*) module="sdk/go/ratls" ;; + sdk/go/v0.6.1) module="sdk/go" ;; + *) + echo "::error::unexpected tag $tag, expected sdk/go/dstack/v*, sdk/go/ratls/v*, or sdk/go/v0.6.1" + exit 1 + ;; + esac + version="v${tag##*/v}" + # sdk/go/dstack requires the package-less sdk/go v0.6.1 to defuse + # ambiguous imports for importers pinned to sdk/go v0.6.0, so that + # tag must be indexed on the proxy first. ratls does not require + # the stub and is not gated on it. + if [ "$module" = "sdk/go/dstack" ] && ! curl -fsSL --retry 3 --retry-delay 5 --retry-all-errors \ + -o /dev/null "https://proxy.golang.org/github.com/!dstack-!t!e!e/dstack/sdk/go/@v/v0.6.1.mod"; then + echo "::error::sdk/go v0.6.1 is not on the module proxy; tag sdk/go/v0.6.1 first" + exit 1 + fi + fi + if ! [[ "$version" =~ ^v[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then + echo "::error::invalid version $version" + exit 1 + fi + echo "module=$module" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + + - name: GitHub Release + if: github.event_name == 'push' + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + name: "Go SDK ${{ steps.meta.outputs.version }}" + body: | + ## Go module + + **Module**: `github.com/Dstack-TEE/dstack/${{ steps.meta.outputs.module }}` + **Version**: `${{ steps.meta.outputs.version }}` + + ```bash + go get github.com/Dstack-TEE/dstack/${{ steps.meta.outputs.module }}@${{ steps.meta.outputs.version }} + ``` + + **Docs**: https://pkg.go.dev/github.com/Dstack-TEE/dstack/${{ steps.meta.outputs.module }}@${{ steps.meta.outputs.version }} + + # pkg.go.dev and the module proxy both crawl on demand, and the crawl + # takes minutes after a tag push. A plain curl right after the release + # races the crawl and 404s. Pull the version through the proxy first + # (that request is what indexes the proxy), then poll pkg.go.dev until + # its own crawl finishes. + - name: Index the module on pkg.go.dev + run: | + module="${{ steps.meta.outputs.module }}" + module_path="github.com/Dstack-TEE/dstack/$module" + version="${{ steps.meta.outputs.version }}" + # Go module proxy escaping applies to both the path and the version: + # every uppercase letter becomes "!" + its lowercase form (BSD sed + # has no \L, so loop in bash). A raw uppercase prerelease like + # v0.6.1-RC1 is rejected by the proxy as an invalid escaped version. + escape() { + local s="$1" out="" c i + for ((i = 0; i < ${#s}; i++)); do + c="${s:i:1}" + if [[ "$c" =~ [A-Z] ]]; then + out+="!${c,,}" + else + out+="$c" + fi + done + echo "$out" + } + proxy_path=$(escape "$module_path") + proxy_version=$(escape "$version") + deadline=$((SECONDS + 240)) + until curl -fsSL --max-time 30 -o /dev/null "https://proxy.golang.org/${proxy_path}/@v/${proxy_version}.info"; do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "::error::module proxy never served ${module_path}@${version}" + exit 1 + fi + sleep 10 + done + echo "proxy serves ${module_path}@${version}" + if [ "$module" = "sdk/go" ]; then + # The package-less deprecation stub is never indexed by + # pkg.go.dev (observed: 404 for 50+ minutes while the proxy + # serves it). It only needs the proxy, where `go get` resolves + # it for importers pinned to v0.6.0. + echo "sdk/go is a package-less stub; skipping pkg.go.dev" + exit 0 + fi + deadline=$((SECONDS + 480)) + until curl -fsSL --max-time 30 -o /dev/null "https://pkg.go.dev/${module_path}@${version}"; do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "::error::pkg.go.dev never indexed ${module_path}@${version}" + exit 1 + fi + sleep 10 + done + echo "pkg.go.dev indexed ${module_path}@${version}" + # Best effort: the unversioned page can lag minutes behind the + # versioned one, and a transient error here says nothing about the + # indexing above. + curl -fsSL --max-time 30 -o /dev/null "https://pkg.go.dev/${module_path}" || \ + echo "::warning::unversioned pkg.go.dev page not refreshed yet" diff --git a/.github/workflows/guest-os.yml b/.github/workflows/guest-os.yml new file mode 100644 index 0000000000..09fdbe41e0 --- /dev/null +++ b/.github/workflows/guest-os.yml @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +# DEPRECATED: the Yocto backend is superseded by mkosi. Guest OS releases are +# built by mkosi-build.yml; this workflow is kept only to rebuild legacy images. +name: Build Guest Images (Yocto, deprecated) + +on: + workflow_dispatch: + inputs: + tag: + description: 'Tag to create and release (e.g. guest-os-v0.6.0). Leave empty to build only.' + required: false + default: '' + type: string + +jobs: + build: + runs-on: yocto-builder + timeout-minutes: 480 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Build production guest OS (deprecated Yocto backend) + run: make os-image-yocto + + - name: Upload artifacts + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: guest-images + path: | + os/yocto/repro-build/dist/*.tar.gz + os/yocto/repro-build/dist/reproduce.sh + retention-days: 30 + + release: + if: inputs.tag != '' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) + needs: build + runs-on: yocto-builder + timeout-minutes: 60 + environment: release + permissions: + contents: write + steps: + - name: Checkout default branch + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event.repository.default_branch }} + + - name: Download artifacts + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: guest-images + path: os/yocto/repro-build/dist + + - name: Validate release tag + env: + TAG: ${{ inputs.tag }} + run: | + echo "$TAG" | grep -Eq '^guest-os-v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.-]+)?$' + VERSION="${TAG#guest-os-v}" + python3 - "$VERSION" <<'PY' + import re + import sys + + match = re.match(r"^(\d+)\.(\d+)\.(\d+)", sys.argv[1]) + if not match or tuple(map(int, match.groups())) < (0, 6, 0): + raise SystemExit("guest OS versions below 0.6.0 belong in Dstack-TEE/meta-dstack") + PY + BARE="os/yocto/repro-build/dist/dstack-${VERSION}.tar.gz" + UKI="os/yocto/repro-build/dist/dstack-${VERSION}-uki.tar.gz" + test -f "$BARE" + test -f "$UKI" + + read -r IMAGE_VERSION IMAGE_REVISION < <( + tar -xOf "$BARE" "dstack-${VERSION}/metadata.json" | + python3 -c 'import json, sys; data=json.load(sys.stdin); print(data["version"], data["git_revision"])' + ) + test "$IMAGE_VERSION" = "$VERSION" + test "$IMAGE_REVISION" = "$(git rev-parse HEAD)" + tar -tzf "$UKI" | grep -Fx "dstack-${VERSION}/disk.raw" + + - name: Create tag and release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ inputs.tag }} + run: | + git tag "$TAG" + git push origin "$TAG" + gh release create "$TAG" \ + os/yocto/repro-build/dist/*.tar.gz \ + os/yocto/repro-build/dist/reproduce.sh \ + --title "$TAG" --generate-notes diff --git a/.github/workflows/halmos.yml b/.github/workflows/halmos.yml new file mode 100644 index 0000000000..5c839fc761 --- /dev/null +++ b/.github/workflows/halmos.yml @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: KMS Auth-ETH Halmos + +on: + push: + paths: + - 'dstack/kms/auth-eth/**' + - '.github/workflows/halmos.yml' + pull_request: + paths: + - 'dstack/kms/auth-eth/**' + - '.github/workflows/halmos.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + halmos: + name: ${{ matrix.contract }} + runs-on: ubuntu-latest + timeout-minutes: 40 + strategy: + fail-fast: false + matrix: + contract: + - DstackAppSymbolicTest + - DstackAppEpochSymbolicTest + - DstackKmsSymbolicTest + - DstackKmsEpochSymbolicTest + defaults: + run: + working-directory: dstack/kms/auth-eth + env: + # Halmos does not support the vm.deployCode that dynamic test linking emits. + FOUNDRY_DYNAMIC_TEST_LINKING: 'false' + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Checkout contract dependencies + working-directory: . + run: | + git submodule update --init --recursive --depth 1 -- \ + dstack/kms/auth-eth/lib/forge-std \ + dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable \ + dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@v1 + with: + version: v1.8.4 + + - name: Install Halmos + run: pipx install halmos==0.3.3 + + - name: Run Halmos + run: halmos --contract ${{ matrix.contract }} diff --git a/.github/workflows/js-sdk-release.yml b/.github/workflows/js-sdk-release.yml new file mode 100644 index 0000000000..ec4679ca08 --- /dev/null +++ b/.github/workflows/js-sdk-release.yml @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Publish JS SDK to npm +on: + push: + tags: ['js-sdk-v*'] + workflow_dispatch: + inputs: + npm_tag: + description: 'npm dist-tag (latest, beta, canary)' + required: true + default: 'latest' + type: choice + options: + - latest + - beta + - canary + +permissions: + id-token: write + contents: write + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: '20' + registry-url: 'https://registry.npmjs.org' + + - name: Upgrade npm for trusted publishers support + run: | + npm install -g npm@11.21.1 + echo "npm: $(npm --version)" + + - name: Verify OIDC token availability + run: | + if [ -n "${ACTIONS_ID_TOKEN_REQUEST_URL}" ] && [ -n "${ACTIONS_ID_TOKEN_REQUEST_TOKEN}" ]; then + echo "OIDC token available" + else + echo "OIDC token NOT available" + echo "Check workflow permissions include 'id-token: write'" + exit 1 + fi + + - name: Verify repository configuration + working-directory: sdk/js + run: | + echo "Checking repository consistency..." + GIT_REPO=$(git remote get-url origin | sed 's/.*github.com[/:]//; s/.git$//') + PKG_REPO=$(node -e "console.log(require('./package.json').repository?.url || '')" | sed 's|https://github.com/||; s|git+||; s|.git$||') + echo "Git remote: $GIT_REPO" + echo "package.json: $PKG_REPO" + if [ "$GIT_REPO" != "$PKG_REPO" ]; then + echo "Repository mismatch!" + echo "This will cause 422 error during publish" + exit 1 + fi + echo "Repositories match" + + # bun.lock is the only lockfile in sdk/js; installing from it keeps the + # dependency tree of this credentialed job fixed. `--ignore-scripts` + # because Bun otherwise runs install scripts for its default-trusted + # packages (bufferutil, utf-8-validate here), and the build needs none. + # npm is still used to publish, for trusted publishing. + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.4.4 + + - name: Install dependencies + working-directory: sdk/js + run: bun install --frozen-lockfile --ignore-scripts + + - name: Build + working-directory: sdk/js + run: bun run build + + - name: Determine version and npm dist-tag + id: tag + working-directory: sdk/js + run: | + PKG_VERSION=$(node -e "console.log(require('./package.json').version)") + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + VERSION="$PKG_VERSION" + echo "tag=${{ github.event.inputs.npm_tag }}" >> "$GITHUB_OUTPUT" + else + TAG_VERSION="${GITHUB_REF_NAME#js-sdk-v}" + if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then + echo "::error::tag version ($TAG_VERSION) does not match package.json version ($PKG_VERSION)" + exit 1 + fi + VERSION="$TAG_VERSION" + # auto-detect from git tag: js-sdk-v0.5.8-beta.1 -> beta + if echo "$VERSION" | grep -qiE '(beta|alpha|rc|preview)'; then + echo "tag=beta" >> "$GITHUB_OUTPUT" + else + echo "tag=latest" >> "$GITHUB_OUTPUT" + fi + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Publish to npm + working-directory: sdk/js + run: | + NPM_TAG="${{ steps.tag.outputs.tag }}" + echo "Publishing with dist-tag: $NPM_TAG" + npm publish --access public --provenance --tag "$NPM_TAG" + + - name: GitHub Release + if: github.event_name == 'push' + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + name: "JS SDK v${{ steps.tag.outputs.version }}" + body: | + ## npm Package + + **Package**: `@phala/dstack-sdk@${{ steps.tag.outputs.version }}` + + **Install**: `npm install @phala/dstack-sdk@${{ steps.tag.outputs.version }}` + + **Dist-tag**: `${{ steps.tag.outputs.tag }}` + + **Registry**: https://www.npmjs.com/package/@phala/dstack-sdk/v/${{ steps.tag.outputs.version }} diff --git a/.github/workflows/key-recovery-release.yml b/.github/workflows/key-recovery-release.yml new file mode 100644 index 0000000000..3974914bc9 --- /dev/null +++ b/.github/workflows/key-recovery-release.yml @@ -0,0 +1,106 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Key Recovery Release + +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the key-recovery-v prefix + required: true + type: string + push: + tags: + - 'key-recovery-v*' + +permissions: + attestations: write + id-token: write + contents: write + packages: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + steps: + - name: Parse and check version + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/key-recovery-v*) VERSION=${GITHUB_REF#refs/tags/key-recovery-v} ;; + *) echo "Expected a key-recovery-v* tag" >&2; exit 1 ;; + esac + fi + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "Version must be a valid Docker tag" >&2 + exit 1 + fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "RELEASE_TAG=key-recovery-v$VERSION" >> "$GITHUB_ENV" + + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false + + - name: Log in to GitHub Container Registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Resolve the revision to build + run: echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Build and push + id: build + uses: docker/build-push-action@ca052bb54ab0790a636c9b5f226502c73d547a25 # v5 + with: + context: dstack/tools/key-recovery + file: dstack/tools/key-recovery/Dockerfile + push: true + provenance: true + sbom: true + build-args: | + DSTACK_REV=${{ env.GIT_REV }} + tags: | + ghcr.io/dstack-tee/dstack-key-recovery:${{ env.VERSION }} + ghcr.io/dstack-tee/dstack-key-recovery:latest + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-name: ghcr.io/dstack-tee/dstack-key-recovery + subject-digest: ${{ steps.build.outputs.digest }} + push-to-registry: true + + - name: GitHub Release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + tag_name: ${{ env.RELEASE_TAG }} + name: "Key Recovery v${{ env.VERSION }}" + body: | + ## Docker Image + + **Image**: `ghcr.io/dstack-tee/dstack-key-recovery:${{ env.VERSION }}` + + **Digest (SHA256)**: `${{ steps.build.outputs.digest }}` + + **Verification**: [Verify on Sigstore](https://search.sigstore.dev/?hash=${{ steps.build.outputs.digest }}) + + Build from source: + + ```bash + docker build -f tools/key-recovery/Dockerfile -t dstack-key-recovery dstack + ``` diff --git a/.github/workflows/kms-auth-eth.yml b/.github/workflows/kms-auth-eth.yml new file mode 100644 index 0000000000..26aed2e9a3 --- /dev/null +++ b/.github/workflows/kms-auth-eth.yml @@ -0,0 +1,182 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: KMS auth-eth + +# The auth-eth webhook ships on its own cadence, separate from the KMS +# image: a `kms-auth-eth-v*` tag publishes +# ghcr.io/dstack-tee/dstack-kms-auth-eth:. Pull requests and +# pushes that touch the backend run the checks and build the image without +# pushing it. +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the kms-auth-eth-v prefix + required: true + type: string + push: + branches: [ next, 'release/**' ] + tags: + - 'kms-auth-eth-v*' + # Top-level files only: the server lives next to the Foundry project, whose + # contracts/, lib/, test/ and script/ are covered by foundry-test.yml. + paths: + - 'dstack/kms/auth-eth/*' + - '.github/workflows/kms-auth-eth.yml' + pull_request: + branches: [ next, 'release/**', 'feat/**' ] + paths: + - 'dstack/kms/auth-eth/*' + - '.github/workflows/kms-auth-eth.yml' + +permissions: + contents: read + +env: + IMAGE: ghcr.io/dstack-tee/dstack-kms-auth-eth + BACKEND_DIR: dstack/kms/auth-eth + +jobs: + check: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('kms-auth-eth-v{0}', inputs.version) || github.sha }} + persist-credentials: false + + - name: Set up Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + # Keep in step with the base image in the Dockerfile. + bun-version: 1.4.4 + # A release build must not restore a cache an untrusted run wrote. + no-cache: true + + - name: Install dependencies + working-directory: ${{ env.BACKEND_DIR }} + run: bun install --frozen-lockfile + + - name: Audit dependencies + working-directory: ${{ env.BACKEND_DIR }} + run: bun audit --audit-level=moderate + + - name: Lint + working-directory: ${{ env.BACKEND_DIR }} + run: bun run lint + + - name: Test + working-directory: ${{ env.BACKEND_DIR }} + run: bun run test:run + + image: + needs: check + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + attestations: write + id-token: write + steps: + - name: Decide whether to publish + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + VERSION= + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/kms-auth-eth-v*) VERSION=${GITHUB_REF#refs/tags/kms-auth-eth-v} ;; + esac + fi + if [ -n "$VERSION" ]; then + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "version must be a valid Docker tag" >&2 + exit 1 + fi + echo "PUBLISH=1" >> "$GITHUB_ENV" + echo "IMAGE_REF=$IMAGE:$VERSION" >> "$GITHUB_ENV" + else + echo "PUBLISH=" >> "$GITHUB_ENV" + echo "IMAGE_REF=$IMAGE:check" >> "$GITHUB_ENV" + fi + + # Manual runs rebuild an existing release tag, not the selected branch. + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && format('kms-auth-eth-v{0}', inputs.version) || github.sha }} + persist-credentials: false + + - name: Resolve the revision to build + run: | + echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + echo "SOURCE_DATE_EPOCH=$(git show -s --format=%ct HEAD)" >> "$GITHUB_ENV" + + - name: Log in to GitHub Container Registry + if: env.PUBLISH == '1' + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + with: + driver-opts: image=moby/buildkit:v0.20.2@sha256:c457984bd29f04d6acc90c8d9e717afe3922ae14665f3187e0096976fe37b1c8 + + - name: Build and push Docker image + id: build + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6 + with: + context: ${{ env.BACKEND_DIR }} + platforms: linux/amd64 + outputs: type=image,push=${{ env.PUBLISH == '1' }},oci-mediatypes=true,rewrite-timestamp=true + provenance: false + tags: ${{ env.IMAGE_REF }} + build-args: | + GIT_REV=${{ env.GIT_REV }} + SOURCE_DATE_EPOCH=${{ env.SOURCE_DATE_EPOCH }} + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.revision=${{ env.GIT_REV }} + org.opencontainers.image.description=dstack KMS auth webhook backed by the DstackKms contract + + - name: Verify anonymous pull access + if: env.PUBLISH == '1' + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + run: | + token=$(curl -fsSL \ + "https://ghcr.io/token?scope=repository:dstack-tee/dstack-kms-auth-eth:pull" \ + | jq -er .token) + curl -fsSL -o /dev/null \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json" \ + "https://ghcr.io/v2/dstack-tee/dstack-kms-auth-eth/manifests/$IMAGE_DIGEST" + + - name: Generate artifact attestation + if: env.PUBLISH == '1' + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-name: ${{ env.IMAGE }} + subject-digest: ${{ steps.build.outputs.digest }} + push-to-registry: true + + - name: Summarize + if: env.PUBLISH == '1' + env: + IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + run: | + { + echo "**Image**: \`$IMAGE_REF\`" + echo + echo "**Pinned**: \`$IMAGE@$IMAGE_DIGEST\`" + echo + echo "**Revision**: \`$GIT_REV\`" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/kms-release.yml b/.github/workflows/kms-release.yml new file mode 100644 index 0000000000..b1ad81a439 --- /dev/null +++ b/.github/workflows/kms-release.yml @@ -0,0 +1,155 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: KMS Release + +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the kms-v prefix + required: true + type: string + push: + tags: + - 'kms-v*' +permissions: + attestations: write + id-token: write + contents: write + packages: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + steps: + - name: Parse and check version + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/kms-v*) VERSION=${GITHUB_REF#refs/tags/kms-v} ;; + *) echo "Expected a kms-v* tag" >&2; exit 1 ;; + esac + fi + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "Version must be a valid Docker tag" >&2 + exit 1 + fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "RELEASE_TAG=kms-v$VERSION" >> "$GITHUB_ENV" + + - name: Reclaim runner disk space + run: | + sudo rm -rf \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /usr/local/.ghcup \ + /usr/local/lib/android \ + /usr/share/dotnet + df -h / + + # Manual runs rebuild an existing release tag, not the selected branch. + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false + + - name: Checkout contract dependencies + run: | + git submodule update --init --recursive --depth 1 -- \ + dstack/kms/auth-eth/lib/forge-std \ + dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable \ + dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades + + - name: Log in to GitHub Container Registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Resolve the revision to build + run: echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + # Release images are built through the same script contributors run by + # hand, so a published image can be reproduced and checked digest-for-digest. + # See the builder README for the reproduction recipe. + - name: Build and push Docker image + id: build-and-push + env: + PUSH: "1" + METADATA_FILE: ${{ runner.temp }}/build-metadata.json + GIT_REV: ${{ env.GIT_REV }} + IMAGE_VERSION: ${{ env.VERSION }} + IMAGE_NAME: ghcr.io/dstack-tee/dstack-kms:${{ env.VERSION }} + IMAGE_SOURCE_URL: ${{ github.server_url }}/${{ github.repository }} + DSTACK_SRC_URL: ${{ github.server_url }}/${{ github.repository }}.git + run: | + dstack/kms/dstack-app/builder/build-image.sh \ + "$IMAGE_NAME" + digest=$(jq -r '."containerimage.digest"' "$METADATA_FILE") + if [ -z "$digest" ] || [ "$digest" = null ]; then + echo "the build did not report an image digest" >&2 + exit 1 + fi + echo "digest=$digest" >> "$GITHUB_OUTPUT" + + - name: Verify anonymous pull access + env: + IMAGE_DIGEST: ${{ steps.build-and-push.outputs.digest }} + run: | + token=$(curl -fsSL \ + "https://ghcr.io/token?scope=repository:dstack-tee/dstack-kms:pull" \ + | jq -er .token) + curl -fsSL -o /dev/null \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json" \ + "https://ghcr.io/v2/dstack-tee/dstack-kms/manifests/$IMAGE_DIGEST" + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-name: "ghcr.io/dstack-tee/dstack-kms" + subject-digest: ${{ steps.build-and-push.outputs.digest }} + push-to-registry: true + + - name: Install Foundry + uses: foundry-rs/foundry-toolchain@908c540300062bd5a7e473851cdb4282204cee09 # v1 + + - name: Compile contracts with Foundry + run: | + cd dstack/kms/auth-eth + forge build + + - name: GitHub Release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + tag_name: ${{ env.RELEASE_TAG }} + target_commitish: ${{ env.GIT_REV }} + name: "KMS Release v${{ env.VERSION }}" + files: | + dstack/kms/auth-eth/out/DstackKms.sol/DstackKms.json + dstack/kms/auth-eth/out/DstackApp.sol/DstackApp.json + body: | + ## Docker Image Information + + **Image**: `ghcr.io/dstack-tee/dstack-kms:${{ env.VERSION }}` + + **Digest (SHA256)**: `${{ steps.build-and-push.outputs.digest }}` + + **Verification**: [Verify on Sigstore](https://search.sigstore.dev/?hash=${{ steps.build-and-push.outputs.digest }}) + + ## Contract ABIs + + This release includes the compiled contract ABIs: + - `DstackKms.json` - Main KMS contract ABI + - `DstackApp.json` - Application contract ABI diff --git a/.github/workflows/lean.yml b/.github/workflows/lean.yml new file mode 100644 index 0000000000..ea25f71e7f --- /dev/null +++ b/.github/workflows/lean.yml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Lean proofs + +on: + push: + branches: [ next, 'release/**' ] + paths: [ 'formal/**', '.github/workflows/lean.yml' ] + pull_request: + branches: [ next, 'release/**', 'feat/**' ] + paths: [ 'formal/**', '.github/workflows/lean.yml' ] + +permissions: + contents: read + +jobs: + build: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Reject axioms and unchecked code + run: "! grep -rnE '^\\s*(axiom|unsafe|@\\[implemented_by|@\\[extern)|native_decide' --include='*.lean' formal" + + - uses: leanprover/lean-action@v1 + with: + lake-package-directory: formal diff --git a/.github/workflows/local-key-provider-release.yml b/.github/workflows/local-key-provider-release.yml new file mode 100644 index 0000000000..8372b9acd6 --- /dev/null +++ b/.github/workflows/local-key-provider-release.yml @@ -0,0 +1,141 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Local Key Provider Release + +on: + workflow_dispatch: + inputs: + version: + description: Release version without the local-key-provider-v prefix + required: true + type: string + push: + tags: + - 'local-key-provider-v*' + +permissions: + attestations: write + id-token: write + contents: write + packages: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + steps: + - name: Parse and check version + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/local-key-provider-v*) VERSION=${GITHUB_REF#refs/tags/local-key-provider-v} ;; + *) echo "Expected a local-key-provider-v* tag" >&2; exit 1 ;; + esac + fi + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "Version must be a valid Docker tag" >&2 + exit 1 + fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "RELEASE_TAG=local-key-provider-v$VERSION" >> "$GITHUB_ENV" + + # Manual runs rebuild an existing release tag, not the selected branch. + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false + + - name: Log in to GitHub Container Registry + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + + - name: Resolve the revision to build + run: echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + - name: Build and push Docker image + id: build-and-push + uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 + with: + context: dstack + file: dstack/local-key-provider/build/Dockerfile.key-provider + push: true + tags: ghcr.io/dstack-tee/local-key-provider:${{ env.VERSION }} + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.revision=${{ env.GIT_REV }} + org.opencontainers.image.version=${{ env.VERSION }} + platforms: linux/amd64 + provenance: false + + - name: Verify anonymous pull access + env: + IMAGE_DIGEST: ${{ steps.build-and-push.outputs.digest }} + run: | + token=$(curl -fsSL \ + "https://ghcr.io/token?scope=repository:dstack-tee/local-key-provider:pull" \ + | jq -er .token) + curl -fsSL -o /dev/null \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json" \ + "https://ghcr.io/v2/dstack-tee/local-key-provider/manifests/$IMAGE_DIGEST" + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4 + with: + subject-name: "ghcr.io/dstack-tee/local-key-provider" + subject-digest: ${{ steps.build-and-push.outputs.digest }} + push-to-registry: true + + - name: Export enclave measurements + env: + IMAGE_DIGEST: ${{ steps.build-and-push.outputs.digest }} + IMAGE_NAME: ghcr.io/dstack-tee/local-key-provider + run: | + docker pull "${IMAGE_NAME}@${IMAGE_DIGEST}" + docker run --rm \ + --entrypoint gramine-sgx-sigstruct-view \ + "${IMAGE_NAME}@${IMAGE_DIGEST}" \ + --output-format json \ + /dstack/local-key-provider/build/local-key-provider.sig \ + | tee local-key-provider.sig.json + + MRENCLAVE=$(jq -er .mr_enclave local-key-provider.sig.json) + MRSIGNER=$(jq -er .mr_signer local-key-provider.sig.json) + echo "MRENCLAVE=$MRENCLAVE" >> "$GITHUB_ENV" + echo "MRSIGNER=$MRSIGNER" >> "$GITHUB_ENV" + + - name: GitHub Release + uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3 + with: + name: "Local Key Provider Release v${{ env.VERSION }}" + tag_name: ${{ env.RELEASE_TAG }} + target_commitish: ${{ env.GIT_REV }} + files: local-key-provider.sig.json + body: | + ## Docker Image Information + + **Image**: `ghcr.io/dstack-tee/local-key-provider:${{ env.VERSION }}` + + **Digest (SHA256)**: `${{ steps.build-and-push.outputs.digest }}` + + **MRENCLAVE**: `${{ env.MRENCLAVE }}` + + **MRSIGNER**: `${{ env.MRSIGNER }}` + + **Verification**: [Verify on Sigstore](https://search.sigstore.dev/?hash=${{ steps.build-and-push.outputs.digest }}) + + The enclave signing key is generated for each build. Pin the + release's image digest and MRENCLAVE rather than expecting MRSIGNER + to remain stable across releases. diff --git a/.github/workflows/mkosi-build.yml b/.github/workflows/mkosi-build.yml new file mode 100644 index 0000000000..5c23ea147d --- /dev/null +++ b/.github/workflows/mkosi-build.yml @@ -0,0 +1,435 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Build Guest Images (mkosi) + +# Publishing is bound to the tag, not to a workflow input: pushing +# mkosi-os-v is the only event that creates a GitHub Release. Every +# other trigger builds and reports the hashes without publishing anything, so a +# dry run can never be mistaken for a release. +on: + workflow_dispatch: + inputs: + repro_check: + description: 'Build twice with different job counts and compare byte-for-byte (roughly doubles the run time)' + required: false + default: false + type: boolean + pull_request: + paths: + - 'os/**' + - '.github/workflows/mkosi-build.yml' + # No paths filter here on purpose. GitHub ANDs the path filter with the ref + # filter, so a release tag placed on a commit that happens not to touch os/** + # would be silently dropped. The static job costs seconds and the image build + # is gated by its own `if`, so an unfiltered push trigger is cheap. + push: + branches: [next, 'release/**'] + tags: ['mkosi-os-v*'] + +concurrency: + group: mkosi-build-${{ github.ref }} + # A release build must never be cancelled by a later push. + cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }} + +jobs: + static: + name: Static contract + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + # Runs in seconds and covers the whole os/mkosi static contract, so it + # gates every change rather than waiting for a manual dispatch. + - name: Check the static contract + run: ./os/mkosi/build.sh lint + + build: + name: Build guest images + # The full image build takes ~40 minutes, so keep it off the PR path. + if: >- + github.event_name == 'workflow_dispatch' || + startsWith(github.ref, 'refs/tags/mkosi-os-v') + needs: static + runs-on: ubuntu-latest + timeout-minutes: 360 + permissions: + contents: read + outputs: + version: ${{ steps.hashes.outputs.version }} + os_image_hash: ${{ steps.hashes.outputs.os_image_hash }} + bare_sha256: ${{ steps.hashes.outputs.bare_sha256 }} + uki_sha256: ${{ steps.hashes.outputs.uki_sha256 }} + kernel_devel_sha256: ${{ steps.hashes.outputs.kernel_devel_sha256 }} + mrtd: ${{ steps.hashes.outputs.mrtd }} + uki_auth: ${{ steps.hashes.outputs.uki_auth }} + aws_pcr: ${{ steps.hashes.outputs.aws_pcr }} + + steps: + # GitHub-hosted runners have enough CPU and memory for this build, but + # their preinstalled SDKs consume most of the available disk. Remove only + # those unused SDKs before checkout; the OS build itself remains hermetic. + - name: Reclaim runner disk space + run: | + sudo rm -rf \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /usr/local/.ghcup \ + /usr/local/lib/android \ + /usr/local/share/boost \ + /usr/share/dotnet + df -h / + + # Check out the dispatched ref, not a hardcoded revision. Pinning a + # revision here meant the job could never validate the branch it ran on, + # and the pinned commit becomes unreachable once the branch is squashed + # or rebased, which would break the job outright. + - name: Checkout + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Python for mkosi + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: '3.13' + + - name: Install pinned mkosi + run: | + set -euo pipefail + # Take the revision from versions.env so CI and the container builder + # in os/mkosi/repro-build cannot drift onto different mkosi builds. + # shellcheck source=/dev/null + source os/mkosi/versions.env + python3 -m venv "$RUNNER_TEMP/mkosi-venv" + "$RUNNER_TEMP/mkosi-venv/bin/pip" install --disable-pip-version-check \ + "mkosi @ git+https://github.com/systemd/mkosi.git@${MKOSI_REVISION}" + echo "$RUNNER_TEMP/mkosi-venv/bin" >> "$GITHUB_PATH" + + - name: Install mkosi host dependencies + run: | + mapfile -t dependencies < <(mkosi --directory os/mkosi dependencies) + sudo apt-get update + sudo apt-get install --yes --no-install-recommends "${dependencies[@]}" + + - name: Build guest images + id: build + env: + # ubuntu-latest currently provides four vCPUs and 16 GiB of RAM. + # Do not oversubscribe either the CPU or compiler memory. + JOBS: '4' + REPRO_CHECK: ${{ inputs.repro_check }} + run: | + set -euo pipefail + # GitHub-hosted Ubuntu runners restrict unprivileged user namespaces. + # Run mkosi as root instead of weakening the runner's AppArmor policy. + # Keep setup-python out of the build PATH because Ubuntu's lddtree + # expects the distro Python and its python3-pyelftools module. + ci_bin="$RUNNER_TEMP/mkosi-ci-bin" + mkdir -p "$ci_bin" + ln -s "$(command -v mkosi)" "$ci_bin/mkosi" + build_dir="$RUNNER_TEMP/mkosi-build" + if [ "$REPRO_CHECK" = "true" ]; then + # repro-check builds prod twice with different job counts and + # compares the release tarballs byte for byte. It leaves leg a in + # $build_dir/a, which is the same release contract as `image`. + action=repro-check + dist_dir="$build_dir/a" + else + action=image + dist_dir="$build_dir/out/prod" + fi + # A release build never reuses the component cache. The runner is + # fresh, so this costs nothing here, but it keeps the published + # artifacts a product of the cold path the repro check verifies. + sudo --set-home env \ + "PATH=$ci_bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" \ + "JOBS=$JOBS" \ + ./os/mkosi/build.sh --no-cache "$action" "$build_dir" + sudo chown -R "$USER:$USER" "$build_dir" + echo "dist_dir=$dist_dir" >> "$GITHUB_OUTPUT" + df -h / + + - name: Build dstack-mr + # Only needed to decode the measurement CBOR for the report below. The + # image build produces its own copy under a scratch directory that + # mkosi.postoutput deletes, and this target directory stays outside the + # work tree so it cannot perturb a later source-tree build. + env: + CARGO_TARGET_DIR: ${{ runner.temp }}/dstack-mr-target + run: | + set -euo pipefail + # Take the toolchain from versions.env rather than pinning it again + # here, so this stays the same rustc the image build itself used. + # shellcheck source=/dev/null + source os/mkosi/versions.env + rustup toolchain install "$RUST_TOOLCHAIN_VERSION" --profile minimal + cargo "+$RUST_TOOLCHAIN_VERSION" build --release --locked \ + --manifest-path dstack/Cargo.toml -p dstack-mr + + - name: Report image hashes + id: hashes + env: + DIST_DIR: ${{ steps.build.outputs.dist_dir }} + DSTACK_MR: ${{ runner.temp }}/dstack-mr-target/release/dstack-mr + run: | + set -euo pipefail + # shellcheck source=/dev/null + source os/mkosi/versions.env + version="$DSTACK_VERSION" + bare="$DIST_DIR/dstack-$version.tar.gz" + uki="$DIST_DIR/dstack-$version-uki.tar.gz" + test -f "$bare" + test -f "$uki" + + # Read the identity out of the published tarball rather than the + # staging tree beside it, so the reported hashes describe exactly what + # ships. + work=$(mktemp -d) + tar -xzf "$bare" -C "$work" + img="$work/dstack-$version" + os_image_hash=$(cat "$img/digest.txt") + + # digest.txt is the release's claim; recompute it. os_image_hash is + # sha256(sha256sum.txt), the identity registered on chain and enforced + # by dstack-kms, so a mismatch here is a corrupt release. + computed=$(sha256sum "$img/sha256sum.txt" | awk '{print $1}') + if [ "$os_image_hash" != "$computed" ]; then + echo "::error::digest.txt says $os_image_hash but sha256sum.txt hashes to $computed" + exit 1 + fi + # Both packages describe one image and must carry one identity. + uki_digest=$(tar -xOf "$uki" "dstack-$version/digest.txt") + if [ "$uki_digest" != "$os_image_hash" ]; then + echo "::error::UKI package digest $uki_digest does not match bare-metal $os_image_hash" + exit 1 + fi + + bare_sha256=$(sha256sum "$bare" | awk '{print $1}') + uki_sha256=$(sha256sum "$uki" | awk '{print $1}') + kernel_devel_sha256=$(sha256sum "$DIST_DIR/dstack-$version-kernel-devel.tar.gz" | awk '{print $1}') + git_revision=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["git_revision"])' "$img/metadata.json") + mrtd=$("$DSTACK_MR" inspect-measurement "$img/measurement.tdx.cbor" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["tdvf"]["mrtd"]["single_pass"])') + uki_auth=$("$DSTACK_MR" inspect-measurement "$img/measurement.gcp.cbor" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["uki_auth"])') + aws_pcr=$("$DSTACK_MR" inspect-measurement "$img/measurement.aws.cbor" \ + | python3 -c 'import json,sys; print(json.load(sys.stdin)["boot_pcr_digest"])') + + { + echo "version=$version" + echo "os_image_hash=$os_image_hash" + echo "bare_sha256=$bare_sha256" + echo "uki_sha256=$uki_sha256" + echo "kernel_devel_sha256=$kernel_devel_sha256" + echo "mrtd=$mrtd" + echo "uki_auth=$uki_auth" + echo "aws_pcr=$aws_pcr" + } >> "$GITHUB_OUTPUT" + + # os_image_hash is the value operators need most, so surface it in the + # log, in the job summary, and as a downloadable record. + echo "::notice title=os_image_hash::$os_image_hash" + { + echo "### dstack guest OS \`$version\` (mkosi backend)" + echo + echo '| Field | Value |' + echo '| --- | --- |' + echo "| \`os_image_hash\` | \`$os_image_hash\` |" + echo "| Git revision | \`$git_revision\` |" + echo "| TDX \`MRTD\` | \`$mrtd\` |" + echo "| GCP \`uki_auth\` | \`$uki_auth\` |" + echo "| AWS \`boot_pcr_digest\` | \`$aws_pcr\` |" + echo "| \`dstack-$version.tar.gz\` | \`$bare_sha256\` |" + echo "| \`dstack-$version-uki.tar.gz\` | \`$uki_sha256\` |" + echo "| \`dstack-$version-kernel-devel.tar.gz\` | \`$kernel_devel_sha256\` |" + echo + echo '
sha256sum.txt (os_image_hash preimage)' + echo + echo '```' + cat "$img/sha256sum.txt" + echo '```' + echo + echo '
' + echo + echo '
metadata.json' + echo + echo '```json' + cat "$img/metadata.json" + echo '```' + echo + echo '
' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload guest images + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: mkosi-guest-images + path: ${{ steps.build.outputs.dist_dir }}/dstack-*.tar.gz + retention-days: 30 + if-no-files-found: error + + kernel-builder: + name: Kernel module builder image + if: >- + github.event_name == 'workflow_dispatch' || + startsWith(github.ref, 'refs/tags/mkosi-os-v') + needs: build + runs-on: ubuntu-latest + timeout-minutes: 30 + permissions: + contents: read + packages: write + + steps: + - name: Checkout + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Download guest images + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: mkosi-guest-images + path: dist + + - name: Build the builder image + env: + VERSION: ${{ needs.build.outputs.version }} + run: | + owner=$(echo "$GITHUB_REPOSITORY_OWNER" | tr '[:upper:]' '[:lower:]') + echo "IMAGE=ghcr.io/$owner/dstack-kernel-builder:$VERSION" >> "$GITHUB_ENV" + GIT_REVISION="$GITHUB_SHA" ./os/image/kernel-builder/build.sh \ + "dist/dstack-$VERSION-kernel-devel.tar.gz" "ghcr.io/$owner/dstack-kernel-builder:$VERSION" + + - name: Log in to GitHub Container Registry + if: startsWith(github.ref, 'refs/tags/mkosi-os-v') + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Push the builder image + if: startsWith(github.ref, 'refs/tags/mkosi-os-v') + run: docker push "$IMAGE" + + release: + name: Publish release + # The tag is the publish decision. Nothing else reaches this job. + if: startsWith(github.ref, 'refs/tags/mkosi-os-v') + needs: [build, kernel-builder] + runs-on: ubuntu-latest + timeout-minutes: 30 + environment: release + permissions: + contents: write + + steps: + - name: Checkout + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Download guest images + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: mkosi-guest-images + path: dist + + - name: Validate the release tag against the built image + env: + TAG: ${{ github.ref_name }} + OS_IMAGE_HASH: ${{ needs.build.outputs.os_image_hash }} + run: | + set -euo pipefail + echo "$TAG" | grep -Eq '^mkosi-os-v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.-]+)?$' + version="${TAG#mkosi-os-v}" + # shellcheck source=/dev/null + source os/mkosi/versions.env + if [ "$version" != "$DSTACK_VERSION" ]; then + echo "::error::tag $TAG does not match DSTACK_VERSION=$DSTACK_VERSION in os/mkosi/versions.env" + exit 1 + fi + bare="dist/dstack-$version.tar.gz" + uki="dist/dstack-$version-uki.tar.gz" + test -f "$bare" + test -f "$uki" + + read -r image_version image_revision < <( + tar -xOf "$bare" "dstack-$version/metadata.json" | + python3 -c 'import json, sys; d=json.load(sys.stdin); print(d["version"], d["git_revision"])' + ) + test "$image_version" = "$version" + # A release must be reproducible from the tagged tree, so the revision + # baked into the measured metadata.json has to be the tagged commit. + # build.sh appends -modified when it builds a dirty work tree, which + # this equality also rejects. + if [ "$image_revision" != "$GITHUB_SHA" ]; then + echo "::error::image was built from $image_revision but the tag points at $GITHUB_SHA" + exit 1 + fi + # The UKI package is the GCP/AWS delivery path; assert its payload. + tar -tzf "$uki" | grep -Fx "dstack-$version/disk.raw" + test "$(tar -xOf "$bare" "dstack-$version/digest.txt")" = "$OS_IMAGE_HASH" + + - name: Create the release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ github.ref_name }} + VERSION: ${{ needs.build.outputs.version }} + OS_IMAGE_HASH: ${{ needs.build.outputs.os_image_hash }} + BARE_SHA256: ${{ needs.build.outputs.bare_sha256 }} + UKI_SHA256: ${{ needs.build.outputs.uki_sha256 }} + KERNEL_DEVEL_SHA256: ${{ needs.build.outputs.kernel_devel_sha256 }} + MRTD: ${{ needs.build.outputs.mrtd }} + UKI_AUTH: ${{ needs.build.outputs.uki_auth }} + AWS_PCR: ${{ needs.build.outputs.aws_pcr }} + run: | + set -euo pipefail + { + echo "Guest OS image \`$VERSION\`, built by the Debian/mkosi backend." + echo + echo "Register \`os_image_hash\` on chain to authorize this image; see" + echo "[docs/onchain-governance.md](https://github.com/${GITHUB_REPOSITORY}/blob/${TAG}/docs/onchain-governance.md)." + echo + echo '| Field | Value |' + echo '| --- | --- |' + echo "| \`os_image_hash\` | \`$OS_IMAGE_HASH\` |" + echo "| Git revision | \`$GITHUB_SHA\` |" + echo "| TDX \`MRTD\` | \`$MRTD\` |" + echo "| GCP \`uki_auth\` | \`$UKI_AUTH\` |" + echo "| AWS \`boot_pcr_digest\` | \`$AWS_PCR\` |" + echo "| \`dstack-$VERSION.tar.gz\` | \`$BARE_SHA256\` |" + echo "| \`dstack-$VERSION-uki.tar.gz\` | \`$UKI_SHA256\` |" + echo "| \`dstack-$VERSION-kernel-devel.tar.gz\` | \`$KERNEL_DEVEL_SHA256\` |" + echo + echo "To build out-of-tree kernel modules, use" + echo "\`ghcr.io/dstack-tee/dstack-kernel-builder:$VERSION\`; see" + echo "[docs/building-guest-os.md](https://github.com/${GITHUB_REPOSITORY}/blob/${TAG}/docs/building-guest-os.md#kernel-headers-for-out-of-tree-modules)." + } > release-notes.md + # --verify-tag: the tag is the publish trigger, so it must already + # exist. This job never creates one. + # + # --prerelease is kept until release maintainers promote a stable + # mkosi-built release. os/mkosi is the default backend and Yocto is + # deprecated, but dropping the flag is a release decision, not a + # backend-status one. + # + # The title names the product, not the build backend: the tag prefix + # only exists to keep this workflow's trigger distinct from the + # deprecated Yocto one, and it should not leak into the release listing. + gh release create "$TAG" \ + "dist/dstack-$VERSION.tar.gz" \ + "dist/dstack-$VERSION-uki.tar.gz" \ + "dist/dstack-$VERSION-kernel-devel.tar.gz" \ + --title "dstack OS v$VERSION" \ + --notes-file release-notes.md \ + --verify-tag \ + --prerelease diff --git a/.github/workflows/plumber-check.yml b/.github/workflows/plumber-check.yml new file mode 100644 index 0000000000..fdb972a012 --- /dev/null +++ b/.github/workflows/plumber-check.yml @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: © 2026 Thibaud Van den Berghe +# +# SPDX-License-Identifier: Apache-2.0 + +name: Plumber check + +# Checks the workflows themselves: token scopes, checkouts that keep the +# token, action references and the lockfile. Not a required status check, so +# a workflow-level filter is safe here: what it reads cannot change unless +# something under `.github/` or the Plumber configuration does. +on: + push: + branches: [ next ] + paths: + - '.github/**' + - '.plumber.yaml' + pull_request: + branches: [ next ] + paths: + - '.github/**' + - '.plumber.yaml' + +permissions: + contents: read + +jobs: + plumber: + runs-on: ubuntu-latest + permissions: + contents: read + # Workflow states and one run log, to prove each job's token scope. + actions: read + # Lists the findings under code scanning. + security-events: write + # Needed by score-push, no secret or token to store. + id-token: write + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Run Plumber + uses: getplumber/plumber@v0.7.23 + with: + # Pull requests from forks get a read-only token, so the code + # scanning upload is skipped there. The report stays a workflow + # artifact. + upload-sarif: ${{ github.event.pull_request.head.repo.fork != true }} + # Fail under 85 points. The default gate is 100, where any finding + # fails. + min-points: 85 + # Publish the score and the repository name on score.getplumber.io, + # where the README badge reads them. Only pushes to next publish, a + # pull request never does. + score-push: ${{ github.event_name == 'push' }} diff --git a/.github/workflows/prek-check.yml b/.github/workflows/prek-check.yml new file mode 100644 index 0000000000..6f42422305 --- /dev/null +++ b/.github/workflows/prek-check.yml @@ -0,0 +1,65 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Prek checks + +on: + push: + branches: [ next, 'release/**' ] + pull_request: + branches: [ next, 'release/**', 'feat/**' ] + +permissions: + contents: read + +jobs: + prek: + runs-on: ubuntu-latest + env: + RUSTUP_TOOLCHAIN: 1.92.0 + + steps: + - uses: actions/checkout@v5 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + components: rustfmt + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version: '1.22' + + - name: Install prek + run: pip install prek + + - name: Run prek checks (PR) + if: github.event_name == 'pull_request' + run: prek run --from-ref ${{ github.event.pull_request.base.sha }} --to-ref ${{ github.event.pull_request.head.sha }} --show-diff-on-failure + + - name: Run prek checks (push) + if: github.event_name == 'push' + env: + BEFORE: ${{ github.event.before }} + AFTER: ${{ github.event.after }} + run: | + # A push that creates a branch reports an all-zero "before", and a + # force-push can name one this clone no longer has. Neither is a commit, + # so the range would be invalid; check every file instead. + if git rev-parse --verify --quiet "$BEFORE^{commit}" >/dev/null; then + prek run --from-ref "$BEFORE" --to-ref "$AFTER" --show-diff-on-failure + else + echo "no usable base commit ($BEFORE); checking all files" + prek run --all-files --show-diff-on-failure + fi diff --git a/.github/workflows/python-sdk-release.yml b/.github/workflows/python-sdk-release.yml new file mode 100644 index 0000000000..5fc1e19f00 --- /dev/null +++ b/.github/workflows/python-sdk-release.yml @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Publish Python SDK to PyPI +on: + push: + tags: ['python-sdk-v*'] + workflow_dispatch: + inputs: + target: + description: 'Publish target' + required: true + default: 'pypi' + type: choice + options: + - pypi + - testpypi + +permissions: + id-token: write + contents: write + +jobs: + publish: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.11' + + # Build with the pinned, hash-checked backend alone: pdm-backend has no + # dependencies on Python >= 3.10, so nothing else is resolved in this + # credentialed job. + - name: Install build backend + run: | + echo 'pdm-backend==2.5.0 --hash=sha256:5b8746b567a16a1fd506ce66ee28e89d46374526f52238aa1b96cc2c08245c63' > "$RUNNER_TEMP/build-requirements.txt" + pip install --require-hashes --no-deps -r "$RUNNER_TEMP/build-requirements.txt" + + - name: Build distribution + working-directory: sdk/python + run: python -c "from pdm.backend import build_sdist, build_wheel; build_sdist('dist'); build_wheel('dist')" + + - name: Parse and verify version + id: version + working-directory: sdk/python + run: | + PKG_VERSION=$(python -c " + import re + with open('pyproject.toml') as f: + m = re.search(r'^version\s*=\s*\"([^\"]+)\"', f.read(), re.M) + print(m.group(1) if m else '') + ") + if [ -z "$PKG_VERSION" ]; then + echo "::error::failed to parse version from pyproject.toml" + exit 1 + fi + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + VERSION="$PKG_VERSION" + else + TAG_VERSION="${GITHUB_REF_NAME#python-sdk-v}" + if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then + echo "::error::tag version ($TAG_VERSION) does not match pyproject.toml version ($PKG_VERSION)" + exit 1 + fi + VERSION="$TAG_VERSION" + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Publish to PyPI + if: github.event_name == 'push' || github.event.inputs.target == 'pypi' + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + packages-dir: sdk/python/dist + + - name: Publish to TestPyPI + if: github.event_name == 'workflow_dispatch' && github.event.inputs.target == 'testpypi' + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + repository-url: https://test.pypi.org/legacy/ + packages-dir: sdk/python/dist + + - name: GitHub Release + if: github.event_name == 'push' + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + name: "Python SDK v${{ steps.version.outputs.version }}" + body: | + ## PyPI Package + + **Package**: `dstack-sdk ${{ steps.version.outputs.version }}` + + **Install**: `pip install dstack-sdk==${{ steps.version.outputs.version }}` + + **Registry**: https://pypi.org/project/dstack-sdk/${{ steps.version.outputs.version }}/ diff --git a/.github/workflows/qemu-acpi-differential.yml b/.github/workflows/qemu-acpi-differential.yml new file mode 100644 index 0000000000..5dae1c9631 --- /dev/null +++ b/.github/workflows/qemu-acpi-differential.yml @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# SPDX-License-Identifier: Apache-2.0 + +name: QEMU ACPI differential tests + +on: + pull_request: + branches: [next] + paths: + - .github/workflows/qemu-acpi-differential.yml + - dstack/crates/qemu-acpi/** + workflow_dispatch: + inputs: + seed: + description: Random seed accepted by Python int(value, 0) + required: false + type: string + cases: + description: Number of random cases in addition to boundary cases + required: false + default: "32" + type: string + +permissions: + contents: read + +jobs: + differential: + runs-on: ubuntu-latest + timeout-minutes: 20 + defaults: + run: + working-directory: dstack + env: + REFERENCE_IMAGE: kvin/dstack-acpi-tables@sha256:54e692d8c68c6f02dd7c655bf6de6e7f3ad7a43fded6ca00d8e998918108a3b4 + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + + - name: Build Rust ACPI generator + run: cargo build -p qemu-acpi --example dump + + - name: Run boundary and seeded random differential tests + env: + INPUT_SEED: ${{ inputs.seed }} + INPUT_CASES: ${{ inputs.cases }} + run: | + seed="${INPUT_SEED:-0x$(git rev-parse --short=16 HEAD)}" + cases="${INPUT_CASES:-32}" + echo "ACPI differential seed: $seed" + echo "Random case count: $cases" + crates/qemu-acpi/scripts/differential-random.py \ + --image "$REFERENCE_IMAGE" \ + --rust-dump target/debug/examples/dump \ + --seed "$seed" \ + --cases "$cases" \ + --failure-dir qemu-acpi-failure + + - name: Upload failing blobs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: qemu-acpi-differential-failure + path: dstack/qemu-acpi-failure + if-no-files-found: ignore diff --git a/.github/workflows/rust-sdk-release.yml b/.github/workflows/rust-sdk-release.yml new file mode 100644 index 0000000000..96127c21b5 --- /dev/null +++ b/.github/workflows/rust-sdk-release.yml @@ -0,0 +1,101 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Publish SDK to crates.io + +on: + push: + tags: ['dstack-sdk-v*'] + +jobs: + publish: + runs-on: ubuntu-latest + environment: sdk-release + permissions: + id-token: write + contents: write + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Extract version from tag + id: ver + run: | + tag="${GITHUB_REF_NAME}" + version="${tag#dstack-sdk-v}" + if [[ -z "$version" || "$version" == "$tag" ]]; then + echo "::error::tag '$tag' does not start with 'dstack-sdk-v'" + exit 1 + fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "Publishing version: $version" + + - name: Verify Cargo.toml versions match tag + env: + VERSION: ${{ steps.ver.outputs.version }} + run: | + python3 <<'PY' + import os, sys, tomllib + + want = os.environ["VERSION"] + + def pkg_version(path): + with open(path, "rb") as f: + return tomllib.load(f)["package"]["version"] + + def ws_dep_version(path, name): + with open(path, "rb") as f: + dep = tomllib.load(f)["workspace"]["dependencies"][name] + return dep["version"] if isinstance(dep, dict) else dep + + checks = [ + ("sdk/rust/types/Cargo.toml [package.version]", + pkg_version("sdk/rust/types/Cargo.toml")), + ("sdk/rust/Cargo.toml [package.version]", + pkg_version("sdk/rust/Cargo.toml")), + ("sdk/rust/Cargo.toml [workspace.dependencies.dstack-sdk-types.version]", + ws_dep_version("sdk/rust/Cargo.toml", "dstack-sdk-types")), + ] + + fail = False + for label, got in checks: + ok = got == want + fail = fail or not ok + print(f" {'OK ' if ok else 'BAD'} {label}: {got}") + + if fail: + print(f"\ntag is dstack-sdk-v{want}; bump SDK package versions to {want} before tagging.", + file=sys.stderr) + sys.exit(1) + PY + + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 + id: auth + + - name: Publish dstack-sdk-types + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + VERSION: ${{ steps.ver.outputs.version }} + run: .github/scripts/cargo-publish-idempotent.sh dstack-sdk-types + + - name: Publish dstack-sdk + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + VERSION: ${{ steps.ver.outputs.version }} + run: .github/scripts/cargo-publish-idempotent.sh dstack-sdk + + - name: Create GitHub Release + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.ver.outputs.version }} + run: | + if gh release view "$GITHUB_REF_NAME" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then + echo "::notice::GitHub Release $GITHUB_REF_NAME already exists; skipping" + exit 0 + fi + gh release create "$GITHUB_REF_NAME" \ + --title "dstack-sdk $VERSION" \ + --notes "Published to crates.io: [dstack-sdk@$VERSION](https://crates.io/crates/dstack-sdk/$VERSION), [dstack-sdk-types@$VERSION](https://crates.io/crates/dstack-sdk-types/$VERSION)" \ + --verify-tag diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index fb0e6a780b..d3e490306c 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -1,30 +1,94 @@ +# SPDX-FileCopyrightText: © 2024-2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + name: Rust checks on: push: - branches: [ master ] + branches: [ next, 'release/**' ] pull_request: - branches: [ master ] + branches: [ next, 'release/**', 'feat/**' ] + +permissions: + contents: read env: CARGO_TERM_COLOR: always jobs: rust-checks: - runs-on: ubuntu-latest + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + defaults: + run: + working-directory: dstack steps: - - uses: actions/checkout@v4 - + - uses: actions/checkout@v5 + with: + # The change detection below diffs against the base commit. + fetch-depth: 0 + persist-credentials: false + + # Which files changed, decided here rather than with a workflow-level + # `paths:` filter. + # + # `rust-checks` is a required status check. A workflow skipped by `paths:` + # reports nothing at all, so the check never arrives and the pull request + # waits on it forever -- the filter has to live inside a job that always + # runs and always reports. Everything expensive below is gated on this + # output; when nothing relevant moved the job costs a checkout and a diff. + - name: Detect relevant changes + id: changes + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + if [ -z "$BASE_SHA" ]; then + echo "relevant=true" >> "$GITHUB_OUTPUT" + echo "push build: running everything" + exit 0 + fi + changed=$(git diff --name-only "$BASE_SHA...HEAD") + echo "$changed" + if echo "$changed" | grep -qE '^(dstack/|sdk/simulator/|rust-toolchain\.toml|\.github/workflows/rust\.yml)'; then + echo "relevant=true" >> "$GITHUB_OUTPUT" + else + echo "relevant=false" >> "$GITHUB_OUTPUT" + echo "nothing this job covers changed" + fi + - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@v1 with: - components: clippy - + toolchain: 1.92.0 + components: clippy, rustfmt + + # The largest job in the repository was compiling the workspace from nothing + # on every run. `simulator-release.yml` already caches this way; this brings + # the check that gates every merge in line with it. + # + # `workspaces` because the manifest lives in `dstack/`, not at the root, and + # the action keys the cache on the lockfile it finds there. `sdk/` is a + # separate workspace, cached by its own job. + - name: Cache cargo + if: steps.changes.outputs.relevant == 'true' + uses: Swatinem/rust-cache@v2 + with: + workspaces: dstack + - name: Run Clippy - run: cargo clippy -- -D warnings --allow unused_variables - + if: steps.changes.outputs.relevant == 'true' + run: cargo clippy -- -D warnings -D clippy::expect_used -D clippy::unwrap_used --allow unused_variables + - name: Cargo fmt check + if: steps.changes.outputs.relevant == 'true' run: cargo fmt --check --all + # The LUKS tests in dstack-util skip and pass when cryptsetup is missing. + # Fail here instead, so a runner without it cannot hide them. + - name: Require cryptsetup + if: steps.changes.outputs.relevant == 'true' + run: cryptsetup --version + - name: Run tests - run: cargo test \ No newline at end of file + if: steps.changes.outputs.relevant == 'true' + run: ./run-tests.sh diff --git a/.github/workflows/sdk-compat.yaml b/.github/workflows/sdk-compat.yaml new file mode 100644 index 0000000000..3dfa22ab30 --- /dev/null +++ b/.github/workflows/sdk-compat.yaml @@ -0,0 +1,154 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: SDK compatibility + +permissions: + contents: read + +# Released SDKs against the current agent: nothing to re-check unless the SDKs +# or the agent they talk to changed. Not a required status check, so a +# workflow-level filter is safe. +# +# `dstack/**` rather than the guest-agent directories alone. The agent under +# test is built through `simulator_start`, whose dependency closure reaches a +# dozen crates in that workspace; naming the three obvious ones would leave the +# rest silently uncovered the moment one of them changed behaviour. +on: + push: + branches: [next, 'release/**'] + paths: + - 'sdk/**' + - 'dstack/**' + - 'rust-toolchain.toml' + - '.github/workflows/sdk-compat.yaml' + pull_request: + branches: [next, 'release/**'] + paths: + - 'sdk/**' + - 'dstack/**' + - 'rust-toolchain.toml' + - '.github/workflows/sdk-compat.yaml' + +env: + CARGO_TERM_COLOR: always + # Both the current tree and the released tags pin channel "1.92" in + # rust-toolchain.toml. Without this, rustup would treat that as a toolchain + # distinct from the "1.92.0" installed below and re-download it -- along with + # the three cross-compilation targets the pin asks for, none of which the SDK + # suites need. The compat job is about the wire surface, not about + # reproducing each tag's toolchain provisioning. + RUSTUP_TOOLCHAIN: 1.92.0 + +jobs: + # The agent the released SDKs are tested against, built once. + # + # Both matrix legs call `simulator_start`, which builds + # `dstack-guest-agent-simulator` out of the current tree -- the same binary, + # from the same commit, compiled twice in parallel. Nothing here replaces that + # call or hands the legs a binary from elsewhere: they still build from their + # own checkout, so what they test is still what this commit produces. This job + # only puts the artifacts in the cache first, under a key both legs restore, + # so the build they run finds its work already done. + # + # A `needs:` rather than a skip switch in `simulator_build` on purpose. That + # switch would be a path where the binary under test did not come from the + # checkout, which is not worth trading for a few minutes. + simulator: + name: Build the agent under test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + + - name: Cache cargo + uses: Swatinem/rust-cache@v2 + with: + workspaces: dstack + shared-key: sdk-compat-agent + + - name: Build the simulator + run: ./sdk/simulator/build.sh + + sdk-compat: + name: ${{ matrix.tag }} SDKs vs current agent + needs: simulator + runs-on: ubuntu-latest + strategy: + # Each tag is an independent claim; one failing should not hide the other. + fail-fast: false + matrix: + # v0.5.11 is the tag the freeze is defined against, and v0.5.8 is the + # newest tag whose SDK *clients and suites* actually differ from it. + # + # The bar is a different client, not a different tree. v0.5.10's sdk/ + # tree is the same object as v0.5.11's (`git rev-parse v0.5.10:sdk + # v0.5.11:sdk` prints one hash twice) and v0.5.9 differs from it by a + # single line -- a reqwest dependency spec in sdk/rust/Cargo.toml, with + # every client and test source in all four languages byte-identical. + # Either pair runs the same suites twice and reports one agreement as + # two independent results, at the cost of a second uncached + # four-language build. v0.5.8 is the first tag going back that carries + # a genuinely different client (26 files), and it earns its slot: it is + # the only released client that still asserts `EmitEvent` succeeds, so + # it is the only one that catches 0.6.0 removing it. v0.5.11's three + # assertions about that method were all rewritten in v0.5.9..v0.5.11 + # to tolerate failure under a simulator endpoint, so the v0.5.11 leg + # passes them without exercising anything. See sdk/compat/README.md. + tag: [v0.5.8, v0.5.11] + steps: + - uses: actions/checkout@v5 + with: + # The job checks the released SDKs out with `git worktree add `, + # which needs that tag's commit and its full tree locally. A shallow + # clone plus `fetch-tags` gives the refs but not a guarantee about the + # objects behind them, so take the whole history: the clone is a + # rounding error next to the Rust build in this job. + fetch-depth: 0 + persist-credentials: false + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + + # Restore only. The `simulator` job above populated this key; a leg that + # saved as well would race its twin for the same entry and gain nothing, + # since the next run's `simulator` job writes it again anyway. + - name: Restore the agent build + uses: Swatinem/rust-cache@v2 + with: + workspaces: dstack + shared-key: sdk-compat-agent + save-if: false + + - name: Install Go + uses: actions/setup-go@v5 + with: + # The `go` directive in the released sdk/go/go.mod. + go-version: '1.24' + + - name: Install Node + uses: actions/setup-node@v5 + with: + # The released sdk/js/package.json asks for node >=18; 20 is what the + # JS SDK release workflow publishes from. + node-version: '20' + + - name: Install Python + uses: actions/setup-python@v5 + with: + # The released sdk/python/pyproject.toml asks for >=3.10; 3.11 is what + # the Python SDK release workflow builds with. The runner script + # installs PDM if it is missing, the same way sdk/run-tests.sh does. + python-version: '3.11' + + - name: Released SDKs against the current agent + run: ./sdk/compat/run-compat-tests.sh ${{ matrix.tag }} diff --git a/.github/workflows/sdk.yaml b/.github/workflows/sdk.yaml new file mode 100644 index 0000000000..a101b5a135 --- /dev/null +++ b/.github/workflows/sdk.yaml @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: © 2025 Daniel Sharifi +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: SDK tests +permissions: + contents: read + +on: + push: + branches: [next, 'release/**'] + pull_request: + branches: [next, 'release/**', 'feat/**'] + +env: + CARGO_TERM_COLOR: always + +jobs: + sdk-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + with: + # The change detection below diffs against the base commit. + fetch-depth: 0 + persist-credentials: false + + # Which files changed, decided here rather than with a workflow-level + # `paths:` filter. + # + # `sdk-tests` is a required status check. A workflow skipped by `paths:` + # reports nothing at all, so the check never arrives and the pull request + # waits on it forever -- the filter has to live inside a job that always + # runs and always reports. Everything expensive below is gated on this + # output; when nothing relevant moved the job costs a checkout and a diff. + # + # `dstack/` is in the pattern because `sdk/run-tests.sh` starts the + # simulator, which is built from that workspace -- these suites exercise + # the agent's wire surface, not just the client libraries. The whole + # directory rather than the simulator's dependency closure: the closure is + # a dozen crates deep and would go stale the first time a dependency + # moved, and a filter that silently stops covering something is worse than + # one that occasionally runs when it need not. + - name: Detect relevant changes + id: changes + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + if [ -z "$BASE_SHA" ]; then + echo "relevant=true" >> "$GITHUB_OUTPUT" + echo "push build: running everything" + exit 0 + fi + changed=$(git diff --name-only "$BASE_SHA...HEAD") + echo "$changed" + if echo "$changed" | grep -qE '^(sdk/|dstack/|rust-toolchain\.toml|\.github/workflows/sdk\.yaml)'; then + echo "relevant=true" >> "$GITHUB_OUTPUT" + else + echo "relevant=false" >> "$GITHUB_OUTPUT" + echo "nothing this job covers changed" + fi + + - name: Install Rust + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: 1.92.0 + components: clippy, rustfmt + # This additional target is needed for wasm32 compatibility check. + targets: wasm32-unknown-unknown, thumbv6m-none-eabi + + # Both workspaces: `sdk/rust` for the SDK crates, and `dstack` for the + # release simulator that `sdk/run-tests.sh` builds before any suite runs. + # Without the second entry that build starts cold every time and is most + # of the job's wall time. + - name: Cache cargo + if: steps.changes.outputs.relevant == 'true' + uses: Swatinem/rust-cache@v2 + with: + workspaces: | + sdk/rust + dstack + # Save only from pushes to protected branches; pull requests restore + # from those. This cache is about 1 GB, and one per pull request ref + # would quickly push the repository past its cache quota and evict + # the entries that are actually shared. + save-if: ${{ github.event_name == 'push' }} + + # Pin the interpreter: the runner image's system Python can be newer than + # the PyO3 versions in the Python SDK's locked dependencies support. + - name: Install Python + if: steps.changes.outputs.relevant == 'true' + uses: actions/setup-python@v5 + with: + python-version: '3.13' + + - name: SDK tests + if: steps.changes.outputs.relevant == 'true' + run: cd sdk && ./run-tests.sh + + - name: Verify WASM compilation + if: steps.changes.outputs.relevant == 'true' + # Ensures SDK types can be used in smart contracts + run: cargo check --manifest-path sdk/rust/Cargo.toml --target=wasm32-unknown-unknown -p dstack-sdk-types + + - name: Verify no_std compatibility + if: steps.changes.outputs.relevant == 'true' + run: | + cargo test --manifest-path sdk/rust/Cargo.toml -p dstack-sdk-types --test no_std_test --no-default-features + cargo check --manifest-path sdk/rust/Cargo.toml -p no_std_check --target thumbv6m-none-eabi diff --git a/.github/workflows/simulator-release.yml b/.github/workflows/simulator-release.yml new file mode 100644 index 0000000000..2acf998816 --- /dev/null +++ b/.github/workflows/simulator-release.yml @@ -0,0 +1,101 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Simulator Release + +on: + workflow_dispatch: + inputs: + version: + description: 'Release version (for example: 0.5.8)' + required: true + type: string + push: + tags: + - 'simulator-v*' + +permissions: + contents: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + env: + TARGET_TRIPLE: x86_64-unknown-linux-musl + steps: + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Resolve version and tag + run: | + if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then + VERSION="${{ github.event.inputs.version }}" + else + VERSION="${GITHUB_REF#refs/tags/simulator-v}" + fi + VERSION="${VERSION#simulator-v}" + TAG="simulator-v${VERSION}" + echo "VERSION=${VERSION}" >> "$GITHUB_ENV" + echo "TAG=${TAG}" >> "$GITHUB_ENV" + echo "Resolved release version: ${VERSION}" + + - name: Install musl toolchain + run: | + sudo apt-get update + sudo apt-get install -y musl-tools + + - name: Set up Rust toolchain + uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1 + with: + toolchain: stable + targets: ${{ env.TARGET_TRIPLE }} + + - name: Cache Rust build artifacts + uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2 + with: + workspaces: dstack -> target + + - name: Build musl simulator binary + run: cargo build --manifest-path dstack/Cargo.toml --locked --release --target "${TARGET_TRIPLE}" -p dstack-guest-agent-simulator + + - name: Package release bundle + run: ./dstack/guest-agent-simulator/package-release.sh "${VERSION}" "${TARGET_TRIPLE}" + + - name: GitHub Release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + tag_name: ${{ env.TAG }} + name: "Simulator Release v${{ env.VERSION }}" + files: | + dstack/guest-agent-simulator/dist/dstack-simulator-${{ env.VERSION }}-${{ env.TARGET_TRIPLE }}.tar.gz + dstack/guest-agent-simulator/dist/dstack-simulator-${{ env.VERSION }}-${{ env.TARGET_TRIPLE }}.tar.gz.sha256 + dstack/guest-agent-simulator/install-systemd.sh + body: | + ## Release Assets + + - `dstack-simulator-${{ env.VERSION }}-${{ env.TARGET_TRIPLE }}.tar.gz` + - `dstack-simulator-${{ env.VERSION }}-${{ env.TARGET_TRIPLE }}.tar.gz.sha256` + - `install-systemd.sh` + + The tarball contains the musl-linked `dstack-simulator` binary together with the default + simulator config, fixture data, and a systemd unit template. + + ## Quick Start + + Download and run directly: + + ```bash + curl -LO https://github.com/${{ github.repository }}/releases/download/${{ env.TAG }}/dstack-simulator-${{ env.VERSION }}-${{ env.TARGET_TRIPLE }}.tar.gz + tar -xzf dstack-simulator-${{ env.VERSION }}-${{ env.TARGET_TRIPLE }}.tar.gz + cd dstack-simulator-${{ env.VERSION }}-${{ env.TARGET_TRIPLE }} + ./dstack-simulator -c dstack.toml + ``` + + Install to systemd: + + ```bash + curl -fsSL https://raw.githubusercontent.com/${{ github.repository }}/${{ env.TAG }}/dstack/guest-agent-simulator/install-systemd.sh | sudo bash -s -- --version ${{ env.VERSION }} + ``` diff --git a/.github/workflows/spdx-check.yml b/.github/workflows/spdx-check.yml new file mode 100644 index 0000000000..19f4366cda --- /dev/null +++ b/.github/workflows/spdx-check.yml @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: SPDX License Check + +on: + push: + branches: [ next, 'release/**' ] + pull_request: + branches: [ next, 'release/**', 'feat/**' ] + +permissions: + contents: read + +jobs: + reuse-lint: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + + steps: + - name: Checkout repository + uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: REUSE Compliance Check + uses: fsfe/reuse-action@v5 + with: + args: lint diff --git a/.github/workflows/verifier-release.yml b/.github/workflows/verifier-release.yml new file mode 100644 index 0000000000..e9d65289c0 --- /dev/null +++ b/.github/workflows/verifier-release.yml @@ -0,0 +1,133 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Verifier Release + +on: + workflow_dispatch: + inputs: + version: + description: Existing release tag version without the verifier-v prefix + required: true + type: string + push: + tags: + - 'verifier-v*' +permissions: + attestations: write + id-token: write + contents: write + packages: write + +jobs: + build-and-release: + runs-on: ubuntu-latest + steps: + - name: Parse and check version + env: + DISPATCH_VERSION: ${{ inputs.version }} + run: | + if [ "$GITHUB_EVENT_NAME" = workflow_dispatch ]; then + VERSION=$DISPATCH_VERSION + else + case "$GITHUB_REF" in + refs/tags/verifier-v*) VERSION=${GITHUB_REF#refs/tags/verifier-v} ;; + *) echo "Expected a verifier-v* tag" >&2; exit 1 ;; + esac + fi + if [[ ! "$VERSION" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "Version must be a valid Docker tag" >&2 + exit 1 + fi + echo "VERSION=$VERSION" >> "$GITHUB_ENV" + echo "RELEASE_TAG=verifier-v$VERSION" >> "$GITHUB_ENV" + + - name: Reclaim runner disk space + run: | + sudo rm -rf \ + /opt/ghc \ + /opt/hostedtoolcache/CodeQL \ + /usr/local/.ghcup \ + /usr/local/lib/android \ + /usr/share/dotnet + df -h / + + # Manual runs rebuild an existing release tag, not the selected branch. + - name: Checkout repository + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + ref: ${{ github.event_name == 'workflow_dispatch' && env.RELEASE_TAG || github.sha }} + persist-credentials: false + + - name: Log in to GitHub Container Registry + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3 + + - name: Resolve the revision to build + run: echo "GIT_REV=$(git rev-parse HEAD)" >> "$GITHUB_ENV" + + # Release images are built through the same script contributors run by + # hand, so a published image can be reproduced and checked digest-for-digest. + # See the builder README for the reproduction recipe. + - name: Build and push Docker image + id: build-and-push + env: + PUSH: "1" + METADATA_FILE: ${{ runner.temp }}/build-metadata.json + GIT_REV: ${{ env.GIT_REV }} + IMAGE_VERSION: ${{ env.VERSION }} + IMAGE_NAME: ghcr.io/dstack-tee/dstack-verifier:${{ env.VERSION }} + LATEST_IMAGE_NAME: ghcr.io/dstack-tee/dstack-verifier:latest + IMAGE_SOURCE_URL: ${{ github.server_url }}/${{ github.repository }} + DSTACK_SRC_URL: ${{ github.server_url }}/${{ github.repository }}.git + run: | + dstack/verifier/builder/build-image.sh \ + "$IMAGE_NAME" \ + "$LATEST_IMAGE_NAME" + digest=$(jq -r '."containerimage.digest"' "$METADATA_FILE") + if [ -z "$digest" ] || [ "$digest" = null ]; then + echo "the build did not report an image digest" >&2 + exit 1 + fi + echo "digest=$digest" >> "$GITHUB_OUTPUT" + + - name: Verify anonymous pull access + env: + IMAGE_DIGEST: ${{ steps.build-and-push.outputs.digest }} + run: | + token=$(curl -fsSL \ + "https://ghcr.io/token?scope=repository:dstack-tee/dstack-verifier:pull" \ + | jq -er .token) + curl -fsSL -o /dev/null \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.manifest.v1+json" \ + "https://ghcr.io/v2/dstack-tee/dstack-verifier/manifests/$IMAGE_DIGEST" + + - name: Generate artifact attestation + uses: actions/attest-build-provenance@ef244123eb79f2f7a7e75d99086184180e6d0018 # v1 + with: + subject-name: "ghcr.io/dstack-tee/dstack-verifier" + subject-digest: ${{ steps.build-and-push.outputs.digest }} + push-to-registry: true + + - name: GitHub Release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + tag_name: ${{ env.RELEASE_TAG }} + target_commitish: ${{ env.GIT_REV }} + name: "Verifier Release v${{ env.VERSION }}" + body: | + ## Docker Image Information + + **Image**: `ghcr.io/dstack-tee/dstack-verifier:${{ env.VERSION }}` + + **Digest (SHA256)**: `${{ steps.build-and-push.outputs.digest }}` + + **Verification**: [Verify on Sigstore](https://search.sigstore.dev/?hash=${{ steps.build-and-push.outputs.digest }}) diff --git a/.github/workflows/verifier-wasm-release.yml b/.github/workflows/verifier-wasm-release.yml new file mode 100644 index 0000000000..fda7ee473e --- /dev/null +++ b/.github/workflows/verifier-wasm-release.yml @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: Publish TDX lite verifier wasm to npm +on: + push: + tags: ['verifier-wasm-v*'] + workflow_dispatch: + inputs: + npm_tag: + description: 'npm dist-tag (beta, latest)' + required: true + default: 'beta' + type: choice + options: + - beta + - latest + +permissions: + id-token: write + contents: write + +jobs: + publish: + runs-on: ubuntu-latest + defaults: + run: + working-directory: sdk/verifier-wasm + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: '22' + registry-url: 'https://registry.npmjs.org' + + - name: Upgrade npm for trusted publishers support + run: | + npm install -g npm@11.21.1 + echo "npm: $(npm --version)" + + - name: Verify OIDC token availability + run: | + if [ -n "${ACTIONS_ID_TOKEN_REQUEST_URL}" ] && [ -n "${ACTIONS_ID_TOKEN_REQUEST_TOKEN}" ]; then + echo "OIDC token available" + else + echo "OIDC token NOT available" + echo "Check workflow permissions include 'id-token: write'" + exit 1 + fi + + - name: Verify repository configuration + run: | + echo "Checking repository consistency..." + GIT_REPO=$(git remote get-url origin | sed 's/.*github.com[/:]//; s/.git$//') + PKG_REPO=$(node -e "console.log(require('./package.json').repository?.url || '')" | sed 's|https://github.com/||; s|git+||; s|.git$||') + echo "Git remote: $GIT_REPO" + echo "package.json: $PKG_REPO" + if [ "$GIT_REPO" != "$PKG_REPO" ]; then + echo "Repository mismatch!" + echo "This will cause 422 error during publish" + exit 1 + fi + echo "Repositories match" + + - name: Build wasm package + working-directory: . + env: + REPRO_CHECK: '1' + run: bash sdk/verifier-wasm/scripts/build-in-container.sh + + - name: Run Node tests + run: npm test + + - name: Determine version and npm dist-tag + id: tag + run: | + PKG_VERSION=$(node -e "console.log(require('./package.json').version)") + PRERELEASE=false + if echo "$PKG_VERSION" | grep -qiE '(beta|alpha|rc|preview)'; then + PRERELEASE=true + fi + + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + VERSION="$PKG_VERSION" + REQUESTED="${{ github.event.inputs.npm_tag }}" + if [ "$PRERELEASE" = true ] && [ "$REQUESTED" = "latest" ]; then + echo "::error::prerelease $PKG_VERSION cannot be published with dist-tag latest" + exit 1 + fi + echo "tag=$REQUESTED" >> "$GITHUB_OUTPUT" + else + TAG_VERSION="${GITHUB_REF_NAME#verifier-wasm-v}" + if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then + echo "::error::tag version ($TAG_VERSION) does not match package.json version ($PKG_VERSION)" + exit 1 + fi + VERSION="$TAG_VERSION" + if [ "$PRERELEASE" = true ]; then + echo "tag=beta" >> "$GITHUB_OUTPUT" + else + echo "tag=latest" >> "$GITHUB_OUTPUT" + fi + fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + + - name: Publish to npm + run: | + NPM_TAG="${{ steps.tag.outputs.tag }}" + echo "Publishing with dist-tag: $NPM_TAG" + npm publish --access public --provenance --tag "$NPM_TAG" + + - name: GitHub Release + if: github.event_name == 'push' + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + with: + name: "verifier-wasm v${{ steps.tag.outputs.version }}" + body: | + ## npm Package + + **Package**: `@phala/dstack-verifier-wasm@${{ steps.tag.outputs.version }}` + + **Install**: `npm install @phala/dstack-verifier-wasm@${{ steps.tag.outputs.version }}` + + **Dist-tag**: `${{ steps.tag.outputs.tag }}` + + **Registry**: https://www.npmjs.com/package/@phala/dstack-verifier-wasm/v/${{ steps.tag.outputs.version }} diff --git a/.github/workflows/verifier-wasm.yml b/.github/workflows/verifier-wasm.yml new file mode 100644 index 0000000000..4060ab2a9b --- /dev/null +++ b/.github/workflows/verifier-wasm.yml @@ -0,0 +1,206 @@ +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: TDX lite verifier wasm + +on: + push: + branches: [ next, 'release/**' ] + tags: ['verifier-wasm-v*'] + pull_request: + types: [opened, synchronize, reopened, labeled, unlabeled] + branches: [ next, 'release/**' ] + workflow_dispatch: + inputs: + runtimes: + description: Run Electron and browser jobs + type: boolean + default: true + +permissions: + contents: read + +jobs: + changes: + runs-on: ubuntu-latest + outputs: + relevant: ${{ steps.changes.outputs.relevant }} + runtimes: ${{ steps.changes.outputs.runtimes }} + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Detect relevant changes + id: changes + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + BEFORE_SHA: ${{ github.event.before }} + EVENT_NAME: ${{ github.event_name }} + REF: ${{ github.ref }} + HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'verifier-wasm-runtimes') }} + DISPATCH_RUNTIMES: ${{ github.event_name == 'workflow_dispatch' && inputs.runtimes }} + run: | + relevant=false + if [ "$EVENT_NAME" = "workflow_dispatch" ] || [[ "$REF" == refs/tags/* ]]; then + relevant=true + echo "dispatch or tag: running" + else + if [ -n "$BASE_SHA" ]; then + changed=$(git diff --name-only "$BASE_SHA...HEAD") + elif [ -n "$BEFORE_SHA" ] && [ "$BEFORE_SHA" != "0000000000000000000000000000000000000000" ]; then + changed=$(git diff --name-only "$BEFORE_SHA...HEAD") + else + changed=$(git diff --name-only HEAD~1...HEAD) + fi + echo "$changed" + # Keep in sync with the workspace crates dstack-verifier-wasm depends on + # (`cargo metadata --filter-platform wasm32-unknown-unknown`). + if echo "$changed" | grep -qE '^(sdk/verifier-wasm/|dstack/crates/dstack-verifier-wasm/|dstack/dstack-mr/|dstack/crates/qemu-acpi/|dstack/dstack-types/|dstack/cc-eventlog/|dstack/size-parser/|dstack/verifier/fixtures/|dstack/Cargo\.(toml|lock)|\.github/workflows/verifier-wasm\.yml)'; then + relevant=true + else + echo "nothing this job covers changed" + fi + fi + + runtimes=false + if [ "$relevant" = true ]; then + if [ "$DISPATCH_RUNTIMES" = "true" ]; then + runtimes=true + elif [ "$EVENT_NAME" = "push" ] && { [ "$REF" = "refs/heads/next" ] || [[ "$REF" == refs/tags/* ]]; }; then + runtimes=true + elif [ "$HAS_LABEL" = "true" ]; then + runtimes=true + fi + fi + + echo "relevant=$relevant" >> "$GITHUB_OUTPUT" + echo "runtimes=$runtimes" >> "$GITHUB_OUTPUT" + echo "relevant=$relevant runtimes=$runtimes" + + build: + needs: changes + if: needs.changes.outputs.relevant == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + + - name: Build wasm in pinned container + env: + # The release workflow always checks reproducibility; PRs build once. + REPRO_CHECK: ${{ github.event_name == 'pull_request' && '0' || '1' }} + run: bash sdk/verifier-wasm/scripts/build-in-container.sh + + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src/wasm-bytes.js + if-no-files-found: error + + node: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node: ['20.19.0', '22', '24'] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: ${{ matrix.node }} + - name: Run cases + working-directory: sdk/verifier-wasm + run: npm test + + bun: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: latest + - name: Run cases + working-directory: sdk/verifier-wasm + run: bun test/run-cases.mjs + + electron: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' && needs.changes.outputs.runtimes == 'true' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + electron: ['31', 'latest'] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: '22' + - name: Install Electron + run: | + mkdir -p "$RUNNER_TEMP/electron" + cd "$RUNNER_TEMP/electron" + npm init -y >/dev/null + npm install "electron@${{ matrix.electron }}" + echo "ELECTRON_BIN=$RUNNER_TEMP/electron/node_modules/.bin/electron" >> "$GITHUB_ENV" + ELECTRON_RUN_AS_NODE=1 "$RUNNER_TEMP/electron/node_modules/.bin/electron" -e 'console.log(process.versions.electron)' + - name: Run cases as Node + working-directory: sdk/verifier-wasm + run: ELECTRON_RUN_AS_NODE=1 "$ELECTRON_BIN" test/run-cases.mjs + - name: Install xvfb + run: sudo apt-get update && sudo apt-get install -y xvfb + - name: Run cases in Electron main + working-directory: sdk/verifier-wasm + run: xvfb-run -a "$ELECTRON_BIN" --no-sandbox test/electron-main.mjs + + browser: + needs: [changes, build] + if: needs.changes.outputs.relevant == 'true' && needs.changes.outputs.runtimes == 'true' + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + browser: [chromium, firefox, webkit] + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5 + with: + persist-credentials: false + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: verifier-wasm-bytes + path: sdk/verifier-wasm/src + - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5 + with: + node-version: '20' + - name: Install Playwright and run cases + working-directory: sdk/verifier-wasm + run: | + npm install --no-save --no-package-lock playwright@1.65.0 + npx playwright install --with-deps ${{ matrix.browser }} + node test/browser/playwright.mjs ${{ matrix.browser }} diff --git a/.github/workflows/vmm-ui.yml b/.github/workflows/vmm-ui.yml new file mode 100644 index 0000000000..5e79081267 --- /dev/null +++ b/.github/workflows/vmm-ui.yml @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: © 2024-2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +name: VMM UI build + +permissions: + contents: read + +# The VMM's web UI and vmm-cli are built and tested here. Not a required +# status check, so a workflow-level filter is safe. +on: + push: + branches: [ next, 'release/**' ] + paths: + - 'dstack/vmm/ui/**' + - 'dstack/vmm/src/vmm-cli.py' + - 'dstack/vmm/src/tests/test_vmm_cli.py' + - 'dstack/vmm/requirements.txt' + - '.github/workflows/vmm-ui.yml' + pull_request: + branches: [ next, 'release/**', 'feat/**' ] + paths: + - 'dstack/vmm/ui/**' + - 'dstack/vmm/src/vmm-cli.py' + - 'dstack/vmm/src/tests/test_vmm_cli.py' + - 'dstack/vmm/requirements.txt' + - '.github/workflows/vmm-ui.yml' + +jobs: + build: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: '20' + + - name: Build vmm UI + run: | + npm ci + npm run build + working-directory: dstack/vmm/ui + + - name: Ensure vmm UI build is clean + run: | + if [ -n "$(git status --porcelain)" ]; then + echo "VMM UI build produced uncommitted changes." + echo "Run: cd dstack/vmm/ui && npm ci && npm run build" + echo "Then commit the updated build output dstack/vmm/src/console_v1.html" + git status --porcelain + exit 1 + fi + + # `--if-present`: the UI test script is not on every branch yet. + - name: Test vmm UI + run: npm run test --if-present + working-directory: dstack/vmm/ui + + vmm-cli: + runs-on: ${{ vars.CI_RUNNER || 'ubuntu-latest' }} + steps: + - uses: actions/checkout@v5 + with: + persist-credentials: false + + - name: Install Python + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install vmm-cli dependencies + run: pip install -r requirements.txt + working-directory: dstack/vmm + + - name: Test vmm-cli + run: python3 -m unittest -v tests/test_vmm_cli.py + working-directory: dstack/vmm/src diff --git a/.gitignore b/.gitignore index 22f88f8a6b..b40b898a3a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,20 @@ -/target +/dstack/target +/dstack/local-key-provider/build/target /certs /build-config.sh -/build -generated/ +/build/* +/images +/run +/rust-target +**/generated/* +!**/generated/mod.rs +node_modules/ +/.cargo +.venv +/tmp +.claude/settings.local.json +__pycache__ +/.ruff_cache/ +.planning/ +/dstack/vmm/src/console_v1.html +.claude/worktrees/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000000..05449f8bca --- /dev/null +++ b/.gitmodules @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +[submodule "dstack/kms/auth-eth/lib/forge-std"] + path = dstack/kms/auth-eth/lib/forge-std + url = https://github.com/foundry-rs/forge-std +[submodule "dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable"] + path = dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable + url = https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable +[submodule "dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades"] + path = dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades + url = https://github.com/OpenZeppelin/openzeppelin-foundry-upgrades + +[submodule "os/yocto/deps/bitbake"] + path = os/yocto/deps/bitbake + url = https://git.openembedded.org/bitbake + branch = 2.18 + +[submodule "os/yocto/deps/openembedded-core"] + path = os/yocto/deps/openembedded-core + url = https://git.openembedded.org/openembedded-core + branch = wrynose + +[submodule "os/yocto/deps/meta-yocto"] + path = os/yocto/deps/meta-yocto + url = https://git.yoctoproject.org/meta-yocto + branch = wrynose + +[submodule "os/yocto/deps/meta-confidential-compute"] + path = os/yocto/deps/meta-confidential-compute + url = https://github.com/Dstack-TEE/meta-confidential-compute.git + +[submodule "os/yocto/deps/meta-virtualization"] + path = os/yocto/deps/meta-virtualization + url = https://github.com/Dstack-TEE/meta-virtualization.git + +[submodule "os/yocto/deps/meta-openembedded"] + path = os/yocto/deps/meta-openembedded + url = https://github.com/openembedded/meta-openembedded + +[submodule "os/yocto/deps/meta-rust-bin"] + path = os/yocto/deps/meta-rust-bin + url = https://github.com/Dstack-TEE/meta-rust-bin + +[submodule "os/yocto/deps/meta-security"] + path = os/yocto/deps/meta-security + url = https://github.com/Dstack-TEE/meta-security.git diff --git a/.mailmap b/.mailmap new file mode 100644 index 0000000000..dfeddeabd7 --- /dev/null +++ b/.mailmap @@ -0,0 +1,28 @@ +# Phala Network contributors +Kevin Wang Kevin Wang +Yan Yan Leechael Yim +Yan Yan Leechael +Hang Yin h4x3rotab +Hang Yin Hang Yin +Jianwei Zhu Jianwei Zhu +Joshua Waller Joshua <64296537+HashWarlock@users.noreply.github.com> +Shawn Tian Shawn TIAN +Shelven Zhou Shelven Zhou +Shelven Zhou Shunfan Zhou +Wenfeng Wang Wenfeng Wang + +# Other contributors +Andrew MacPherson Andrew MacPherson +Daniel Sharifi Daniel Sharifi +Franco Barpp Gomes Franco Barpp Gomes +Franco Barpp Gomes Franco Barpp Gomes +Nitanshu Lokhande nlok5923 +Nitanshu Lokhande Nitanshu Lokhande <56120084+nlok5923@users.noreply.github.com> +Pierre Le Guen Pierre Le Guen <26087574+PierreLeGuen@users.noreply.github.com> +Tei Im Tei Im <40449056+ImTei@users.noreply.github.com> +Tei Im Tei Im +Created-for-a-purpose Created-for-a-purpose +crStiv crStiv +near-bookrock near-bookrock +Olexandr88 Olexandr88 +tuddman tuddman diff --git a/.plumber.yaml b/.plumber.yaml new file mode 100644 index 0000000000..0bf9475a0e --- /dev/null +++ b/.plumber.yaml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: © 2026 Thibaud Van den Berghe +# +# SPDX-License-Identifier: Apache-2.0 + +# Plumber configuration: the built-in defaults plus what this repository needs. +extends: plumber:default +version: "2.0" + +github: + controls: + githubActionMustComeFromAuthorizedSources: + includePlumberDefaults: true + # Third-party actions the workflows use, on top of the default trust list. + trustedGithubActions: + - dtolnay/rust-toolchain # installs the Rust toolchain + - Swatinem/rust-cache # cargo cache of the Rust jobs + - softprops/action-gh-release # creates the GitHub releases + - foundry-rs/foundry-toolchain # forge, for the KMS contracts + - leanprover/lean-action # builds the Lean proofs + # dtolnay/rust-toolchain downloads the rustup installer only when rustup + # is missing, and ubuntu-latest ships rustup. The four jobs that take + # their runner from `vars.CI_RUNNER` would run that download on a runner + # without it. + actionsMustNotExecuteMutableRemoteCode: + enabled: false diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..cf4eefcee5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,2355 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Upgrade notes + +- **`secure_time` refuses a clock the host controls.** `secure_time` is on + unless the app compose sets it to `false`, so this applies to every app + that leaves it out. Such an app no longer boots on AWS, nor when the + clocksource is not `tsc`. On AMD SEV-SNP the VMM launches it with Secure + TSC, which needs QEMU >= 11.2 (not released yet), host kernel >= 6.18 and a + CPU that supports it; an older QEMU exits at startup on the unknown + `secure-tsc` property. Such a guest also needs a KMS and verifier of this + release. Apps with `secure_time: false` launch as before. + +### Added + +- **Landlock in the guest kernel.** `CONFIG_SECURITY_LANDLOCK` is now built in, + so unprivileged sandboxes that rely on Landlock run inside CVMs. This + changes the guest kernel and therefore the OS image measurements. +- **Secure TSC for AMD SEV-SNP guests.** The VMM launches an SNP guest with + Secure TSC when `secure_time` is on, so the host cannot skew the guest + clock. +- `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). +- **The KMS auth-eth server can require several RPC providers to agree.** + `ETH_RPC_URLS` with `ETH_RPC_QUORUM=n/m` answers a read only with what n of + the m endpoints return alike, and `ETH_MAX_BLOCK_AGE`, required with several + endpoints, rejects a stale block. + `dstack-app/deploy-to-vmm.sh` reads the endpoints from `rpc.json` and keeps + API keys out of the measured compose file. See [Multiple RPC providers](dstack/kms/auth-eth/README.md#multiple-rpc-providers). +- **`key_provider: tdx-seal` derives keys from TDX hardware sealing.** The + guest derives its seed with `TDG.MR.KEY.GET`, bound to the OS, VM + configuration and app identity, so a CVM on a TDX host can recover its disk + without a KMS or SGX. See [TDX Hardware Key Provider](docs/tdx-seal-key-provider.md). + +### Security + +- **A new `sev-snp` disk is sealed to the running TCB.** The guest used + sealing parameters the host had already stored in `.instance_info`, so a host + could seal a new disk to an older TCB that stays able to derive its key. +- **Sysbox is updated to 0.7.2.** It fixes read-only bind mounts being made + writable from inside a Sysbox container, and host files being reachable + through symlinks while Sysbox syncs special volumes. See the + [upstream release](https://github.com/nestybox/sysbox/releases/tag/v0.7.2) + for the advisories. + +### Changed + +- **TDX quotes go to QGS over vsock first.** When `/etc/tdx-attest.conf` + sets a port, `tdx-attest` asks QGS directly and falls back to configfs only + if that fails, or uses configfs alone when `DCAP_TDX_QUOTE_CONFIGFS_PATH` is + set. The kernel's configfs path polls once a second, so a quote took about + 1 s there and takes about 5 ms over vsock. +- **Breaking:** guest: a data disk left at older KMS key epochs is no longer + migrated after a key rotation; boot stops instead. Start such apps from a + fresh data disk. Migration keeps the volume key, which the old root and any + copy of the old LUKS header reveal, so a migrated disk stays readable and + writable by whoever holds them. `requirements.unsafe_allow_disk_migration` + restores migration and is strongly discouraged; it has to be set in a new + compose approved in the old and the current app epoch rows. +- **`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. +- **`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. +- **The KMS auth-eth server pins contract reads to a block hash.** Each + request reads the block it resolved by hash (EIP-1898) rather than by number, + so the RPC endpoint must accept a block hash in `eth_call`, which the server + checks at startup. HTTP redirects from the endpoint are refused. The server + no longer falls back to `http://localhost:8545`: it exits unless + `ETH_RPC_URL` or `ETH_RPC_URLS` is set. +- A failing `init_script` is reported to the VMM as a boot error. +- **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 + path is unchanged — importers only update the module line in `go.mod`. The + retired tappd client becomes its own module at its unchanged path + (`sdk/go/tappd`), frozen and deprecated. The old `sdk/go` module is + deprecated and contains no packages from v0.6.1; both new modules require + that version, so `go get` upgrades an existing v0.6.0 pin instead of failing + with an ambiguous import. A consumer importing both `dstack` and `tappd` + must `go get` both new modules; the frozen tappd gets a one-time + `sdk/go/tappd/v0.6.1` tag for exactly that. Releases tag `sdk/go/dstack/v*` + or `sdk/go/ratls/v*`, gated by a new release workflow that also warms + pkg.go.dev indexing. +- **AMD SEV-SNP on bare metal is no longer experimental.** The docs list it + next to Intel TDX, GPU workloads included: the measured, fail-closed GPU gate + gives SNP the same boot-time guarantee, and an SNP verifier checks the GPU + requirement in the policy bound by `compose_hash` instead of the + `gpu-attestation` event. SEV-SNP in public clouds stays unsupported. + +### Fixed + +- The guest agent answers legacy `Info` without a quote on TDX guests whose + kernel exposes the TSM measurement sysfs, so `Info` no longer queues behind + quote callers. Callers that wait more than 10 seconds for the attestation + queue receive HTTP 503 and can retry. + +## [0.6.6] - 2026-11-20 + +### Upgrade notes + +- **KMS state moves to `/var/lib/kms`.** The root keys of every epoch move out + of `cert_dir` into the new `core.keyring_dir` (default + `/var/lib/kms/keyring`), as `epochs//` with `root-epoch` marking the + newest. `cert_dir` and the default listener TLS paths move from + `/etc/kms/certs` to `/var/lib/kms/certs`. A deployment that persists + `/etc/kms/certs` and relies on the defaults must persist `/var/lib/kms` or + set both paths. The on-disk layout is not read from older versions, so + upgrade by onboarding a new KMS, as before. + +- **SEV-SNP verification fetches AMD's CRL.** Every SNP verification now + needs AMD KDS, or the configured mirror, to serve `/crl`, including + evidence that carries its own certificates and used to verify offline. A + mirror that serves only `cert_chain` and VCEKs fails every SNP verification + as unavailable collateral until it serves the CRL too. + +- **SEV-SNP needs a published TCB list.** The KMS judges an SEV-SNP TCB + against the minimum TCB governance publishes for its CPU, and refuses an + SEV-SNP request, its own self-authorization included, while it cannot: + upgrade `DstackKms` and the auth API, then publish the list with + `setSevSnpTcbRequirements` (or `sevSnpTcbRequirements` for `dstack-auth`) + before upgrading the KMS. A KMS can cover the CPUs governance leaves out + with `core.attestation.sev_snp_tcb_requirements_file`, and `dstack-verifier` + judges against the same JSON in `attestation.sev_snp_tcb_requirements_file`. A host whose firmware still emits version 2 + reports, which do not name the CPU, is refused. See + [AMD SEV-SNP](docs/amd-sev-snp.md). + +- **`DstackKms` deploys apps through `appImplementation`.** The app proxy is + now created by `DstackApp.deployProxy` and initialized by `DstackKms`, which + keeps the proxy's creation code out of `DstackKms`, close to the 24 KB + contract size limit. After upgrading `DstackKms`, point `setAppImplementation` + at a current `DstackApp`, as `Upgrade.s.sol:UpgradeKms` now does. With a + released `DstackApp` there, `deployAndRegisterApp` reverts. + +- **Gateway WireGuard key proofs are off until you turn them on.** A CVM now + proves it holds the WireGuard key it registers. Old CVMs and gateways keep + working, and a missing proof is only logged, so the logs show when the fleet + is ready; then require proofs with `SetWgKeyProofConfig`. The squatting it + stops is closed only once every gateway node runs 0.6.6 and proofs are + required (#1615). + +- **The guest agent logs every API request to the serial console**: socket, + caller pid and uid, method, status and latency, never the arguments. Whoever + can read the console sees which internal APIs an app calls and how often + (#1626). + +### Added + +- Guest agent: v0 `GetKey` takes optional `root_epoch` and `app_epoch` and + reports the epochs it derived from, so an app can still reach a v0 key from + before a KMS key rotation. Unset means the current epochs, as before. + `Tappd.DeriveK256Key` shares `GetKeyArgs` and honours them too. The 0.5 line + gets the same in 0.5.16 (#1630, #1631). +- `dstack-key-recovery`, a tool that recovers an application key from an older + KMS root epoch for guests that cannot select one (#1632, #1633). +- KMS and verifier: the SEV-SNP TCB is judged against per-CPU minimums taken + from the AMD security bulletins, published through the auth API or loaded + from a JSON file (#1621, #1627, #1628). +- Gateway: CVMs prove possession of their WireGuard key at registration + (#1615). +- Guest agent: an access log line per API request on the serial console + (#1626). +- `formal/`: Lean 4 models and machine-checked proofs of KMS, gateway and guest + OS logic, built in CI (#1597). + +### Changed + +- KMS: each root epoch keeps the attestation produced when its keys were + generated (`epochs//root-attestation`), and key handover carries it in + `KmsKeys.attestation`, so joined and rotated nodes keep the evidence of every + epoch. The receiver archives it without verifying it; relying parties verify + it. `bootstrap-info.json` is gone: `GetMeta.bootstrap_info` reports the served + epoch's attestation. Auto-bootstrap now records the attestation too (#539). +- **Breaking:** SDKs: the SealedEnv helpers take the app epoch with no + default. `sealEnv`/`seal_env`/`SealEnv` and + `verifySealedEnvPublicKey`/`verify_sealed_env_public_key`/`VerifySealedEnvPublicKey` + take `root_epoch, app_epoch` in that order, and Go's `SealEnvAtEpochs` and + `VerifySealedEnvPublicKeyAtEpochs` and Rust's `seal_env_at_epochs` and + `verify_sealed_env_public_key_at_epochs` are folded into them. The app epoch + used to default to 0, so a key fetched after an app key rotation produced an + envelope the guest could not decrypt at boot. Pass both epochs + `GetSealedEnvPubKey` returns. +- sdk/rust (breaking): `TcbInfo` fields `mrtd` and `rtmr0`-`rtmr3` changed from `String` to `Option` because the server emits null on non-TDX backends; new public fields on `TlsKeyConfig`, `EventLog` and `InfoResponse` break struct-literal construction +- sdk/rust (breaking): `TappdTcbInfo` fields `mrtd` and `rtmr0`-`rtmr3` are now + `Option` to support non-TDX guests. Persisted Borsh values must be + decoded with the old layout before re-encoding. Rust v0 now requires an + agent with the `Version` RPC (dstack 0.5.7 or newer) to request Ed25519 keys, + certificate validity overrides, or application info in TLS certificates. + Default requests are unchanged. +- sdk/js (breaking): v0 and Tappd `TcbInfo` measurement fields `mrtd` and + `rtmr0`-`rtmr3` are typed as `string | null`, matching non-TDX responses. + Check for `null` before using them as hex strings. +- sdk/python (breaking): `TcbInfo` fields `mrtd` and `rtmr0`-`rtmr3` are now `Optional[str]` +- sdk/rust (breaking): v0 and v1 `get_key` take a `GetKeyConfig` built with + `GetKeyConfig::builder()`, which also carries the optional `root_epoch` and + `app_epoch`, and for v0 the `algorithm`. Replace v0 `get_key(Some(path), None)` with + `get_key(GetKeyConfig::builder().path(path).build())`, and v1 + `get_key(domain, algorithm)` with + `get_key(GetKeyConfig::builder().domain(domain).algorithm(algorithm).build())`. +- SDKs: the Python, JS and Go compose-hash helpers follow one rule, taken from + the `dstack-types` serde attributes, and agree on every app-compose vmm-cli + and the VMM UI emit. Go's hash of such files changes, since it used to differ + from the other SDKs. Hand-built inputs holding `null` or `false` values can + hash differently than before: Python and Go now keep a top-level `null`, + and JS drops `requirements.health_check: false` and similar defaults (#1508). +- SDKs: a v1 `GetKey` that selects an epoch fails if the response omits it, as + the v0 clients do: an agent older than the epoch fields ignores the + selectors (#1508). +- sdk/go: `ratls` verifies the versioned attestation current dstack writes, + replays V2 runtime events, accepts only TDX quotes, and gains a `WithVerify` + policy hook (#1508). +- sdk/go (breaking): `AppCompose.InitScript` and `AppCompose.SwapSize` changed to the named types `*InitScripts` and `*SwapSize`. Explicit empty compose slices now encode as `[]`; use nil to reproduce hashes that omitted them. + +### Removed + +- **Breaking:** Go and Rust SDKs: `GetKeyAtRootEpoch` and + `get_key_at_root_epoch`. Use `GetKeyAtEpochs(ctx, domain, algorithm, + &rootEpoch, nil)` or `get_key` with `GetKeyConfig::builder().root_epoch(n)`. + +### Fixed + +- Guest agent: the watchdog probe no longer reuses an idle connection the + agent may be closing, which logged `Connection reset by peer` every few + minutes on 0.6.5 (#1625). +- KMS: refuses to serve from an empty keyring instead of serving epoch + `u32::MAX` (#1618). +- VMM: a dropped start request no longer leaves two QEMUs; stop, power-off and + load recheck their state under the launch lock; the VM manifest and state + are written atomically; a reload no longer tears down a VM created while it + scans; and a VM that fails to load at startup is kept running instead of + stopped as an orphan (#1609-#1614, #1616, #1617). +- Gateway: a lock or lease that is no longer held cannot delete a successor's + or commit writes, and one stamped beyond the clock drift bound counts as + expired; an IP stays allocated while another instance holds it; a peer + gateway address inside this node's pool is warned about; wavekv 2.2 fixes two + replication divergences (#1598-#1601, #1605, #1606). +- Guest: warns on an `instance_id_seed` that is not 20 bytes (#1607). +- SDKs: Tappd clients call only routes `tappd.sock` serves, and Python's + `tdx_quote` pads short raw report data instead of failing; JS validates hex + and handles truncated responses; Python and Rust decode `Info` with null + registers (#1508). + +### Security + +- sev-snp-qvl: binds a supplied VCEK to the chip and TCB the report claims, + and rejects ASKs revoked by AMD's CRL (#1620, #1622). +- cc-eventlog: rejects V1 runtime event names containing `:`, whose digests + were not injective (#1596). +- Gateway: SNI sniffing honours the declared record lengths, and a CVM can no + longer register with a gateway node's WireGuard key (#1602, #1603, #1604). + +## [0.6.5] - 2026-11-15 + +### Upgrade notes + +- **The contracts are not compatible with 0.6.4.** `AuthorizationRequest` gains + `launchTicketHash` (see Changed), which changes the selectors of + `authorizeApp` and `authorizeKms` and the `IAppEpochAuth` interface ID + (`0xd33835bd` to `0xc396c1b0`). Upgrade `DstackKms`, every `DstackApp` proxy + (and `setAppImplementation`) and auth-eth together: a 0.6.4 auth-eth with a + 0.6.5 `DstackKms`, or the reverse, denies every request, and a 0.6.5 + `DstackKms` treats a 0.6.4 `DstackApp` as a legacy policy, limited to app + epoch 0 through `isAppAllowed`. +- **Upgrade the auth backend before the KMS.** A joining KMS needs the auth + backend's `GET /` to report `rootCaPubkey` and an `https://` source URL. +- **Upgrade every KMS instance before `setRequireKmsLaunchTicket(true)`.** + Older instances authorize serving through `isKmsAllowed`, which a required + ticket refuses, so they stop serving every app. +- **KMS refuses its old listener settings.** Move `[rpc]`, `[core.admin]`, + `[core.onboard]` `address`/`port`/`tls`, `[default]` and top-level Rocket + settings to `[listeners.*]` (see Changed) when upgrading the KMS image. +- **Gateway refuses its old listener settings.** A hand-written `gateway.toml` + must move its top-level listener settings, `[tls]`, `[core.admin]` and + `[core.debug]` (see Changed) when upgrading the gateway. + +### Added + +- KMS: an optional `[listeners.public]` listener, off by default, serving only + `GetMeta`, `GetAppEnvEncryptPubKey` and `GetSealedEnvPubKey`, so the guest + listener, which releases keys, can be restricted to CVMs (#1580). +- KMS, gateway: `proxy_protocol = true` on a listener requires a PROXY v1/v2 + header on every connection and logs its source address as the client. The + header is trusted as sent, so the listener must be reachable only through the + proxy. prpc request logs now carry the client address as `remote` (#1582). +- Launch tickets: key release can require a secret ticket the host presents at + launch, checked by the contract before the KMS releases anything, without + changing the compose hash. `DstackApp.setRequireLaunchTicket`, + `addLaunchTicket(hash, label)`, `removeLaunchTicket` and `launchTickets()` + gate `GetAppKey` and `SignCert` at every app epoch; `DstackKms` has the same + for KMS instances, gating only `kms_import_keys`. The hash is + `sha256("dstack-launch-ticket/v1:" || ticket)`. The VMM stores the ticket, + writes it to the guest's sys-config at every boot and returns only + `VmInfo.launch_ticket_hash`; `vmm-cli launch-ticket new|hash`, `deploy + --launch-ticket-file`, `update --launch-ticket-file|--no-launch-ticket`, + `dstack-util get-keys --launch-ticket-file` and the web UI set it. A joining + KMS takes its ticket in `Onboard`. Guests need OS 0.6.5, or 0.5.15 or later + on 0.5.x. See `dstack/kms/README.md#launch-tickets` (#1577). +- auth-eth, dstack-auth: `GET /` reports `rootCaPubkey`, the CA key of the + current root epoch (#1577). +- KMS: refused `GetAppKey`, `SignCert` and `GetKmsKey` requests are logged as + `key release denied` on `dstack_kms::audit`, with the app, instance, caller + and error, and `GetAppEnvEncryptPubKey`/`GetSealedEnvPubKey` as `env public + key served` or `refused` (#1583). +- Gateway: every state-changing admin RPC and every CVM registration logs one + line on `dstack_gateway::audit` with the operation, caller and subject + (#1588), and every proxied connection one line on `dstack_gateway::access` + with client, SNI, route, app, bytes and duration; disable it with + `RUST_LOG=info,dstack_gateway::access=off` (#1589). +- vmm-cli: `DSTACK_VMM_KMS_WHITELIST_PATH` overrides the KMS whitelist path, + `~/.dstack-vmm/kms-whitelist.json` by default (#1591). +- `dstack-verifier-wasm` (`@phala/dstack-verifier-wasm`): the TDX lite OS check + as a self-contained wasm package for JS/TS verifiers, released separately as + `verifier-wasm-v*` (#1555). + +### Changed + +- **Breaking:** KMS: listener settings move to `[listeners.*]`: + `[listeners.default]` (`tls`, `proxy_protocol`, Rocket settings, inherited + by every listener), `[listeners.guest]` (was `[rpc]`), `[listeners.admin]` + (was `[core.admin]`, credentials included), `[listeners.public]` and + `[listeners.onboard]` (`address`/`port`, was in `[core.onboard]`). The KMS + refuses a config that still sets an old location, naming the new one. The + old `[default]` section was never read; only `ident` moves, so responses now + carry `Server: DStack KMS` (#1585). +- **Breaking:** gateway: listener settings move to `[listeners.*]`: + `[listeners.default]` (Rocket settings and `proxy_protocol`, was the top + level, now inherited by the admin and debug listeners too), + `[listeners.guest]` (`address`, `tls`, was the top level), `[listeners.admin]` + (was `[core.admin]`) and `[listeners.debug]` (`enabled`, was `[core.debug] + insecure_enable_debug_rpc`). `insecure_localhost_backend` moves to + `[core.proxy]`. The gateway refuses a config that still sets an old location, + naming the new one; the gateway image's entrypoint writes the new one (#1587). +- **Breaking:** `IAppEpochAuth.AuthorizationRequest` gains `launchTicketHash`, + forwarded by auth-eth and checked by dstack-auth. A required ticket refuses + the legacy `isAppAllowed` and `isKmsAllowed` (#1577). +- KMS: onboarding pins the source's RPC certificate to the current root CA + from its own auth backend and refuses `http://` sources, so the ticket and + `source_token` are sent only to a KMS holding the registered roots (#1577). +- VMM: VM work directories are created with mode 0700 (#1577). +- verifier: `details.acpi_tables_verified` is `false` on an MR mismatch; + `is_valid` is unchanged (#1555). +- mkosi OS releases no longer publish `image-hashes.txt`; MRTD, `uki_auth` and + `boot_pcr_digest` are in the release notes table (#1573). +- dstack-auth is documented as development, testing and evaluation only: the + host operator controls its policy file (#1576). + +### Fixed + +- dstack-util: `get-keys` verifies the KMS with the guest's collateral service + and trust anchors, as system setup does, instead of the production defaults + (#1565). +- VMM: a guest with `simulated_tee = dstack-tdx` gets the vm_config and + measurement document of a TDX guest, so a KMS no longer refuses it with an + MRTD mismatch (#1590). +- auth-eth: bump hono to 4.13.16 for GHSA-4m76-xfj5-7975, GHSA-h7mg-cq63-vhpq, + GHSA-46wx-v44x-9hh2 and GHSA-4h7h-rv7c-7m2v (#1578). + +## [0.6.4] - 2026-11-12 + +### Upgrade notes + +- **Deployment order for key epochs:** upgrade the `DstackKms` and `DstackApp` + proxies and the auth backend, register the existing roots as root epoch 0 + (`registerRootEpoch`), then roll out the KMS nodes, then guests. Keep root and + app epochs at 0 until every KMS and guest is upgraded. See + `dstack/kms/README.md` and `docs/deployment.md`. +- **Auth backends must serve `GET /app/:appId`**, which reports an app's current + app epoch. The KMS reads it for `GetAppEnvEncryptPubKey` and + `GetSealedEnvPubKey`. `auth-eth` and `dstack-auth` serve it; custom webhook + backends must add it. +- **Upgrade KMS before guests.** 0.6.4 guests mint self-issued RA-TLS client + certificates for KMS calls and need a 0.6.4 KMS that accepts them. +- **KMS needs a key handover path to start:** configure the admin listener + with TLS and an admin token, or set `core.onboard.public_key_handover = true` + (see Changed). + +### Added + +- DstackKms, DstackApp: TEE platform allowlists. `AuthorizationRequest` of + `IAppEpochAuth` (the epoch-aware policy interface) carries `teeVariant`, the + platform name the KMS reports (`dstack-tdx`, `dstack-amd-sev-snp`, ...), + passed through unchanged by auth-eth. Each contract allows any platform until + its owner calls `setAllowAnyTeeVariant(false)`; it then allows only the names + set by `setAllowedTeeVariants`, from the platforms `TeeVariantPolicy` knows + (setting an unknown one reverts). The policy covers every epoch, and a + restricted one refuses unknown platforms and the legacy `isAppAllowed` and + `isKmsAllowed`, whose callers report no platform. auth-eth requires + `teeVariant` on `/authorizeKms` and `/authorizeApp`. +- KMS root and application key epochs, epoch-scoped authorization, SealedEnv + HPKE encryption, automatic environment migration, and epoch-aware SDK key + selection. +- dstack-auth: opt-in `allowedTcbStatuses` and `allowedAdvisoryIds` allowlists, + applied to app and KMS requests on `/authorize*` and `/bootAuth/*`. When set, + a `tcbStatus` outside the list, or any advisory ID outside the list, denies; + when absent, neither is checked. `GET /` reports the configured `chainId` and + `appImplementation`, and each decision is logged with the device ID, + measurements and TCB status. +- guest: `key_provider: sev-snp` derives a hardware-bound seed inside an AMD + SEV-SNP guest, so a KMS CVM on an AMD host can recover its disk and stored + root keys after restart without SGX (#1526). + +### Changed + +- KMS: a KMS requires a key handover path and otherwise refuses to start, + before onboarding or bootstrap, naming the missing setting: unless + `core.onboard.public_key_handover = true`, set `[core.admin] enabled = true` + and `[core.admin.tls]` with `key` and `certs`. There is no opt-out, dev auth + included. The built-in config now enables the admin listener with TLS on the + RPC key and certificate, so a KMS on it needs an admin token to start: + `core.admin.auth_token`, `DSTACK_KMS_ADMIN_TOKEN`, or the new + `core.admin.auth_token_hash` (hex SHA-256), which keeps the token out of a + public app compose; the hash is then public, so use a high-entropy random + token such as `openssl rand -hex 32`. When upgrading, add the admin TLS and a token, or enable + the public handover. The `dstack-app` composes and `dstackup` generate the + token and configure its hash; the deploy scripts publish the admin listener + when `KMS_ADMIN_ADDR` is set. +- KMS: `core.onboard.public_key_handover` defaults to `false`, so + `KMS.GetKmsKey` is no longer served on the public port. Onboard through the + source's admin listener with `source_token`; a source that still onboards + 0.5.x KMS nodes must set the option to `true` until they are upgraded. +- KMS: onboarding refuses a source whose certificate carries no OS image hash, + which drops the fallback for KMS 0.5.x sources. Join only from a 0.6+ source; + upgrade a 0.5.x cluster to 0.6.x first. +- dstack-auth: an empty `devices` list no longer allows any device; set + `allowAnyDevice: true` for that. An empty `osImages` list now denies every + app instead of skipping the OS image check. Allowlists generated by + `dstack-cli` already set both explicitly. +- Auth backends: once a root epoch other than 0 is activated, `/bootAuth/kms` + denies a KMS that reports no root epoch, as `/bootAuth/app` already did, so + KMS binaries predating root epochs stop serving at activation. Upgrade every + KMS before activating a new root epoch. +- auth-eth: policy is read at the `finalized` block by default instead of + `latest`, so on-chain changes, including revocations, take effect only once + finalized. Set `ETH_BLOCK_TAG=latest` (or `safe`) to override; an OP-stack + chain read through the Helios light client requires `latest`. Only + `finalized` protects policy from reorgs: with `latest` or `safe`, a reorg can + roll back an activation or a revocation the KMS has already acted on. The + server refuses to start if the RPC cannot serve the configured tag. + `ETH_FINALITY_CONFIRMATIONS` now counts back from that block. +- DstackKms, DstackApp: material approvals are per epoch. A request is decided + on the row of the epoch it selects, so a value is revoked only once every row + allowing it is cleared. Material setters name their rows: + `*AtEpochs(from, to, value)` writes a range, and in `DstackApp` + `*AtEpoch(epoch, value)` one epoch (in `DstackKms`, pass the epoch twice); + `remove*AtEpochs(0, latest root epoch, value)` in `DstackKms` and + `remove*AtEpochs(0, currentAppEpoch, value)` in `DstackApp` revoke a value + everywhere. `DstackApp` reports its setters as the new ERC-165 interface + `IAppEpochManagement` (`0x8c0524c4`). The `Manage.s.sol` scripts require + `ROOT_EPOCH` or `APP_EPOCH`, or a `FROM_*`/`TO_*` range. `DstackApp`'s + `allowAnyDevice` stays a single switch: `setAllowAnyDevice(bool)` covers every + app epoch, so dropping the device restriction cannot leave an older epoch + open to any host. +- App contracts deployed before app epochs (v0.5.x, v0.6.0) keep working with + the upgraded `DstackKms` and KMS, which authorize them for app epoch 0 only. + `Manage.s.sol` detects them by interface ID and calls their epoch-less + setters. Upgrading one to the current `DstackApp` keeps its compose hashes and + devices as app epoch 0, and its `allowAnyDevice` for every app epoch. +- DstackKms, DstackApp: ownership transfers take two steps for proxies upgraded + from v0.5.9: `transferOwnership` nominates, and the new owner must call + `acceptOwnership`. +- dstack-auth: `kms_export_keys` and `kms_import_keys` accept a registered + pending root epoch, so KMS nodes can onboard a new epoch before + `currentRootEpoch` is raised, as with the contract backend. Key-issuing + operations stay limited to the current epoch. +- KMS: retain `GetTempCaCert`, temporary CA files and legacy handover fields so + KMS nodes can be upgraded before existing OS images. +- dstack-util, cert-client: guests mint self-issued RA-TLS client + certificates for KMS calls instead of fetching the temp CA and minting from + it; the KMS authenticates the quote inside the certificate, not its issuer. + Guests fetch the root CA with the key response and bind it to the attested + RPC certificate, without a metadata preflight. Provider pins and the + `key-provider` launch event (RTMR3/PCR14) retain the root identity binding. + The new flow requires an attested KMS that accepts self-issued certificates. +- dstack-types: `KeyProvider::Kms` drops `tmp_ca_key` and `tmp_ca_cert`, so + `.appkeys.json` no longer carries them. Files written by older images still + parse, but out-of-tree readers that require those fields fail on new files. +- KMS: `auth-eth-bun` is renamed to `auth-eth`. The Bun webhook server moves + from `dstack/kms/auth-eth-bun` into `dstack/kms/auth-eth`, next to the + contracts. New releases are tagged `kms-auth-eth-v*` and published as + `ghcr.io/dstack-tee/dstack-kms-auth-eth`; images already published as + `ghcr.io/dstack-tee/dstack-kms-auth-eth-bun` remain available. Update image + references and source paths in deployments. +- **Breaking:** DstackKms: reverts with custom errors such as + `UnknownRootEpoch()` instead of revert strings, to stay under the EIP-170 + size limit. This includes `registerApp`, `setAppImplementation` and + `deployAndRegisterApp`, whose v0.6.0 strings (`Invalid app ID`, `Invalid + implementation address`, `DstackApp implementation not set`, `Invalid owner + address`) become `InvalidAppId()`, `InvalidImplementationAddress()`, + `AppImplementationNotSet()` and `InvalidOwnerAddress()`; tooling that + matches the strings must decode the errors. Authorization rejection reasons + are unchanged. + +### Removed + +- DstackKms: the epoch-less `addOsImageHash`, `removeOsImageHash`, + `addKmsAggregatedMr`, `removeKmsAggregatedMr`, `addKmsDevice` and + `removeKmsDevice`. Use the `*AtEpochs` forms; before any rotation, + `addOsImageHashAtEpochs(0, 0, hash)` is the old call. +- **Breaking:** DstackApp: the epoch-less `addComposeHash`, `removeComposeHash`, + `addDevice` and `removeDevice`, and with them + `IAppAuthBasicManagement`: an upgraded app no longer reports interface ID + `0x8fd37527`, and calls to those functions revert. Use the `*AtEpoch` or + `*AtEpochs` forms (`IAppEpochManagement`); at app epoch 0, + `addComposeHashAtEpoch(0, hash)` is the old call. +- DstackKms: `setKmsInfo`, `setKmsQuote` and `setKmsEventlog`. Root keys are + set with `registerRootEpoch`, and each epoch's attestation lives at its + `evidenceUrl`. +- KMS: the `auth-mock` webhook backend. For development, use the built-in + `[core.auth_api] type = "dev"`, which allows everything. +- `auth-simple` (`dstack/kms/auth-simple`). Use `dstack-auth`, which reads the + same config file. Differences: the TCB status and advisories are not checked + unless `allowedTcbStatuses` / `allowedAdvisoryIds` are set (auth-simple + defaulted to `["UpToDate"]` and `[]`); `/authorize*` requires + `kmsContractAddr`; KMS requests are not matched against `osImages`; the + config path and port are `--config` / `--port` flags instead of + `AUTH_CONFIG_PATH` / `PORT`, and it binds to `127.0.0.1` by default. See + `docs/dstack-auth-operations.md#migrating-from-auth-simple`. +- KMS: the Node `auth-eth` webhook server (`dstack/kms/auth-eth/src`) is + removed. Use the Bun server (formerly `auth-eth-bun`, now in the same + directory, see Changed), which serves the same webhook API and reads the + same environment variables, except that it binds all interfaces and ignores + `HOST`, and `PORT` defaults to 3000 from source (8000 in its image). The + `DstackKms`/`DstackApp` contracts, Foundry tests and deployment scripts stay + in `dstack/kms/auth-eth`. `kms/dstack-app/compose-dev.yaml` now builds + the Bun server. + +### Fixed + +- kms: onboarding with or without `source_token` verifies the source's + attestation on the connection that returns the root keys and checks local + policy before using them. Legacy sources requiring temp-CA-issued clients + must be upgraded. +- ra-rpc: check the TLS handshake signature when CA verification is skipped; + `tls_no_check` is renamed to `tls_skip_ca_verification` (#1522). +- vmm: write `.instance_info` atomically, so a failed write or power loss can no + longer drop the instance ID seed and lose the VM's disk key (#1553). +- KMS, Gateway, Verifier, auth-eth images: set explicit file modes and + normalize timestamps so image digests no longer depend on the clone-time + umask (#1512). + +## [0.6.3] - 2026-11-01 + +### Upgrade notes + +- **Upgrade every Gateway node before deploying the new guest image.** The + guest-agent external API now requires scoped access. Older Gateways cannot + authenticate health probes and drop new guests from rotation; mixed-version + clusters can also lose guest tokens during replication. See + [Guest Agent API access control](docs/guest-api-auth.md). +- **New guest image.** Register the 0.6.3 `os_image_hash` on chain before + deploying it. The guest kernel, rootfs, and their measurements have changed. +- **KMS always verifies the OS image hash.** The `[core.image] verify` option + has been removed; a leftover key is ignored (#1497). + +### Security + +- guest OS: disable automatic GPT partition discovery and host-supplied system + credentials on the measured kernel command line. Remove production systemd + generators that act on host-controlled, unmeasured input; pin the allowed + generator set and assert the hardening configuration during builds. Includes + the unreleased 0.6.2 fixes for GHSA-c79w-3x5w-gmm5. +- guest-agent: gate every external API route by scopes granted through signed + Ed25519 JWTs or `[cvm.guest_agent_api].anonymous_scopes`. No scopes are + anonymous by default; app SDKs keep using the internal Unix socket. The + measured `public_logs`, `public_sysinfo`, and `public_tcbinfo` settings still + control what may leave the TEE (#1469). +- KMS: always verify `os_image_hash`, including its policy and identity-event + bindings (#1497). +- TPM: bound allocations and loops driven by TPM replies, reject undersized + response headers, and handle non-progressing handle enumeration (#1477, + #1481). +- guest OS, service images, KMS auth backends, and SDK locks: update CA trust + stores and TLS dependencies for emSign distrust; remove the obsolete KMS + compose file that pinned vulnerable images (#1463–#1467, #1470, #1492). +- guest OS: update the mkosi kernel to 6.18.59; update Rust and npm dependencies + for published security advisories (#1473, #1493–#1496, #1502). + +### Added + +- guest: `requirements.ephemeral_data_disk` starts every boot with an empty + data disk, formatted before app code runs (#1461). +- guest OS: ship the kernel build tree under `/usr/src/linux-headers-` + with `/lib/modules//build` pointing to it (#1501). +- guest OS: enable transparent huge pages with the `madvise` default, read-only + file THP, opt-in Multi-Gen LRU and BBR, and deferred page initialization + (#1503, #1504). +- guest OS: enable EROFS, ublk, and alternative streamed container-layer + backends (#1509). +- KMS: publish the Bun-based auth-eth backend image (#1452). + +### Fixed + +- guest: keep verity volumes out of data-disk discovery, including volumes + created by older releases, and use distinct partition labels (#1459). +- guest OS: update Sysbox to 0.7.1 and use idmapped overlay mounts so container + rootfs writes persist across restarts and failed starts do not corrupt + ownership (#1489). +- SEV-SNP: coalesce concurrent endorsement-certificate fetches and return HTTP + 503 for unavailable AMD endorsements rather than declaring quotes invalid + (#1484). +- KMS: recover onboarding after repeated clicks or lost provisioning responses, + clear measurement cache entries by their actual filenames, and increase the + Bun auth webhook idle timeout (#1453, #1460, #1471). +- guest-agent: saturate oversized log durations instead of overflowing (#1478). +- vmm/verifier: measure guest NUMA nodes without PXB expanders; validate image + names before writing VM manifests (#1458, #1476). +- gateway: require canonical port numbers in SNI; validate gateway WireGuard + fields before rendering configuration (#1451, #1472). +- TDX: add read/write timeouts for QGS vsock requests (#1454). +- Go SDK: match compose hashing for U+2028 and U+2029 (#1479). + +### Changed + +- vmm: enable the QMP socket by default for newly started CVMs; set + `qmp_socket = false` to opt out (#1450). +- vmm: disable GPU `sanitize_on_attach` by default (#1455). +- guest OS: decompress squashfs file data directly into the page cache using + per-CPU decompressors (#1506). +- gateway: use a guest-issued, ten-year API token that remains valid while + registration is unavailable (#1499, #1500). +- dependencies: update dcap-qvl to 0.7.0; build JS and Python SDK releases from + locked dependencies (#1480, #1498). + +## [0.6.1] - 2026-10-12 + +dstack 0.6.1 is a security release. Upgrade the guest OS, KMS, and verifier. + +### Upgrade notes + +- **New guest image.** Register the 0.6.1 `os_image_hash` on chain before + deploying 0.6.1 images + +### Security + +- guest-agent: `/logs/` rejects names that are not valid Docker + container names, so a crafted name can no longer reach a different Docker + API endpoint (#1442) +- KMS and verifier: a request `vm_config` must match the attested copy, and a + config has one layout. On AMD SEV-SNP the competing copies let a `SignCert` + request pass authorization with one `os_image_hash` and obtain a certificate + claiming another (#1430) + +### Added + +- verifier: measure multi-node NUMA layouts of hugepage VMs through + `vm_config.numa_nodes`; the VMM orders guest NUMA nodes by host node and + records the memory QEMU actually allocates, so such VMs now verify (#1418) +- verifier: `vm_config.extra_root_devices` describes root-bus devices that a + `qemu_path` wrapper appends, so their DSDT entries can be measured (#1424) +- vmm: `passt` networking is back. Each passt runs as a sidecar of the VM + launcher and talks to QEMU over a socketpair; see + `docs/passt-networking.md` (#1422, #1423) +- vmm: per-VM `annotations` for host-side tooling, stored in the VM manifest + and never passed to the guest or measured (#1419, #1421) + +### Changed + +- sdk/simulator: use the GHCR openssh installer image (#1417) +- dependency updates: rustls 0.23.45 in the Rust SDK, hickory-resolver 0.26.2, + and npm packages in KMS auth-eth and the VMM UI (#1429, #1432, #1434, #1436, + #1438, #1439, #1440) + +## [0.6.0] - 2026-09-28 + +> [!IMPORTANT] +> dstack 0.6.0 is the first release from the monorepo. Each component is +> released under its own tag in `Dstack-TEE/dstack`: `mkosi-os-v0.6.0` for the +> guest OS image, and `kms-v0.6.0`, `gateway-v0.6.0` and `verifier-v0.6.0` for +> the services, whose container images now publish to `ghcr.io/dstack-tee`. +> Guest OS releases before 0.6.0 remain in `Dstack-TEE/meta-dstack`. + +### Highlights + +- a versioned guest API, `dstack.guest.v1`, with domain-separated key + derivation, GPU evidence, and one attestation entry point on every platform. + The v0 API is frozen at v0.5.11 and keeps working unchanged +- a unified attestation model for Intel TDX, AMD SEV-SNP, AWS Nitro Enclaves, + AWS NitroTPM, GCP Confidential VMs, and development simulators +- canonical event log v2 and manifest-based OS and workload policy + verification +- a Debian/mkosi guest OS as the default, reproducible build backend, + superseding Yocto +- VMM-managed networking with netd, macvtap, vhost-net multiqueue, and libvirt + network filters +- Gateway application health checks, WaveKV v2, simultaneous CVM connections + to multiple Gateway clusters, and credential-free certificate issuance with + `dns-persist-01` (experimental) +- local key providers, external attestation root CAs, dm-verity volumes, and + data disks that return deleted blocks to the host +- shared authentication across the VMM, Gateway, and KMS administrative APIs +- a security hardening pass across every component + +### Upgrade notes + +See [docs/upgrading-to-0.6.md](docs/upgrading-to-0.6.md) for the upgrade +procedure. + +- **Every measurement changes.** Register the new `os_image_hash` on chain + before deploying 0.6.0 images. The VMM now defaults `qemu_hotplug_off` to + `true`, which changes the ACPI tables and RTMRs of every CVM on its next + start, whatever its image; update any allowlist that pins MRs, or set it + back to `false` on hosts without GPUs (#1387) +- **Apps on the 0.6.0 guest image:** `pre_launch_script` runs under + `set -euo pipefail`; a GPU CVM must pass GPU attestation to boot unless + `requirements.gpu_policy.attest_gpu` is false; legacy iptables is gone; + environment variables arrive byte for byte instead of with `\n` escaped; + and an encrypted environment that cannot be decrypted stops the boot +- **v1 keys differ from v0 keys.** Existing apps keep their keys on the + unversioned (v0) paths. Moving to v1 `GetKey` needs an asset migration + signed by the old key; see `docs/guest-api-v1.md`. v1 attestations and + v1-issued RA-TLS certificates need KMS and verifiers 0.5.9 or later +- **SDKs:** `DstackClient` now means `DstackClientV1`; name `DstackClientV0` + to stay on v0. Deep imports of the v0 modules gain a `_v0` suffix, and the + Python v0 client emits a `DeprecationWarning` +- **Guest agent:** `EmitEvent` always fails; bind app data through + `report_data` instead. `GetQuote` answers on Intel TDX only; use `Attest` + elsewhere +- **KMS:** Nitro Enclave key release needs `nitro_enclave_key_release = true` + (#1303), and the Nitro Enclave `device_id` is now `sha256(PCR4)`, so + `DstackApp` contracts with `allowAnyDevice = false` must add the new value + (#1302). Root-key handover moves to the admin listener; turn off + `core.onboard.public_key_handover` once every node is upgraded (#1307) +- **Admin APIs fail closed:** a KMS or Gateway with its admin API enabled + but no `auth_token` or `htpasswd_file` refuses to start. The VMM's `[auth]` + now guards the whole API and web UI +- **Gateway:** roll nodes one at a time; 0.5.x and 0.6.0 nodes serve traffic + but do not sync until every node is upgraded. + `core.debug.insecure_skip_attestation` is gone, and a gateway + without a guest agent no longer starts (#1148). A certificate configured in + `[core.proxy]` is ignored; install it with `Admin.ImportCert` (#1239) +- **VMM:** a 0.5.x app that sets `key_provider_id` cannot boot its 0.5.x + image on a 0.6.0 VMM; move it to the 0.6.0 image with the host. Upgrade + netd together with the VMM, and before it on hosts running + bridge or macvtap VMs (#1145, #1217) +- **Images:** component images publish to `ghcr.io/dstack-tee/` + (#1222). `dstackup` digest-pins its default KMS image, so fresh installs + register a different KMS app id +- **certbot:** every renewal uses a new private key; update DANE/TLSA or SPKI + pins on each renewal + +### Added + +#### Guest API v1 and SDKs + +- guest-agent: the versioned API `dstack.guest.v1`, served at `/v1` on the + internal socket (`IssueCert`, `GetKey`, `Attest`, `AttestGpu`, `Info`, + `Version`) and at `/prpc/v1` on the external listener (`Info`, `Version`, + `Health`). Specified byte for byte in `docs/guest-api-v1.md` (#1116) +- guest-agent: v1 `GetKey` derives keys with a domain-separated KDF, so the + two curves no longer share a secret, and its signature-chain claim cannot be + forged through the v0 surface (#1116) +- guest-agent: v1 `Attest` returns the boot-time GPU attestation evidence on + request, and `AttestGpu` collects fresh GPU evidence against a caller's + nonce (#1111, #1112) +- guest-agent: v1 `Attest` and `IssueCert` always use the MessagePack + attestation schema (#1207) +- guest-agent: a `GpuInfo` RPC for GPU telemetry (#1178) +- sdk: every SDK ships `DstackClientV0` for the frozen v0 surface and + `DstackClientV1` for v1. Neither verifies signature chains locally; relying + parties verify against `docs/guest-api-v1.md` (#1110, #1120) +- sdk: the Go SDK's `AppCompose` gains `init_script`, `storage_fs`, + `swap_size`, `event_log_version`, `port_policy` and `verity_volumes`, and + Go and Python gain `gpu_policy` (#1092) + +#### Attestation and platform support + +- AMD SEV-SNP image conversion, measurement, verification, and simulator + support (#703) +- AWS Nitro Enclave attestation platform specification and simulator support + (#753) +- GCP instance identity binding and unified OS image hash verification + (#726, #757) +- native TEE interfaces and a common TEE variant API (#743, #808) +- unified Intel TDX measurement and attestation handling, including ACPI + measurement support (#742, #762, #769) +- manifest-versioned OS policy, launch token, and GPU verification requirements + (#754, #763, #765) +- canonical JSON event log v2 with stricter event integrity validation + (#646, #879, #1038) +- external attestation root CA support (#806) +- seeded and deterministic simulator attestation for reproducible tests (#964) +- ACPI measurement and diagnosis implemented in Rust, including DSDT + generation for lite TDX images (#943, #1048, #1051, #1052, #1053) +- the TDX measurement document carries the kernel command line, and `auto` + TDX attestation follows the image rather than guest RAM (#1199, #1200) +- guest images normalize the Linux setup header, so the kernel measurement no + longer depends on the host's QEMU (#1189, #1229) +- the measured `gpu-attestation` event reports the GPUs' debug and secure + boot status (#1318), and a measured event records whether the data disk is + encrypted (#1326) + +#### VMM and networking + +- VMM networking RPCs for preparing and managing guest networking (#756) +- a netd-based macvtap networking backend with systemd socket activation + (#1061, #1068, #1069) +- libvirt network filters and guest netfilter support (#837, #1042) +- validation and restriction of requested guest networking modes (#1068) +- virtio-net on vhost-net with configurable queue pairs, off by default + (#1145) +- port mappings can name a NIC index (#1213) +- local key provider support (#788) +- development TDX and software TPM environments (#780, #798) +- TSM provider configuration through environment variables (#782) +- release discovery API for `dstackup` (#805) +- array-form `init_script` support (#975) +- image backend provenance tracking (#1073) +- a host-side data disk preallocation option (#1230) +- GPU listing for Hopper and Blackwell GPUs (#1161) +- a status filter in the console instance list (#1193) +- shared API authentication (`dstack-api-auth`) for the VMM HTTP, pRPC and UI + surface and for Gateway and KMS administration (#796) + +#### Gateway and certificates + +- opt-in application health checks: an app sets + `requirements.health_check`, and the Gateway keeps instances that report + unhealthy out of app-id load balancing. Health comes from the app's Compose + healthchecks or from a `health_status_file` the app writes. See + `docs/app-health-checks.md` (#1079) +- `Admin.SetInstanceReady` takes an instance out of rotation without stopping + it, and `Admin.Status` reports whether health gating is on (#1078) +- opt-in `dns-persist-01` certificate validation, which issues certificates + without DNS provider credentials. Experimental; see + `docs/certbot-dns-persist-01.md` (#1132) +- WaveKV v2 with deterministic conflict resolution. A 0.5.x data directory + is migrated in place; 0.5.x and 0.6.0 nodes do not sync with each other + (#1031, #1067) +- simultaneous CVM connections to multiple Gateway clusters (#1060) +- a Prometheus metrics endpoint (#1037), with sync rejection and node + liveness metrics (#1100, #1102) +- administrative recovery APIs (#1046) +- DNS-based application address resolution (#921) +- Certbot DNS API endpoint (#925) +- `Admin.ImportCert` installs a certificate issued elsewhere into the + replicated store (#1239) + +#### Storage and guest OS + +- integrity-protected dm-verity volumes (#752) +- production and development OS image flavors +- a Debian/mkosi guest OS build with Docker caching and parallel SquashFS + generation, now the default backend (#816, #828, #833, #834, #1208) +- the guest kernel build tree and a matching kernel module builder image, + `ghcr.io/dstack-tee/dstack-kernel-builder`, for out-of-tree modules (#1226) +- NVIDIA kernel module options derived from the GPU topology (#1157) +- TDX guest scaling knobs: batched wake-queue IPIs and paravirtual single + IPIs, on by default (#1219) +- the traffic control and checkpoint/restore kernel features Incus needs + (#1182) +- SELinux policy parity for guest services (#1043) +- reproducible NVIDIA attestation tooling and improved GPU certificate + verification (#789, #791, #813) + +#### Tooling + +- tag-driven release workflows for the Rust, JavaScript, Python, and Go SDKs + (#686, #691, #692) +- Rust SDK releases decoupled from the main workspace (#785) +- API parity improvements for the JavaScript and Python SDKs (#690, #695) +- `dstack-util decrypt` for decrypting protected payloads (#1054) +- measured boot and attestation diagnostics (#943) +- OCI source metadata on published images (#1190) + +### Changed + +- merged the former dstack and guest OS repositories into one monorepo (#770) +- renamed the default development branch to `next` and updated CI accordingly + (#1025, #1026) +- unified platform-specific attestation paths behind common verification and + policy interfaces +- moved KMS administrative APIs to a dedicated administration listener (#802) +- allowed application IDs to be derived without KMS availability (#714) +- added failover and multiple-service support to Gateway and KMS endpoint + configuration +- changed event serialization to canonical, named encodings with stricter + validation +- added explicit release identity and backend provenance to OS artifacts +- guest-agent: the unversioned API is frozen at v0.5.11. Additions made after + v0.5.11 that never shipped in a release moved to v1 (#1116) +- guest-agent: `GetQuote` answers on Intel TDX only, and its `attestation` + field is removed; use `Attest` on other platforms (#1107) +- guest-agent: the `/metrics` endpoint adds conventional `dstack_guest_*` + names; the old names remain for one release (#1103) +- sdk: v1 byte fields use each language's byte type instead of hex strings; + the JSON wire format is unchanged (#1124) +- sdk: the v0 modules are renamed with a `_v0` suffix, and the v0 clients are + marked deprecated in each language's tooling (#1122) +- sdk: the v1 SDKs agree with each other: Go's `IssueCert` defaults + `usage_server_auth` to true, and JavaScript drops its `asUint8Array()` + accessors (#1120) +- vmm: `qemu_hotplug_off` defaults to `true`, and ACPI generation rejects PCI + hotplug with GPU or NVSwitch root ports (#1387) +- vmm: the KMS and Gateway URL lists written to each CVM are shuffled, so new + CVMs spread their requests across service nodes (#1097) +- vmm: netd is served as a pRPC service with one method per operation (#1217) +- dstack-util: a CVM re-registers with the Gateway node that last accepted it + before trying the others (#1093) +- kms: RA-TLS clients are authenticated by their attestation rather than by + certificate issuer; `[rpc.tls.mutual]` is dropped from `kms.toml` (#1106) +- kms: root-key handover is served as `Admin.GetKmsKey`, and onboarding takes + the source operator's token (#1307) +- kms: key release for AWS Nitro Enclaves is opt-in, like SEV-SNP and NitroTPM + (#1303) +- attest: the AWS Nitro Enclave `device_id` is derived from the attested PCR4 + (#1302) +- gateway: WireGuard configuration is applied by a background worker instead + of under the routing lock (#1308) +- certbot: every renewal is issued under a new private key, and the live + certificate and key are swapped atomically (#1241) +- http-client: HTTP clients are shared instead of built per request (#1079) +- dstackup: the default KMS image is pinned by digest (#1250) +- release: component images publish to `ghcr.io/dstack-tee` instead of + Docker Hub (#1222) +- os: the guest kernel's SWIOTLB bounce buffer grows at runtime, and upstream + DMA fixes for confidential guests are backported (#1192, #1194) +- os: mkosi images use an NTS-only chrony configuration (#1354) +- os/yocto: nerdctl 2.3.5, which honours Compose `healthcheck:` (#1083) + +### Deprecated + +- os: the Yocto guest OS backend (`os/yocto/`), in favor of mkosi. `make + os-image` builds with mkosi; Yocto builds move to `make os-image-yocto` + (#1208) + +### Removed + +- guest-agent: `EmitEvent` no longer records anything and always fails, since + runtime RTMR3 events are system-owned (#1116) +- gateway: `core.debug.insecure_skip_attestation` (#1148) +- gateway: the `[core.proxy]` `cert_chain`, `cert_key`, `base_domain`, + `external_port` and `tappd_port` settings, none of which took effect any + more (#1239, #1375) +- gateway: the legacy debug key (#999) +- vmm: legacy port-forward management, in favor of VMM-managed networking + (#795) +- vmm: pulling guest images from an OCI registry (#1282) +- verifier: the `debug` request field and the `acpi_tables` and `rtmr_debug` + response fields (#1332) +- sdk: `TlsKeyOptions.path` in the JavaScript SDK, which was never read + (#1120) +- obsolete SEV text digest handling (#764) + +### Security + +- added LUKS2 keyslot bounds checking and stopped passing storage keys through + process arguments (#799, #886) +- enforced restrictive permissions and atomic updates for KMS, guest, Gateway, + certificate, attestation, and TPM key material, including boot-time secrets, + certbot keys and the `vmm-cli` credential file (#1233, #1241, #1390) +- added archive extraction, image artifact, console log, registry layer, and + filesystem path confinement +- strengthened RA-TLS validation, including certificate/key matching, security + profiles, application extensions, and unattested certificate rejection; an + app certificate can no longer authenticate as the KMS (#1255) +- hardened KMS node authorization, Ethereum authentication, policy auditing, + endpoint redaction, and bootstrap. The KMS refuses to auto-bootstrap over + existing root keys (#1305), bounds its inputs to the auth backend (#1310, + #1311, #1365), reads each auth-eth decision from a single block (#1314), and + fails closed on an empty device allowlist or an unknown `MOCK_POLICY` + (#1344, #1391) +- removed the Gateway debug key and restricted private host APIs +- added stricter quote size, report-data, trailing-byte, event ordering, and + event-preimage validation +- improved WireGuard public key validation and Gateway registration collision + handling +- bounded parsing of untrusted bytes in `dstack-mr`, SEV-SNP and TPM + verification, and collateral fetching, which only reaches allowlisted hosts + (#1231, #1236, #1238, #1267, #1279, #1404) +- the verifier rejects SEV-SNP guests with unsupported `SEV_FEATURES` such as + `DebugSwap`, and checks downloaded OS images end to end before caching them + (#1275, #1337) +- the key provider re-checks TD attributes before provisioning (#1242) +- the guest fails closed when an encrypted environment cannot be decrypted + (#1340), and a container can no longer crash the guest agent or make an + anonymous `Info` call trigger a quote (#1256, #1263) +- `docker compose --remove-orphans` no longer deletes live containers when a + compose file uses `include` (#1254) +- the Gateway rejects malformed SNI values and sync envelopes that claim its + own node id, and a short TLS record on port 443 no longer aborts it (#1278, + #1284, #1380) +- the VMM enforces the port mapping policy on `update_vm`, restricts listed + GPUs to the node's offered devices, and bounds guest-reported event names + (#1286, #1346, #1363) +- guest-agent calls from the VMM and the Gateway are bounded in time and + response size (#1095) +- caller-supplied text can no longer forge log lines (#1401, #1407) +- release builds use `--locked`, CI actions and the release BuildKit image are + pinned by digest, and the KMS onboarding page and VMM console pin their + front-end dependencies by integrity (#1389, #1393, #1395, #1396, #1398, + #1403) + +### Fixed + +- data disks release deleted blocks back to the host through ZFS or ext4, + dm-crypt and QEMU. Discard is on by default; set `storage_discard: false` + to disable it (#1175) +- a GPU CVM using the TPM key provider can reboot again (#1410) +- sdk: compose-hash helpers in Go and Python no longer drop unknown + app-compose fields, Go no longer HTML-escapes `<`, `>` and `&`, and Python + no longer mutates its input, so every SDK produces the digest that is + whitelisted on chain (#1079, #1092) +- sdk: the Python and JavaScript wallet adapters reject TLS-key responses, + which derived the same wallet from different keys (#1283) +- sdk: the JavaScript and Rust clients report HTTP errors with the status and + the server's message, and JavaScript v0 methods reject on failure instead + of resolving to empty objects (#1120) +- sdk: the JavaScript transport sends and reads non-ASCII payloads correctly + and reports timeouts as timeouts (#1120) +- certbot: a certificate for both a name and its wildcard can be issued over + `dns-01`, and editing `domains` triggers a reissue (#1136, #1137) +- gateway: a new cluster registers a single ACME account (#1138) +- gateway: a node removed with `RemoveNode` stays out until an operator + re-admits it (#1100) +- gateway: KV tombstones are garbage-collected (#1099) +- gateway: `Admin.RemoveCvm` no longer reports a successful removal as failed + (#1088) +- fixed VMM CID allocation and reload behavior, including stopped VMs and + bounded allocation windows +- fixed VM restart policies, one-shot failure handling, stopped-VM resizing, + host port conflicts, serial log limits, and encrypted KMS URL propagation; + a VM that is still stopping starts once QEMU has exited (#1414) +- fixed simulator races and measurement inconsistencies across TPM, NitroTPM, + Intel TDX, AMD SEV-SNP, and GCP vTPM environments +- fixed guest startup and credential refresh during temporary Gateway or KMS + outages +- fixed Gateway certificate reload, certificate ordering, ACME credential + recovery, CAA reconciliation, DNS timing, peer synchronization, and + registration consistency, and moved KV store access off the routing lock + (#1253, #1262, #1265, #1385, #1386) +- fixed KMS CA persistence across restarts, repeated onboarding, authorization + locking, endpoint failover, and certificate log handling; an interrupted + bootstrap can be redone (#1309) +- fixed verifier configuration precedence, cache versioning, archive + confinement, development trust labels, one-shot output, and historical image + verification; the measurement cache is bounded and downloads are retried + (#1334, #1369, #1388) +- fixed GPU reset and VFIO sanitization, including PCI secondary bus reset + handling (#1065) +- fixed guest boot ordering, so the app starts only after `dstack-prepare` + and the guest agent, and an interrupted data disk initialization is redone + (#1322, #1324, #1328, #1339) +- fixed OS image release metadata so `/etc/os-release` and release artifacts + consistently identify dstack 0.6.0 (#1076) + +## [0.5.5] - 2025-10-20 + +### Added +- SDK sync agent for automated protobuf schema synchronization (#366) +- dstack-verifier CLI tool with OS image hash verification (#341) +- built-in swap configuration support for CVMs (#348, #357, #358) +- support for ext4 filesystem type on storage (#348) +- size-parser crate for handling size configurations (#355) +- init_script support in app-compose.json (#337) +- cache for verifier (#341) +- Add QEMU version and image name in VmConfig (#340) +- documentation for minimum version of each compose field (#363) + +### Changed +- max app compose size increased to 256K (#349) +- default timeout increased to 3 secs for python SDK (#339) +- auto reconnect when WireGuard gets stuck (#350) +- put filesystem type in RTMR3 event log (#348) +- read QEMU path from /etc/dstack/client.conf (#332) +- refactor sys-config generation code (#351) +- when formatting app_url, skip port if it's 443 (#326) +- update docker organization references (#342, #343) +- RA-TLS: add KeyCertSign and CrlSign usages for CA cert (#320) + +### Fixed +- guest-agent: request demo cert lazily +- VmConfig decode error (#347) +- potential panic due to int overflow in dstack-mr (#345) +- SDK issues - marked rootfs_hash optional (#339) + +### Removed +- docker_config field from app-compose.json (#374) + +## [0.5.4] - 2025-09-01 + +### Security +- Fixed LUKS header validation security vulnerability (GHSA-jxq2-hpw3-m5wf) + +### Added +- Support for generating borsh schema for public types (#302) +- Python SDK v0.5.0 with async support +- Auth backend examples (auth-mock, auth-eth-bun) +- Support for passt as network egress +- Support for more than 255 CPUs +- SPDX license annotations +- Security audit report and documentation +- Media kit and branding updates +- gRPC proxy support for gateway +- Browser compatibility for JS SDK +- git-cliff based changelog generation +- CONTRIBUTING.md documentation + +### Changed +- Better error reporting for TDX quote errors +- Moved generated prpc files to OUT_DIR +- Refactored dstack-sdk into two crates for no_std support +- Updated various dependencies (sha.js, elliptic, tokio, etc.) +- Improved vmm with one-shot support +- Updated documentation for non-KMS app access +- Consolidated dstack branding capitalization + +### Fixed +- Warnings and clippy issues +- Networking configuration issues +- Typing errors in Python SDK +- Compilation errors in supervisor +- Reserved IP allocation issues + +### Contributors +New contributors in this release: +- @DSharifi +- @pbeza +- @bravesasha +- @Olexandr88 +- @crStiv + +## [0.5.3] - 2025-06-24 + +### Added +- Add doc design-and-hardening-decisions.md by @kvinwang +- Add doc cvm-boundaries.md by @kvinwang +- Add ERC-165 support with hardcoded interface IDs by @Leechael +- Add warning for dev kms by @kvinwang +- Add script to config firewall for qemu by @kvinwang + +### Changed +- Bump version to 0.5.3 by @kvinwang +- Merge pull request #225 from Dstack-TEE/license by @h4x3rotab in [#225](https://github.com/Dstack-TEE/dstack/pull/225) +- Create LICENSE by @h4x3rotab +- Merge pull request #221 from Dstack-TEE/doc-harden by @kvinwang in [#221](https://github.com/Dstack-TEE/dstack/pull/221) +- Update dcap-qvl to 0.3.0 by @kvinwang +- Default max disk size to 10T by @kvinwang +- Merge pull request #220 from Dstack-TEE/feat-gateway-admin-rpc-get-meta-v05x by @Leechael in [#220](https://github.com/Dstack-TEE/dstack/pull/220) +- Merge pull request #216 from Dstack-TEE/doc-cvm-boundaries by @kvinwang in [#216](https://github.com/Dstack-TEE/dstack/pull/216) +- Merge pull request #215 from Dstack-TEE/sec-guide by @kvinwang in [#215](https://github.com/Dstack-TEE/dstack/pull/215) +- Merge branch 'master' into sec-guide by @kvinwang +- Add security guide by @kvinwang +- Merge pull request #217 from Dstack-TEE/add-reprobuid-note by @kvinwang in [#217](https://github.com/Dstack-TEE/dstack/pull/217) +- Add link to reproducible build by @kvinwang +- Merge pull request #213 from Dstack-TEE/kms-erc-165-support by @Leechael in [#213](https://github.com/Dstack-TEE/dstack/pull/213) +- Remove duplicate code. by @Leechael +- Update kms auth related docs by @Leechael +- Commands in hardhat.config.ts by @Leechael +- Build error. by @Leechael +- Update typechain-types. by @Leechael +- Add C code source URL by @kvinwang +- Add security guide by @kvinwang +- Better deployment script by @kvinwang +- Don't copy symbol link files by @kvinwang +- Merge pull request #212 from Dstack-TEE/impl-up-user-config by @kvinwang in [#212](https://github.com/Dstack-TEE/dstack/pull/212) +- Implement update user_config in UI and CLI by @kvinwang +- Merge pull request #199 from Dstack-TEE/config-fw by @Leechael in [#199](https://github.com/Dstack-TEE/dstack/pull/199) +- Update comments by @kvinwang +- Correct checking symlink existance by @kvinwang +- Merge pull request #207 from Dstack-TEE/gw-rt by @kvinwang in [#207](https://github.com/Dstack-TEE/dstack/pull/207) +- Seperate proxy runtime from Rocket by @kvinwang +- Use jemalloc by @kvinwang +- Merge pull request #210 from Dstack-TEE/vmm-gpu-attach-all-opt by @kvinwang in [#210](https://github.com/Dstack-TEE/dstack/pull/210) +- Optional disable attach all gpus by @kvinwang +- Merge pull request #204 from Dstack-TEE/gw-reload-cert by @kvinwang in [#204](https://github.com/Dstack-TEE/dstack/pull/204) +- Fix unit tests by @kvinwang +- Hot reload TLS certificate by @kvinwang +- Add helper function reload_certs by @kvinwang +- Merge pull request #203 from Dstack-TEE/gw-health by @kvinwang in [#203](https://github.com/Dstack-TEE/dstack/pull/203) +- Add health check endpoint by @kvinwang +- Merge pull request #202 from Dstack-TEE/config-tls-ver by @kvinwang in [#202](https://github.com/Dstack-TEE/dstack/pull/202) +- Cargo fmt by @kvinwang +- Configrable tls version and crypto provider by @kvinwang +- Extract create acceptor to a function by @kvinwang +- Merge pull request #205 from Dstack-TEE/vmm-cfg-id by @kvinwang in [#205](https://github.com/Dstack-TEE/dstack/pull/205) +- Only set mr_config_id for supported images by @kvinwang +- Update dstack version to 0.5.2 in docs by @kvinwang +- Merge branch 'gw-no-status' by @kvinwang in [#198](https://github.com/Dstack-TEE/dstack/pull/198) +- Move rpc status/info to admin port by @kvinwang +- Fix tboot.service in dep by @kvinwang + +### Fixed +- Move get_meta to admin API. by @Leechael +- Fix test cases for AppAuth test. by @Leechael + +### Removed +- Remove unused field bootstraped from InstanceInfo by @kvinwang +- Remove head from dstack-util show by @kvinwang + +## [0.5.2] - 2025-06-04 + +### Added +- Add optional appAuthImplementation setting in initialize by @Leechael +- Add AI generated cheatsheet. by @Leechael +- Add add deploy factory support to KmsAuth by @Leechael +- Add initializeWithData to AppAuth by @Leechael +- Add debug hints for download_image by @Leechael +- Add gateway_app_id to KMS.GetMetaResponse by @Leechael +- Add get_compose_hash endpoint for compose-hash check. by @Leechael +- Added detail in error message for destination issue debugging. by @Leechael +- Adds docstrings by @tuddman + +### Changed +- Dstack v0.5.2 by @kvinwang in [#196](https://github.com/Dstack-TEE/dstack/pull/196) +- Merge pull request #195 from Dstack-TEE/mr_config_id_v2 by @kvinwang in [#195](https://github.com/Dstack-TEE/dstack/pull/195) +- Better way to get td report by @kvinwang +- Implement mr_config_id v2 by @kvinwang +- Merge pull request #181 from Dstack-TEE/feat/gateway-rpc-domain-and-kms-info-enhancements by @kvinwang in [#181](https://github.com/Dstack-TEE/dstack/pull/181) +- Merge pull request #182 from Dstack-TEE/imp-app-auth-contract by @Leechael in [#182](https://github.com/Dstack-TEE/dstack/pull/182) +- Code review feedback. by @Leechael +- Update typechain-types by @Leechael +- Update deploy script & cheatsheet docs. by @Leechael +- _registerAppInternal. by @Leechael +- Remove redundant initialization code. by @Leechael +- Expose app implementation address by @Leechael +- Update generated assets. by @Leechael +- Clippy by @Leechael +- Chore(gateway): Add debug log for AcmeClient. by @Leechael +- Expose more metadata in GetMeta API. by @Leechael +- Fmt by @Leechael +- Allows to configure RPC_DOMAIN optionally by @Leechael +- Merge pull request #177 from Dstack-TEE/cvm-kms-url by @kvinwang in [#177](https://github.com/Dstack-TEE/dstack/pull/177) +- Merge pull request #179 from Dstack-TEE/fix-vmm-cli by @Leechael in [#179](https://github.com/Dstack-TEE/dstack/pull/179) +- Update_vm_env with custom kms_urls by @Leechael +- Support for set kms/gw urls for individual CVM by @kvinwang +- Merge pull request #193 from near-bookrock/master by @kvinwang in [#193](https://github.com/Dstack-TEE/dstack/pull/193) +- Merge branch 'master' into master by @near-bookrock +- Merge pull request #194 from tuddman/rust-sdk-docstrings by @kvinwang in [#194](https://github.com/Dstack-TEE/dstack/pull/194) +- Vmm ui: Fix gpu mode display in upgrade panel by @kvinwang +- Use rbind mount by @kvinwang +- Merge pull request #192 from Dstack-TEE/fix-log-span by @kvinwang in [#192](https://github.com/Dstack-TEE/dstack/pull/192) +- Fix bug in log span by @kvinwang +- Make all fields public by @near-bookrock +- Make tcb_info public by @near-bookrock + +### Fixed +- Clippy by @Leechael +- Abi in factory method is incorrect. by @Leechael +- Set ensure_ascii=False when generated compose-hash by @Leechael +- Compatible with custom kms-url and gateway-url by @Leechael + +## New Contributors +* @near-bookrock made their first contribution +## [0.5.1] - 2025-05-29 + +### Added +- Support for enforce key provider id in compose by @kvinwang +- Add deepwiki badge by @h4x3rotab +- Add option to hide tcbinfo from 8090 port by @kvinwang +- Add repobeats analytics by @h4x3rotab + +### Changed +- Merge branch 'configid' by @kvinwang in [#190](https://github.com/Dstack-TEE/dstack/pull/190) +- Support for bind key provider by @kvinwang +- Set compose hash to mr_config_id by @kvinwang +- Validate compose_hash according to configid by @kvinwang +- Merge pull request #191 from Dstack-TEE/rm-mr-kp by @kvinwang in [#191](https://github.com/Dstack-TEE/dstack/pull/191) +- Fix typo by @kvinwang +- Merge pull request #187 from Dstack-TEE/kms-clear-cache by @kvinwang in [#187](https://github.com/Dstack-TEE/dstack/pull/187) +- Minor rename by @kvinwang +- Add ensure_admin by @kvinwang +- Add RPC to clear image cache by @kvinwang +- Update to v0.5.1 in README by @kvinwang +- Merge branch 'up-md' by @kvinwang in [#189](https://github.com/Dstack-TEE/dstack/pull/189) +- Update build steps in README by @kvinwang +- Update build steps in README by @kvinwang +- Merge pull request #188 from Dstack-TEE/readme by @h4x3rotab in [#188](https://github.com/Dstack-TEE/dstack/pull/188) +- Merge pull request #186 from Dstack-TEE/rpc-req-id by @kvinwang in [#186](https://github.com/Dstack-TEE/dstack/pull/186) +- Add request id by @kvinwang +- Merge pull request #180 from Dstack-TEE/gw-app-auth by @kvinwang in [#180](https://github.com/Dstack-TEE/dstack/pull/180) +- Add LAUNCH TOKEN by @kvinwang +- Add auth API by @kvinwang +- Merge pull request #183 from Dstack-TEE/md-custom-domain by @kvinwang in [#183](https://github.com/Dstack-TEE/dstack/pull/183) +- Update Custom Domain in README by @kvinwang +- Merge pull request #184 from Dstack-TEE/public-tcbinfo by @kvinwang in [#184](https://github.com/Dstack-TEE/dstack/pull/184) +- Merge pull request #185 from Dstack-TEE/readme by @h4x3rotab in [#185](https://github.com/Dstack-TEE/dstack/pull/185) +- Merge pull request #178 from Dstack-TEE/metrics by @Leechael in [#178](https://github.com/Dstack-TEE/dstack/pull/178) +- Add prometheus metrics API by @kvinwang +- Merge pull request #176 from Dstack-TEE/fix-subvar by @kvinwang in [#176](https://github.com/Dstack-TEE/dstack/pull/176) +- More for the rename by @kvinwang +- Rename mr_image to os_image_hash by @kvinwang +- Update deployment doc by @kvinwang +- Update kms compose file by @kvinwang +- Fix mr_image verification issues by @kvinwang +- Minor rename by @kvinwang +- Cargo fmt by @kvinwang +- Support for the new mr_image model by @kvinwang +- Add mr_image in sys-config.json by @kvinwang +- Update CI config by @kvinwang +- Bump versio to 0.5.1 by @kvinwang +- Auto setulimit by @kvinwang +- Remove dep on openssl by @kvinwang in [#174](https://github.com/Dstack-TEE/dstack/pull/174) + +### Fixed +- Missed subvar in deploy-to-vmm.sh script by @Leechael + +### Removed +- Remove the unused mr_key_provider by @kvinwang + +## [0.5.0] - 2025-05-15 + +### Added +- Add extend_rtmr3 in tdx-attest by @kvinwang +- Support verity based rootfs by @kvinwang +- Adds build-able TlsKeyConfig by @tuddman +- Add rust client for dstack by @Created-for-a-purpose +- Add extend_rtmr3 in tdx-attest by @kvinwang +- Add inspect API for kms/auth-api by @Leechael +- Added requirements.txt by @Leechael + +### Changed +- Fix update compose file by @kvinwang +- Fix mount path by @kvinwang +- Update rust in tproxy docker image to 1.86 by @kvinwang +- Merge pull request #173 from Dstack-TEE/sodiumbox by @kvinwang in [#173](https://github.com/Dstack-TEE/dstack/pull/173) +- Implement sodiumbox by @kvinwang +- Better layout for upgrade pannel by @kvinwang +- Merge pull request #171 from Dstack-TEE/dev-0.5.0 by @kvinwang in [#171](https://github.com/Dstack-TEE/dstack/pull/171) +- Cargo fmt by @kvinwang +- Add venv.sh by @kvinwang +- Upgraded test kms contract by @kvinwang +- Auto update certs on start by @kvinwang +- Rm gpus section when no GPUs by @kvinwang +- Mount overlayfs on /home/root by @kvinwang +- Allow null gpu config by @kvinwang +- Fix clippy by @kvinwang +- Use 0.5.0 base image by @kvinwang +- Allow non-zero mr_config_id by @kvinwang +- Add tproxy_app_id for compatibility by @kvinwang +- Merge remote-tracking branch 'ds/master' into dev-0.5.0 by @kvinwang +- Better layout for Features by @kvinwang +- Fix gpu config issues by @kvinwang +- New gpu config format by @kvinwang +- Load tdx-guest.ko in prepare.sh by @kvinwang +- Fix invalid config in dstack-prepare.service by @kvinwang +- Run dstack-prepare service after chronyd by @kvinwang +- Use ZFS for data partition by @kvinwang in [#159](https://github.com/Dstack-TEE/dstack/pull/159) +- Optional secure time by @kvinwang +- Use extend_rtmr3 from tdx-attest by @kvinwang +- Rename tdxctl to dstack-util by @kvinwang +- Bump version to 0.5.0 by @kvinwang +- Merge pull request #170 from Dstack-TEE/rust-1.86 by @kvinwang in [#170](https://github.com/Dstack-TEE/dstack/pull/170) +- Use rust 1.86 by @kvinwang +- Merge pull request #169 from Dstack-TEE/fix-rust-sdk by @kvinwang in [#169](https://github.com/Dstack-TEE/dstack/pull/169) +- Fix incorrect args in rust-sdk by @kvinwang +- Merge pull request #161 from RizeLabs/feat/dstack-sdk-rust by @kvinwang in [#161](https://github.com/Dstack-TEE/dstack/pull/161) +- Merge pull request #6 from tuddman/rust-sdk-addendum-4 by @nlok5923 +- Merge pull request #5 from tuddman/rust-sdk-addendum-3 by @nlok5923 +- Merge pull request #4 from tuddman/rust-sdk-addendum-2 by @nlok5923 +- Merge pull request #3 from tuddman/rust-sdk-addendum by @nlok5923 +- Replace evidence-api with dcap-qvl by @Created-for-a-purpose +- Replace ethers with alloy by @Created-for-a-purpose +- Crate renaming + add readme by @nlok5923 +- Merge pull request #1 from Created-for-a-purpose/dstack-sdk-rust by @nlok5923 +- Minor cleanup by @Created-for-a-purpose +- Merge pull request #168 from Dstack-TEE/rust-1.86 by @kvinwang in [#168](https://github.com/Dstack-TEE/dstack/pull/168) +- Update Rust in CI to 1.86 by @kvinwang +- Merge pull request #165 from Dstack-TEE/fix-upgrade-btn by @kvinwang in [#165](https://github.com/Dstack-TEE/dstack/pull/165) +- Fix disappeared [Upgrade] button by @kvinwang +- Merge pull request #164 from Dstack-TEE/agent-start-order by @kvinwang in [#164](https://github.com/Dstack-TEE/dstack/pull/164) +- Ensure agent starts before docker by @kvinwang +- Merge pull request #166 from Dstack-TEE/rm-command by @kvinwang in [#166](https://github.com/Dstack-TEE/dstack/pull/166) +- Remove command from the api by @kvinwang +- Merge pull request #160 from Dstack-TEE/api-extend-rtmr3 by @h4x3rotab in [#160](https://github.com/Dstack-TEE/dstack/pull/160) +- Add API EmitEvent by @kvinwang +- Add API EmitEvent by @kvinwang +- Optimize vmm firewall rules by @kvinwang +- Merge pull request #156 from Dstack-TEE/fix-phala-cloud-integration by @Leechael in [#156](https://github.com/Dstack-TEE/dstack/pull/156) +- Gateway app: Optional turning on sync mode by @kvinwang +- Fmt(tdxctl) by @Leechael +- Merge pull request #155 from Dstack-TEE/docs by @h4x3rotab in [#155](https://github.com/Dstack-TEE/dstack/pull/155) +- Update docs by @h4x3rotab +- Merge pull request #154 from Dstack-TEE/app-deploy by @h4x3rotab in [#154](https://github.com/Dstack-TEE/dstack/pull/154) +- [doc] Add app deployment section in deployment.md by @kvinwang + +### Fixed +- Ordering and unnecessary import by @tuddman +- Suggested changes by @tuddman +- Fixes PR feedback by @tuddman +- Allowed_app_id comparation for gateway should be case insensitive. by @Leechael +- Deploy scripts. by @Leechael +- Tappd.sock has been rename to dstack.sock by @Leechael +- Use up-to-date package name in docker-compose.yml by @Leechael +- Typechain-types by @Leechael + +### Removed +- Remove sodiumoxide from Cargo.toml by @kvinwang + +## New Contributors +* @nlok5923 made their first contribution +* @tuddman made their first contribution +* @Created-for-a-purpose made their first contribution +## [0.4.2] - 2025-04-18 + +### Added +- Support https for prpc client by @kvinwang +- Add client agent API docs by @kvinwang +- Add signature verification in go tests by @kvinwang +- Add back the previous go sdk implementation by @kvinwang +- Add dstack simulator config by @kvinwang +- Add a note on how to access info about Dstack by @HashWarlock +- Add unknown-2035.json by @kvinwang +- Add mr_system by @kvinwang +- Add info API. by @Leechael +- Add ethereum Account transform. by @Leechael +- Add optional dependencies solders & keypair generate support by @Leechael +- Add encryptEnvVars by @Leechael +- Add docs/deployment.md by @kvinwang +- Added view stderr in teepod's builtin console by @Leechael +- Add note about how to view stderr by @Leechael +- Add tproxy setup guide & faq by @Leechael +- Add script to deploy kms to teepod by @kvinwang +- Support ACME_STAGING for the docker by @kvinwang +- Add --build to docker compose by @kvinwang +- Add dbg log by @kvinwang +- Add example code by @kvinwang +- Add Attestation doc by @kvinwang + +### Changed +- V0.4.2 by @kvinwang in [#153](https://github.com/Dstack-TEE/dstack/pull/153) +- Merge pull request #152 from Dstack-TEE/fix-status by @kvinwang in [#152](https://github.com/Dstack-TEE/dstack/pull/152) +- Fix status display after CVM updated by @kvinwang +- Merge pull request #149 from Dstack-TEE/pccs_url by @kvinwang in [#149](https://github.com/Dstack-TEE/dstack/pull/149) +- Read pccs_url from env var by @kvinwang +- Merge pull request #150 from Dstack-TEE/prpc-client-https by @kvinwang in [#150](https://github.com/Dstack-TEE/dstack/pull/150) +- Merge pull request #151 from Dstack-TEE/api-doc by @kvinwang in [#151](https://github.com/Dstack-TEE/dstack/pull/151) +- Better config fallback for tproxy_enabled by @kvinwang +- Don't include compose file in brief mode by @kvinwang +- Merge pull request #148 from Dstack-TEE/rename-tapp by @kvinwang in [#148](https://github.com/Dstack-TEE/dstack/pull/148) +- Cargo fmt by @kvinwang +- Rename tapp to app or /dstack by @kvinwang +- Unify dstack agent address getter by @kvinwang +- Rename run_as_tapp to run_in_dstack by @kvinwang +- Rename _tapp-address to _dstack-app-address by @kvinwang +- Fix default agent_port and gateway_urls alias by @kvinwang +- Merge pull request #146 from Dstack-TEE/auto-restart by @kvinwang in [#146](https://github.com/Dstack-TEE/dstack/pull/146) +- Auto restart exited VMs by @kvinwang +- Merge pull request #147 from Dstack-TEE/error-on-wrong-contract by @kvinwang in [#147](https://github.com/Dstack-TEE/dstack/pull/147) +- Kms script: Throw error if app auth not found by @kvinwang +- Merge pull request #145 from Dstack-TEE/cross-tdx-attest by @kvinwang in [#145](https://github.com/Dstack-TEE/dstack/pull/145) +- Make tdx-attest compile on non-linux by @kvinwang +- Merge pull request #144 from Dstack-TEE/rename-sdk by @kvinwang in [#144](https://github.com/Dstack-TEE/dstack/pull/144) +- Js sdk: Warn for simulator endpoint by @kvinwang +- Refactor python SDK by @kvinwang +- Refactor js sdk by @kvinwang +- Refactor go sdk by @kvinwang +- Merge pull request #142 from Dstack-TEE/renaming by @kvinwang in [#142](https://github.com/Dstack-TEE/dstack/pull/142) +- Merge pull request #143 from Dstack-TEE/simulator by @kvinwang in [#143](https://github.com/Dstack-TEE/dstack/pull/143) +- Use app key to sign the derived key by @kvinwang +- Rename more tappd in comments to guest agent by @kvinwang +- Always generate random tls key by @kvinwang +- One more rename by @kvinwang +- Rename get_eth_key to get_key by @kvinwang +- API backward compatibility for vmm and gw by @kvinwang +- Set mime application/json by @kvinwang +- Rename kms to dstack-kms by @kvinwang +- Rename teepod to dstack-vmm by @kvinwang +- Rename tproxy to dstack-gateway by @kvinwang +- Different handler for v0 and latest by @kvinwang +- Fix service name emittion by @kvinwang +- Add report_data in GetQuote response by @kvinwang +- Rename tappd to dstack-guest-agent by @kvinwang +- Fix file existance check by @kvinwang +- Update safe-write to 0.1.2 by @kvinwang +- Merge pull request #140 from Dstack-TEE/tappd-health by @kvinwang in [#140](https://github.com/Dstack-TEE/dstack/pull/140) +- Don't reuse connections in healthy check client by @kvinwang +- Persistent iptalbes rules by @kvinwang +- Merge pull request #139 from Dstack-TEE/teepod-compat by @kvinwang in [#139](https://github.com/Dstack-TEE/dstack/pull/139) +- Compatible older images by @kvinwang +- Merge pull request #138 from HashWarlock/patch-1 by @h4x3rotab in [#138](https://github.com/Dstack-TEE/dstack/pull/138) +- Merge pull request #137 from Dstack-TEE/gpu-include by @kvinwang in [#137](https://github.com/Dstack-TEE/dstack/pull/137) +- Add gpu whitelist by @kvinwang +- Merge pull request #135 from Dstack-TEE/mr-kms by @kvinwang in [#135](https://github.com/Dstack-TEE/dstack/pull/135) +- Add mr-kms to RTMR3 by @kvinwang +- Merge pull request #134 from Dstack-TEE/teepod-ui-opt by @kvinwang in [#134](https://github.com/Dstack-TEE/dstack/pull/134) +- Auto close dropdown by @kvinwang +- Store page size to localStorage by @kvinwang +- More efficient pagination by @kvinwang +- Add pagination/search and optimize net traffic by @kvinwang +- Support for updating port mapping by @kvinwang +- Merge pull request #133 from Dstack-TEE/cvm-fw by @kvinwang in [#133](https://github.com/Dstack-TEE/dstack/pull/133) +- Add script setting the user net firewall by @kvinwang +- Update deployment.md by @kvinwang +- Validate TCB attributes by @kvinwang +- Default memory size to 2048 by @kvinwang +- Show compose hash in the UI by @kvinwang +- Print watchdog error detail by @kvinwang +- Default max_disk_size to 500GB by @kvinwang +- Merge pull request #132 from Dstack-TEE/vec-reserved-net by @kvinwang in [#132](https://github.com/Dstack-TEE/dstack/pull/132) +- Turns reserved-net into an array by @kvinwang +- Fix used slots detect by @kvinwang +- Update unknown-2035.json by @kvinwang +- Release GPU for exited instances by @kvinwang +- Merge pull request #131 from Dstack-TEE/kms-tcb by @kvinwang in [#131](https://github.com/Dstack-TEE/dstack/pull/131) +- Reject to send keys to outdated TCB nodes by @kvinwang +- Add tcbStatus and advisoryIds to BootInfo by @kvinwang +- Update unknown-2035.json by @kvinwang +- Fix missing mrImage in BootInfo by @kvinwang +- V0.4.1 by @kvinwang +- Merge pull request #130 from Dstack-TEE/refactor-contracts by @kvinwang in [#130](https://github.com/Dstack-TEE/dstack/pull/130) +- Refactor KMS contracts to support the new MRs by @kvinwang +- Add device control by @kvinwang +- Merge pull request #128 from Dstack-TEE/det-rtmr3 by @kvinwang in [#128](https://github.com/Dstack-TEE/dstack/pull/128) +- Teepod ui: no_instance_id if no tproxy by @kvinwang +- Rename fn by @kvinwang +- Support for --no-instance-id by @kvinwang +- Optional instance-id by @kvinwang +- Merge pull request #129 from Dstack-TEE/up-deps by @kvinwang in [#129](https://github.com/Dstack-TEE/dstack/pull/129) +- Update dependencies by @kvinwang +- Merge pull request #110 from Dstack-TEE/sdk-updates by @Leechael in [#110](https://github.com/Dstack-TEE/dstack/pull/110) +- Doc update & release. by @Leechael +- Bump py sdk to 0.1.6 & js sdk to 0.1.11 by @Leechael +- Info API & update docs. by @Leechael +- Udpate sdk docs. by @Leechael +- V0.1.10 by @Leechael +- V0.1.8 by @Leechael +- Helper function for solana Keypair by @Leechael +- Update README.md by @Leechael +- TappdInfo API. by @Leechael +- Merge pull request #127 from Dstack-TEE/teepod-gpu by @kvinwang in [#127](https://github.com/Dstack-TEE/dstack/pull/127) +- Cargo fmt by @kvinwang +- Show slot or product_id for associated device by @kvinwang +- Refresh gpus status while opening deploy panel by @kvinwang +- Filter started vm while restore devices by @kvinwang +- Also release devices after shutdown by @kvinwang +- Auto start vm after created by @kvinwang +- Store allocated device id to instance state by @kvinwang +- Add pin-numa and hugepages by @kvinwang +- Add slot in gpu list by @kvinwang +- Support to start CVM with GPUs by @kvinwang +- Merge pull request #126 from Dstack-TEE/teepod-foreground by @kvinwang in [#126](https://github.com/Dstack-TEE/dstack/pull/126) +- Support for non-detached supervisor by @kvinwang +- Add #[serde(default)] by @kvinwang +- Fix compilation error by @kvinwang +- Add secret pubkey verification by @kvinwang +- Fix pubkey in GetMeta by @kvinwang +- Merge pull request #124 from Dstack-TEE/docs-deployment by @kvinwang in [#124](https://github.com/Dstack-TEE/dstack/pull/124) +- Merge pull request #123 from Dstack-TEE/docs by @kvinwang in [#123](https://github.com/Dstack-TEE/dstack/pull/123) +- Merge branch 'deploy-script' by @kvinwang +- Merge pull request #122 from Dstack-TEE/deploy-script by @kvinwang in [#122](https://github.com/Dstack-TEE/dstack/pull/122) +- Update contracts DB by @kvinwang +- Kms cli: Remove salt from app:deploy by @kvinwang +- Add update-env by @kvinwang +- Better deployment script by @kvinwang +- Support for UDS by @kvinwang +- Refactor kms deployment script by @kvinwang +- Add nextAppId by @kvinwang +- Merge pull request #121 from Dstack-TEE/set-caa by @kvinwang in [#121](https://github.com/Dstack-TEE/dstack/pull/121) +- Recreate acme account if the stored url doesn't matches by @kvinwang +- Add rpc set CAA by @kvinwang +- Support allowed_envs by @kvinwang +- Show mrs after got key if the provider is not KMS by @kvinwang +- Don't compile contracts in docker by @kvinwang +- Use lkp for kms by @kvinwang +- Merge pull request #120 from Dstack-TEE/kp-dockerfile by @kvinwang in [#120](https://github.com/Dstack-TEE/dstack/pull/120) +- Refactor key-provider docker files by @kvinwang +- Update hardhat config by @kvinwang +- Merge pull request #119 from Dstack-TEE/sign-pubkey by @kvinwang in [#119](https://github.com/Dstack-TEE/dstack/pull/119) +- Sign env encrypt pubkey by @kvinwang +- Merge pull request #118 from Dstack-TEE/env-whitelist by @kvinwang in [#118](https://github.com/Dstack-TEE/dstack/pull/118) +- Only allow wihtelisted envs by @kvinwang +- Merge pull request #117 from Dstack-TEE/refactor-shared by @kvinwang in [#117](https://github.com/Dstack-TEE/dstack/pull/117) +- Fix unit tests by @kvinwang +- Only allow wihtelisted envs by @kvinwang +- Refactor host shared files by @kvinwang +- Merge pull request #116 from Dstack-TEE/multiple-urls by @kvinwang in [#116](https://github.com/Dstack-TEE/dstack/pull/116) +- Support for multiple kms and tproxy URLs as fallback by @kvinwang +- Merge pull request #111 from Dstack-TEE/tproxy-p2p by @kvinwang in [#111](https://github.com/Dstack-TEE/dstack/pull/111) +- Degrade some logs to debug level by @kvinwang +- Fix bad wg config by @kvinwang +- Event channel buffer size=1 by @kvinwang +- Switch to use wg pubkey as internal map key by @kvinwang +- Dedup nodes when updating by @kvinwang +- Broadcast sync when CVM registered by @kvinwang +- Add broadcast syncing by @kvinwang +- Always sync self config to node list by @kvinwang +- Recycle staled nodes by @kvinwang +- Move dashboard to admin port by @kvinwang +- Avoid using unsafe port by @kvinwang +- Cert renew timeout 5mins by @kvinwang +- Fix NODE_URL in deploy script by @kvinwang +- Fix host_address parsing by @kvinwang +- Print unsettled challenges by @kvinwang +- Add SUBNET_INDEX in compose file by @kvinwang +- Refactor deploy script by @kvinwang +- Allow multiple tproxy appid by @kvinwang +- Support for config subnet index by @kvinwang +- Exclude broadcast ip by @kvinwang +- Add wg info in net info rpc by @kvinwang +- Show number of connections for cvm by @kvinwang +- Implement new tproxy reg protocol by @kvinwang +- Send all wg servers to client by @kvinwang +- Refactor the config file by @kvinwang +- Fix nodes update by @kvinwang +- Refacto certbot task creation by @kvinwang +- Don't abort on state loading failure by @kvinwang +- Remove app cert from dashboard by @kvinwang +- Add upgrading flag file by @kvinwang +- Better instance-id handling by @kvinwang +- Add connections counter by @kvinwang +- Add proxy nodes info in dashboard by @kvinwang +- Implement sync client by @kvinwang +- Rename tls_domain to rpc_domain by @kvinwang +- Add API update_state by @kvinwang +- Fix dashboard layout by @kvinwang +- Support for multiple servers in the protocol by @kvinwang +- Merge pull request #107 from Dstack-TEE/tproxy-dev by @kvinwang in [#107](https://github.com/Dstack-TEE/dstack/pull/107) +- Add USE_HEAD option by @kvinwang +- Update compose rev by @kvinwang +- User letsencrypt prod api by @kvinwang +- Refine deploy script by @kvinwang +- Add teepod-cli.py by @kvinwang +- Add host_address in portmap RPC by @kvinwang +- Support for localhost by @kvinwang +- Enable certbot by @kvinwang +- Better log by @kvinwang +- Built-in certbot by @kvinwang +- Tune tproxy config by @kvinwang +- Remove debug log by @kvinwang +- Fix default rocket config by @kvinwang +- Add renew hook by @kvinwang +- Add admin RPC by @kvinwang +- Wip by @kvinwang +- Add tappd client by @kvinwang +- Add tapp for tproxy by @kvinwang +- Merge pull request #91 from Dstack-TEE/kms-onchain by @kvinwang in [#91](https://github.com/Dstack-TEE/dstack/pull/91) +- Minor rename by @kvinwang +- Fix unittests by @kvinwang +- Adjust the deployment scripts by @kvinwang +- Support Upgrade for AppAuth by @kvinwang +- Add proxy deployment script by @kvinwang +- Implement OwnableUpgradable by @kvinwang +- Add fn initialize by @kvinwang +- Append some RPC description by @kvinwang +- RPC Comment by @kvinwang +- Minor rename by @kvinwang +- Refined key derivation by @kvinwang +- Update README.md by @kvinwang +- Merge pull request #99 from Dstack-TEE/attestation-doc by @kvinwang in [#99](https://github.com/Dstack-TEE/dstack/pull/99) +- Merge pull request #98 from 0xshawn/key-provider-enhancement by @kvinwang in [#98](https://github.com/Dstack-TEE/dstack/pull/98) +- Make docker restart always and run as daemon by @0xshawn + +### Fixed +- Fix sig verification by @kvinwang +- Parse failed on tcb_info by @Leechael +- Test case for solana. by @Leechael +- ToKeypair failed by @Leechael +- Fix typo in doc. by @Leechael +- Fix js test case. by @Leechael +- Fixed image url by @Leechael + +### Removed +- Remove examples by @kvinwang +- Remove service namespace from the RPC by @kvinwang +- Remove /etc in compose file by @kvinwang + +## New Contributors +* @HashWarlock made their first contribution +* @0xshawn made their first contribution +## [dev-v0.4.0.0] - 2025-01-17 + +### Added +- Add kms compose-dev.yaml by @kvinwang +- Add eventlog in KmsInfo by @kvinwang +- Add event digest validation in event logs replay by @kvinwang +- Add kms/README.md by @kvinwang +- Add transfer ownership to AppAuth.sol by @kvinwang +- Add demo cert in tappd by @kvinwang +- Add random seed for DeriveKey by @kvinwang +- Support for escape ansi color for docker logs by @kvinwang +- Add kms tapp by @kvinwang +- Add workaround for the network issue of the keyprovider by @kvinwang +- Add ci for next branch by @kvinwang +- Support for local key provider by @kvinwang +- Add key-provider build files by @kvinwang +- Add example of using prelaunch script by @kvinwang +- Add apparmor_restrict_unprivileged_userns troubleshooting. by @PierreLeGuen + +### Changed +- Use intermediate cert to sign app certs by @kvinwang +- Merge remote-tracking branch 'master' into kms-onchain by @kvinwang +- Update kms/tapp/compose-dev.yaml by @kvinwang +- Rename mr_enclave to mr_aggregated by @kvinwang +- Update dependency versions by @kvinwang +- Validate kms cert by @kvinwang +- Fix cargo clippy by @kvinwang +- Update contract address by @kvinwang +- Add function to set quote and eventlog by @kvinwang +- Store bootstrap info on disk by @kvinwang +- Fix ts error in unittest by @kvinwang +- Show deploy tx hash by @kvinwang +- Update hardhat config by @kvinwang +- Add eventlog in bootstrap result by @kvinwang +- Default to 50 lines of log by @kvinwang +- Show tx hash by @kvinwang +- Better mrs display in the log by @kvinwang +- Fix response data schema by @kvinwang +- Hide Upgrade button for local instances by @kvinwang +- Add tasks by @kvinwang +- Use string as type of tproxyAppId by @kvinwang +- Auto apply certs from tappd by @kvinwang +- Add optional app_id set in UI by @kvinwang +- No default pccs_url by @kvinwang +- Add option tls_no_check_hostname by @kvinwang +- Better auto cert gen for kms & tproxy by @kvinwang +- Update typechain types by @kvinwang +- Update contract deployment script by @kvinwang +- Add api get_root_ca by @kvinwang +- Fix potential start failure by @kvinwang +- Update README.md by @kvinwang +- Update kms app compose by @kvinwang +- Update README by @kvinwang +- Cargo fmt by @kvinwang +- Layout adjustment for README by @kvinwang +- Fix cargo clippy and warnings by @kvinwang +- Remove a debug print by @kvinwang +- Print error log to console by @kvinwang +- Update .gitignore by @kvinwang +- Remove certs copying by @kvinwang +- Support for auto-bootstrap by @kvinwang +- Auto generate certs for dev by @kvinwang +- Fix cert issue in tproxy setup by @kvinwang +- Extract cert-client to seperate crate by @kvinwang +- Max cert chain len = 2 by @kvinwang +- Wip by @kvinwang +- Fix cert chain in derived key by @kvinwang +- Root-ca default filename by @kvinwang +- Write full certchain in cert by @kvinwang +- No short arg for certgen by @kvinwang +- Providing trusted tproxy id by @kvinwang +- Use mr-kp instead of kp-info to calc mr_enclave by @kvinwang +- Print key provider MR by @kvinwang +- Default kms port 8000 by @kvinwang +- Change default onboard port by @kvinwang +- Consistent appid by @kvinwang +- Optimize onboard UI by @kvinwang +- Fix 0x prefix when checking App authority by @kvinwang +- Better error report by @kvinwang +- Fix boot auth url path by @kvinwang +- Update kms config by @kvinwang +- Fix minor issues by @kvinwang +- Fix rootfs_hash parsing in tdxctl by @kvinwang +- Fix hardhat typechain error by @kvinwang +- Display compose hash by @kvinwang +- Kms contracts: Remove appController method by @kvinwang +- Refactor the contracts by @kvinwang +- Update kms Config by @kvinwang +- Tested by @kvinwang +- Auth-eth in ts by @kvinwang +- Add test for contract by @kvinwang +- Derive k256 keys by @kvinwang +- Onboard by @kvinwang +- Add more fields in AppInfo by @kvinwang +- Add ecdsa key provision by @kvinwang +- Support for webhook by @kvinwang +- Put rootfs_hash to kernel args by @kvinwang +- Update Cargo.lock by @kvinwang +- Merge remote-tracking branch 'ds/master' into next by @kvinwang +- Don't redirect stderr to /dev/null by @kvinwang +- Merge pull request #87 from Dstack-TEE/kp-compose by @kvinwang in [#87](https://github.com/Dstack-TEE/dstack/pull/87) +- Update .gitignore by @kvinwang +- Merge pull request #81 from Dstack-TEE/key-provider by @kvinwang in [#81](https://github.com/Dstack-TEE/dstack/pull/81) +- Add device-id in RTMR3 by @kvinwang +- KMS key provider takes precedence by @kvinwang +- Merge pull request #112 from AndrewMohawk/patch-1 by @kvinwang in [#112](https://github.com/Dstack-TEE/dstack/pull/112) +- Update README.md by @AndrewMohawk +- Merge pull request #105 from Dstack-TEE/prune-images by @kvinwang in [#105](https://github.com/Dstack-TEE/dstack/pull/105) +- Pruning unused images by @kvinwang +- Merge pull request #100 from Dstack-TEE/prelaunch-demo by @kvinwang in [#100](https://github.com/Dstack-TEE/dstack/pull/100) +- Merge pull request #106 from Dstack-TEE/fix-clippy by @kvinwang in [#106](https://github.com/Dstack-TEE/dstack/pull/106) +- Fix cargo clippy errors by @kvinwang +- Merge pull request #104 from Dstack-TEE/disk-req by @kvinwang in [#104](https://github.com/Dstack-TEE/dstack/pull/104) +- Add RAM and disk requirement by @kvinwang +- Update prerequisite dependencies by @nanometerzhu +- Merge pull request #95 from Dstack-TEE/remove-orphans by @kvinwang in [#95](https://github.com/Dstack-TEE/dstack/pull/95) +- Implement tdxctl remove-orphans by @kvinwang +- Merge pull request #94 from Dstack-TEE/pre_launch_script by @kvinwang in [#94](https://github.com/Dstack-TEE/dstack/pull/94) +- Add pre_launch_script in app-compose by @kvinwang +- Merge pull request #90 from PierreLeGuen/master by @kvinwang in [#90](https://github.com/Dstack-TEE/dstack/pull/90) + +### Removed +- Remove mr ca-cert-hash by @kvinwang + +## New Contributors +* @AndrewMohawk made their first contribution +* @PierreLeGuen made their first contribution +## [0.3.4] - 2025-01-04 + +### Changed +- Update Cargo.lock by @nanometerzhu +- Bump version to v0.3.4 by @nanometerzhu + +## [0.3.4-beta] - 2025-01-02 + +### Changed +- No default not_before by @kvinwang +- Don't redirect stderr to /dev/null by @kvinwang +- Update .gitignore by @kvinwang +- Merge pull request #86 from Dstack-TEE/oom-protect by @kvinwang in [#86](https://github.com/Dstack-TEE/dstack/pull/86) +- Prevent tappd from be killed by OOM-killer by @kvinwang +- Merge pull request #85 from Dstack-TEE/fix-tproxy-conn by @Leechael in [#85](https://github.com/Dstack-TEE/dstack/pull/85) +- Fix bug in connection choosing by @kvinwang +- Merge pull request #84 from Dstack-TEE/readme by @h4x3rotab in [#84](https://github.com/Dstack-TEE/dstack/pull/84) +- Improve readme, address both code contrib and community by @h4x3rotab +- Fix a warning by @kvinwang +- Merge pull request #83 from Dstack-TEE/json-prpc by @kvinwang in [#83](https://github.com/Dstack-TEE/dstack/pull/83) +- Choose json codec in prpc clients by @kvinwang +- Move docker-daemon.json to meta repo by @kvinwang +- Merge pull request #82 from Dstack-TEE/safe-remove-orphans by @kvinwang in [#82](https://github.com/Dstack-TEE/dstack/pull/82) +- A better way to remove orphans by @kvinwang +- Merge pull request #46 from Dstack-TEE/feat-get-meta-api by @Leechael in [#46](https://github.com/Dstack-TEE/dstack/pull/46) +- Inspect public_logs and public_sysinfo option in Worker.Info by @Leechael +- Format by @Leechael +- Rename 'id' to 'instance_id' to avoid potential confusion by @Leechael +- Add GetMeta API for heartbeat. by @Leechael +- Add GetMeta API for heartbeat. by @Leechael +- Add GetMeta API for heartbeat. by @Leechael +- Merge pull request #80 from Dstack-TEE/tboot-no-shutdown by @kvinwang in [#80](https://github.com/Dstack-TEE/dstack/pull/80) +- Don't shutdown when tboot.sh fail by @kvinwang +- Merge pull request #79 from Dstack-TEE/remove-orphans by @kvinwang in [#79](https://github.com/Dstack-TEE/dstack/pull/79) +- Add --remove-orphans to docker compose up by @kvinwang +- Correct check for kmsEnabled in secrets reset by @kvinwang +- Merge pull request #78 from Dstack-TEE/wdg-tappd by @kvinwang in [#78](https://github.com/Dstack-TEE/dstack/pull/78) +- No hardcoded port for watchdog by @kvinwang +- Merge pull request #77 from Dstack-TEE/raw-quote by @kvinwang in [#77](https://github.com/Dstack-TEE/dstack/pull/77) +- Add standalone RawQuote API by @kvinwang +- Merge pull request #76 from Dstack-TEE/quote-prefix by @kvinwang in [#76](https://github.com/Dstack-TEE/dstack/pull/76) +- Add `prefix` for TdxQuote API by @kvinwang +- Merge pull request #74 from Dstack-TEE/confirm-rm by @kvinwang in [#74](https://github.com/Dstack-TEE/dstack/pull/74) +- Comfirm on removal by @kvinwang +- Merge pull request #75 from Dstack-TEE/git-ver by @kvinwang in [#75](https://github.com/Dstack-TEE/dstack/pull/75) +- Add git rev in Version rpc by @kvinwang +- Merge pull request #72 from Dstack-TEE/prpc-query-params by @kvinwang in [#72](https://github.com/Dstack-TEE/dstack/pull/72) +- Eliminates prpc routes file by @kvinwang +- Make the ra_rpc more easier to use by @kvinwang +- Support for reading args from url query by @kvinwang +- Merge pull request #73 from Dstack-TEE/e2fsck-no-reboot by @kvinwang in [#73](https://github.com/Dstack-TEE/dstack/pull/73) +- Don'nt reboot if the e2fsck corrected the fs errors by @kvinwang +- Better logs by @kvinwang +- Show compose file in tcb info by @kvinwang +- Display app name by @kvinwang +- Extract config loading logic to crate load_config by @kvinwang +- Add qmp sock by @kvinwang +- Better status display by @kvinwang + +### Fixed +- Fix rev display by @kvinwang + +## [0.3.3] - 2024-12-19 + +### Added +- Add service wg-checker by @kvinwang +- Support for upgrade image by @kvinwang +- Support for disk resizing by @kvinwang +- Add log config by @kvinwang +- Add default docker daemon config by @kvinwang +- Support for boot progress report by @kvinwang +- Add endpoint to ra-rpc server-side by @kvinwang +- Add crate http-client by @kvinwang +- Add crate host-api by @kvinwang +- Add rocket-vsock-listener by @kvinwang +- Add load file button to reset secret panel by @kvinwang + +### Changed +- Make some codes more clear using cmd_lib by @kvinwang in [#71](https://github.com/Dstack-TEE/dstack/pull/71) +- Fix dev image does not upgrade by @kvinwang +- Remove since=1d from default logs url by @kvinwang +- Dstack v0.3.3 by @kvinwang in [#70](https://github.com/Dstack-TEE/dstack/pull/70) +- Merge pull request #69 from Dstack-TEE/kms-up by @kvinwang in [#69](https://github.com/Dstack-TEE/dstack/pull/69) +- Fix clippy by @kvinwang +- Allow upgrade base image by @kvinwang +- Fix first boot failure by @kvinwang +- Show version info on page by @kvinwang +- Fix error in console.html by @kvinwang +- Fix error removing .rootfs_hash in upgrading by @kvinwang +- Fix error in e2fsck by @kvinwang +- Fix error: missing bootstrapped when upgraded from old instance by @kvinwang +- Don't run docker compose pull by @kvinwang +- Merge pull request #68 from Dstack-TEE/wg-fix by @kvinwang in [#68](https://github.com/Dstack-TEE/dstack/pull/68) +- Set iptables to reject arbitray ip to send packets to wg port by @kvinwang +- Merge pull request #55 from Dstack-TEE/tappd-api by @kvinwang in [#55](https://github.com/Dstack-TEE/dstack/pull/55) +- Teepod & tappd: Default logs tail=20 by @kvinwang +- Handle app compose versioning by @kvinwang +- Support for optional logs/sysinfo API by @kvinwang +- Merge pull request #67 from Dstack-TEE/up-img by @kvinwang in [#67](https://github.com/Dstack-TEE/dstack/pull/67) +- Allow upgrade in 'exited' state by @kvinwang +- Sync dynamic config on start vm by @kvinwang +- Merge pull request #66 from Dstack-TEE/resize-disk by @kvinwang in [#66](https://github.com/Dstack-TEE/dstack/pull/66) +- Fix clippy by @kvinwang +- Turnneournald config by @kvinwang +- Web display by @kvinwang +- Only refress netinfo when running by @kvinwang +- Fix watchdog issue by @kvinwang +- Better status display by @kvinwang +- Merge pull request #64 from Dstack-TEE/tappd-wd by @kvinwang in [#64](https://github.com/Dstack-TEE/dstack/pull/64) +- Fix clippy by @kvinwang +- Add systemd watchdog by @kvinwang +- Merge pull request #65 from Dstack-TEE/docker-cfg by @kvinwang in [#65](https://github.com/Dstack-TEE/dstack/pull/65) +- Merge pull request #63 from Dstack-TEE/tappd-vsock by @kvinwang in [#63](https://github.com/Dstack-TEE/dstack/pull/63) +- Fix clippy by @kvinwang +- Adjust buttons layout by @kvinwang +- Reuse the same proto of guest api for teepod and tappd by @kvinwang +- Delegate tappd RPCs by @kvinwang +- Add guest api by @kvinwang +- Merge pull request #62 from Dstack-TEE/teepod-vsock by @kvinwang in [#62](https://github.com/Dstack-TEE/dstack/pull/62) +- Fix clippy by @kvinwang +- Accept boot progress report by @kvinwang +- Add client code in by @kvinwang +- Add prpc support by @kvinwang +- Impl host-api by @kvinwang +- Rename upgraded-app-id to compose-hash by @kvinwang +- Merge pull request #61 from Dstack-TEE/tproxy-url-rule by @kvinwang in [#61](https://github.com/Dstack-TEE/dstack/pull/61) +- The ending `s` in the url must be on the port part by @kvinwang +- Change logs since=1h to 0 by @kvinwang +- Merge pull request #60 from Dstack-TEE/tproxy-multi-connect by @kvinwang in [#60](https://github.com/Dstack-TEE/dstack/pull/60) +- Connect to multiple hosts by @kvinwang +- Fix clippy by @kvinwang +- Update prpc-build to 0.3.6 by @kvinwang +- Merge pull request #59 from Dstack-TEE/fix-app-id-on-reset by @kvinwang in [#59](https://github.com/Dstack-TEE/dstack/pull/59) +- Fix incorrect app-id on reset by @kvinwang +- Better logs filter by @kvinwang in [#58](https://github.com/Dstack-TEE/dstack/pull/58) +- Config for overall timeout for a connection by @kvinwang in [#57](https://github.com/Dstack-TEE/dstack/pull/57) +- Auto set ulimit -n by @kvinwang in [#56](https://github.com/Dstack-TEE/dstack/pull/56) +- Upgrade prpc-build to 0.3.5 by @kvinwang +- Upgrade to prpc-build 0.3.4 by @kvinwang +- Merge pull request #54 from Dstack-TEE/disable-scale-ext by @kvinwang in [#54](https://github.com/Dstack-TEE/dstack/pull/54) +- Disable scale ext for protos by @kvinwang +- Add load from file for secrets by @kvinwang +- Fix clippy by @kvinwang +- Merge pull request #52 from Dstack-TEE/vm-pty by @kvinwang in [#52](https://github.com/Dstack-TEE/dstack/pull/52) +- Open a pty for vm console by @kvinwang +- Merge pull request #51 from Dstack-TEE/cert-sign by @kvinwang in [#51](https://github.com/Dstack-TEE/dstack/pull/51) +- Add subcommand to sign a single cert by @kvinwang +- Use safe-write to store the state by @kvinwang +- Merge pull request #50 from Dstack-TEE/setup-wg by @kvinwang in [#50](https://github.com/Dstack-TEE/dstack/pull/50) +- Auto setup wg interface if not already by @kvinwang +- Merge pull request #49 from Dstack-TEE/fix-sdk-hint by @Leechael in [#49](https://github.com/Dstack-TEE/dstack/pull/49) +- Release js sdk 0.1.7 & python sdk 0.1.5 by @Leechael +- The length hint for raw report data in JS/TS SDK by @Leechael +- The length hint for raw report data in Python SDK by @Leechael +- Merge pull request #47 from Hyodar/feat/go-sdk by @kvinwang in [#47](https://github.com/Dstack-TEE/dstack/pull/47) +- Add package summary and author by @Hyodar +- Mention report data size and padding for raw hashing by @Hyodar +- Avoid unnecessary string operations by @Hyodar +- Add DeriveKeyWithSubject and DeriveKeyWithSubjectAndAltNames by @Hyodar +- Add TdxQuoteWithHashAlgorithm by @Hyodar +- Fix typo by @Hyodar +- Improve report data size check error on raw report by @Hyodar +- Add installation instructions and snippet by @Hyodar +- Add constructor options by @Hyodar +- Mention when altNames is included in the request by @Hyodar +- Avoid extra hex decoding in go SDK by @Hyodar +- Add logger to Tappd client creation in go SDK by @Hyodar +- Use info log instead of warn by @Hyodar +- Add RTMR replay to go SDK by @Hyodar +- Add hash algorithms support to go SDK by @Hyodar +- Add Go SDK README by @Hyodar +- Rename go package to tappd by @Hyodar +- Add Golang SDK by @Hyodar +- Simplify the syntax in Cargo.toml by @kvinwang +- Merge pull request #48 from Dstack-TEE/abspath by @kvinwang in [#48](https://github.com/Dstack-TEE/dstack/pull/48) +- Use path-absolutize instead of canonicalize by @kvinwang +- Merge pull request #45 from Dstack-TEE/sysinfo by @kvinwang in [#45](https://github.com/Dstack-TEE/dstack/pull/45) +- Fix cargo clippy by @kvinwang +- Add API SysInfo by @kvinwang + +### Fixed +- Keep js sdk padding behavior consistent to python sdk by @Leechael +- Fix raw hashing test using SHA512 by @Hyodar +- Parse RTMRs manually and remove go-tdx-qpl dependency by @Hyodar +- Move tests to test package by @Hyodar +- Test parsing TDX quotes by @Hyodar +- Add go SDK unit tests by @Hyodar +- Add Go SDK unit tests by @Hyodar + +## New Contributors +* @Hyodar made their first contribution +## [0.3.2] - 2024-12-09 + +### Added +- Add support for deriving an app instance by @kvinwang +- Add test case for reportdata check by @Leechael +- Add cargo test in action by @kvinwang +- Add github action clippy by @kvinwang +- Python SDK: add fn info() by @kvinwang +- Add killswitch contract by @kvinwang +- Add example crypt-kv by @kvinwang + +### Changed +- V0.3.2 by @kvinwang in [#44](https://github.com/Dstack-TEE/dstack/pull/44) +- Merge pull request #43 from Dstack-TEE/custom-appid by @kvinwang in [#43](https://github.com/Dstack-TEE/dstack/pull/43) +- Cargo fmt by @kvinwang +- Teepod ui: Support for updating vcpu and memory by @kvinwang +- Support custom app-id by @kvinwang +- Validate the compose file when upgrading by @kvinwang +- Only list loadable images by @kvinwang +- Merge pull request #42 from Dstack-TEE/sdk-test-case-for-reportdata-verification by @Leechael in [#42](https://github.com/Dstack-TEE/dstack/pull/42) +- Fix clippy warnings for latest Rust by @kvinwang +- Fix tests by @kvinwang +- Cargo clippy by @kvinwang +- Cargo fmt by @kvinwang +- Format code by @kvinwang +- Merge pull request #41 from Dstack-TEE/cert-time by @kvinwang in [#41](https://github.com/Dstack-TEE/dstack/pull/41) +- Set the default certificate validity period to 1 year by @kvinwang +- Merge pull request #11 from Dstack-TEE/killswitch by @kvinwang in [#11](https://github.com/Dstack-TEE/dstack/pull/11) +- Update notebook by @kvinwang +- Add client code by @kvinwang +- Allow owner to ban self by @kvinwang +- Add info for internal RPC by @kvinwang +- Merge pull request #10 from Dstack-TEE/crypt-kv by @kvinwang in [#10](https://github.com/Dstack-TEE/dstack/pull/10) +- Add ipynb by @kvinwang +- Reduce directory level by @kvinwang + +## [0.3.1] - 2024-12-05 + +### Added +- Add connect timeout & read first byte timeout for proxy by @Leechael +- Add hash_algorithm support python sdk by @Leechael +- Add VmMonitor.get_vm and VmInfo.to_pb by @Leechael +- Add Teepod.GetInfo & Teepod.ResizeVm by @Leechael +- Add TProxy.GetInfo by @Leechael +- Add supervisor by @kvinwang +- Add git rev to apps by @kvinwang +- Add cargo-check-all.sh by @kvinwang +- Support for docker login and registry mirror by @kvinwang +- Support for encrypted env vars by @kvinwang +- Add doc comment for tdxctl by @kvinwang +- Support for no KMS mode by @kvinwang +- Add tappd python client by @kvinwang +- Support for verify quote with PCCS by @kvinwang +- Add instance ID by @kvinwang +- Support to tls passthrough on common domain by @kvinwang +- Support for App Upgrade by @kvinwang +- Add contributors by @h4x3rotab +- Add troubleshooting by @h4x3rotab +- Add LICENSE by @kvinwang +- Support for dev version of image by @kvinwang +- Support for strip ansi colors by @kvinwang +- Add .cursorrules by @kvinwang +- Add certbot-cli by @kvinwang +- Add cert_bot and tests by @kvinwang +- Add Rust version ct_monitor by @kvinwang +- Add ct_monitor.py by @kvinwang +- Add certbot by @kvinwang +- Add user to libvirt group by @kvinwang +- Add external rpc for tappd by @kvinwang +- Add build script by @kvinwang +- Add list page for tproxy by @kvinwang +- Add --config for commands by @kvinwang +- Add vsock modules by @kvinwang +- Add missing cargo feature by @kvinwang +- Add test-scripts by @kvinwang +- Add tproxy by @kvinwang +- Add README.md by @kvinwang +- Support to install image by @kvinwang +- Add default config dir by @kvinwang +- Add teepod by @kvinwang +- Add tappd/tappd-rpc by @kvinwang +- Add mkguest by @kvinwang +- Add tdx-attest/tdxctl/iohash by @kvinwang +- Add tdx-attest-sys by @kvinwang +- Add kms-rpc,rarpc by @kvinwang +- Add kms by @kvinwang +- Add ratls by @kvinwang + +### Changed +- Bump version to 0.3.1 by @kvinwang in [#39](https://github.com/Dstack-TEE/dstack/pull/39) +- Merge pull request #32 from Leechael/feat-tproxy-timeouts by @kvinwang in [#32](https://github.com/Dstack-TEE/dstack/pull/32) +- Fix jupyter notebook not work when the browser using a proxy network by @kvinwang +- More flex timeout config and other refactor by @kvinwang +- Merge pull request #38 from Dstack-TEE/universion by @kvinwang in [#38](https://github.com/Dstack-TEE/dstack/pull/38) +- Extract dependencies to workspace level by @kvinwang +- Use universe version for all Rust crates by @kvinwang +- Merge pull request #36 from Leechael/feat-sdk-and-quote by @kvinwang in [#36](https://github.com/Dstack-TEE/dstack/pull/36) +- Update js sdk by @Leechael +- Update python sdk by @Leechael +- Copy sdk codes from tappd-simulator by @Leechael +- Merge pull request #37 from Dstack-TEE/nanometerzhu-readme-mkisofs by @kvinwang in [#37](https://github.com/Dstack-TEE/dstack/pull/37) +- Mkisofs is also essential by @nanometerzhu +- Add app version header by @kvinwang +- Fix cid already in use by @kvinwang +- Merge pull request #33 from Leechael/feat-apis by @kvinwang in [#33](https://github.com/Dstack-TEE/dstack/pull/33) +- Merge remote-tracking branch 'origin/master' into mrg-master by @kvinwang +- Comment on the resize disk size behavior by @Leechael +- Merge pull request #35 from Dstack-TEE/raw-report-data by @kvinwang in [#35](https://github.com/Dstack-TEE/dstack/pull/35) +- Default to sha512 by @kvinwang +- Support for chosing hash for quote by @kvinwang +- Log by @kvinwang +- Use abspath for supervisor bin by @kvinwang +- Merge pull request #34 from Dstack-TEE/supervisor by @kvinwang in [#34](https://github.com/Dstack-TEE/dstack/pull/34) +- Rm comment by @kvinwang +- Update tests by @kvinwang +- Rename by @kvinwang +- Fix a deadlock by @kvinwang +- Fix the broken default log level by @kvinwang +- Extract process management to a standalone process by @kvinwang +- Add probe based client creation by @kvinwang +- Add client lib by @kvinwang +- Support for redirect log file by @kvinwang +- Expose some process structs by @kvinwang +- Support daemonize self and --pid-file by @kvinwang +- Add config and cmd args by @kvinwang +- Update rocket-apitoken by @kvinwang +- Merge pull request #31 from Dstack-TEE/teepod-auth by @kvinwang in [#31](https://github.com/Dstack-TEE/dstack/pull/31) +- Support for bearer auth by @kvinwang +- Fix Upgrade failure by @kvinwang +- Show qemu log in serial.log by @kvinwang +- Disable buffering for nginx by @kvinwang +- Extract cc-eventlog as a crate by @kvinwang +- Fix reboot issue for no-fde instance by @kvinwang +- Merge pull request #30 from Dstack-TEE/opt-fde by @kvinwang in [#30](https://github.com/Dstack-TEE/dstack/pull/30) +- Support for opt-out disck encryption by @kvinwang +- Merge pull request #29 from Dstack-TEE/docker-login by @kvinwang in [#29](https://github.com/Dstack-TEE/dstack/pull/29) +- Merge pull request #28 from Dstack-TEE/up-rustls by @kvinwang in [#28](https://github.com/Dstack-TEE/dstack/pull/28) +- Update rustls to 0.23.19 by @kvinwang +- Fix console crash if vm files are removed by @kvinwang +- No ca cert if kms is disabled by @kvinwang +- Custom event type by @kvinwang in [#27](https://github.com/Dstack-TEE/dstack/pull/27) +- Show event log in tappd dashboard by @kvinwang +- Define RTMR3 digest format by @kvinwang +- Update dcap-qvl to 0.1.6 by @kvinwang +- Prpc returns non Result by @kvinwang +- Better event log format by @kvinwang +- Merge pull request #26 from Dstack-TEE/tboot-rs by @kvinwang in [#26](https://github.com/Dstack-TEE/dstack/pull/26) +- Fix tproxy crash by @kvinwang +- Minor rename by @kvinwang +- Configurable dir for tboot by @kvinwang +- Use Rust client instead of curl by @kvinwang +- Update prpc to 0.3 by @kvinwang +- Fix qemu net args by @kvinwang +- Fix pubkey update issue after instance reboot by @kvinwang +- Cargo fmt by @kvinwang +- Merge pull request #25 from Dstack-TEE/tboot-rs by @kvinwang in [#25](https://github.com/Dstack-TEE/dstack/pull/25) +- Rewrite tboot.sh in Rust by @kvinwang +- Merge pull request #24 from Dstack-TEE/tproxy-update-pubkey by @kvinwang in [#24](https://github.com/Dstack-TEE/dstack/pull/24) +- Reject register without pubkey by @kvinwang +- Don't allocate new ip for rebooted instance by @kvinwang +- Merge pull request #23 from Dstack-TEE/tproxy-loadbalance by @kvinwang in [#23](https://github.com/Dstack-TEE/dstack/pull/23) +- Load balance by @kvinwang +- Merge pull request #22 from Dstack-TEE/tproxy-persistent by @kvinwang in [#22](https://github.com/Dstack-TEE/dstack/pull/22) +- Show latest handshake by @kvinwang +- Save/Load state by @kvinwang +- Merge pull request #21 from Dstack-TEE/recycle by @kvinwang in [#21](https://github.com/Dstack-TEE/dstack/pull/21) +- Recycle stale instances by @kvinwang +- Merge pull request #19 from Dstack-TEE/custom-net by @kvinwang in [#19](https://github.com/Dstack-TEE/dstack/pull/19) +- Support for custom netdev by @kvinwang +- Merge pull request #18 from Dstack-TEE/sec-env by @kvinwang in [#18](https://github.com/Dstack-TEE/dstack/pull/18) +- Derive for env encrypt key by @kvinwang +- Break on io error by @kvinwang +- Merge pull request #17 from Dstack-TEE/rm-build-sh by @kvinwang in [#17](https://github.com/Dstack-TEE/dstack/pull/17) +- Move build.sh to repo meta-dstack by @kvinwang +- Merge pull request #16 from Dstack-TEE/tailf by @kvinwang in [#16](https://github.com/Dstack-TEE/dstack/pull/16) +- Workaround for client disconnect issue for logs by @kvinwang +- Use tailf instead of linemux for log tailling by @kvinwang +- Move some basefiles from meta-dstack to this repo by @kvinwang +- Bump version to dstack-0.2.0 by @kvinwang +- Merge pull request #15 from Dstack-TEE/teepod-show-detail by @kvinwang in [#15](https://github.com/Dstack-TEE/dstack/pull/15) +- Show vm instance detail information by @kvinwang +- Merge pull request #14 from Dstack-TEE/no-kms by @kvinwang in [#14](https://github.com/Dstack-TEE/dstack/pull/14) +- Merge pull request #13 from Dstack-TEE/port_map by @kvinwang in [#13](https://github.com/Dstack-TEE/dstack/pull/13) +- Support for mapping host port to CVM by @kvinwang +- Merge pull request #12 from Dstack-TEE/rm-mkguest by @kvinwang in [#12](https://github.com/Dstack-TEE/dstack/pull/12) +- Fix compilation error by @kvinwang +- Merge pull request #9 from Dstack-TEE/py-tappd by @kvinwang in [#9](https://github.com/Dstack-TEE/dstack/pull/9) +- Support for setting alt names in derive_key by @kvinwang +- Add fn derive_key by @kvinwang +- Update README by @kvinwang +- Merge pull request #8 from Dstack-TEE/ccel by @kvinwang in [#8](https://github.com/Dstack-TEE/dstack/pull/8) +- Handle eventlogs by @kvinwang +- Support for parsing CCEL logs by @kvinwang +- Set default PCCS URL to PCS by @kvinwang +- Update dcap-qvl by @kvinwang +- Merge pull request #7 from Dstack-TEE/ratls-verify by @kvinwang in [#7](https://github.com/Dstack-TEE/dstack/pull/7) +- Add subcommand rand by @kvinwang +- Auto refresh by @kvinwang +- Merge pull request #6 from Dstack-TEE/instance-id by @kvinwang in [#6](https://github.com/Dstack-TEE/dstack/pull/6) +- Update README for address by instance id and passthrough by @kvinwang +- Use instance url instead of app url for dashboard by @kvinwang +- Merge pull request #5 from Dstack-TEE/passthrough by @kvinwang in [#5](https://github.com/Dstack-TEE/dstack/pull/5) +- Better base domain striping from SNI by @kvinwang +- Fix IPs in build.sh by @kvinwang +- Merge pull request #4 from Dstack-TEE/define-report-data by @kvinwang in [#4](https://github.com/Dstack-TEE/dstack/pull/4) +- Define quote report_data format and check the cert pubkey by @kvinwang +- Remove app id preview by @kvinwang +- Merge pull request #3 from Dstack-TEE/app-compose by @kvinwang in [#3](https://github.com/Dstack-TEE/dstack/pull/3) +- Switch to App compose format by @kvinwang +- Turn deploy into dialog by @kvinwang +- Check config by @kvinwang +- Better error message by @kvinwang +- Merge pull request #2 from Dstack-TEE/upgrade-app by @kvinwang in [#2](https://github.com/Dstack-TEE/dstack/pull/2) +- Support for App Upgrade by @kvinwang +- Store issued certs to fs by @kvinwang +- Merge pull request #1 from Dstack-TEE/contributors by @kvinwang in [#1](https://github.com/Dstack-TEE/dstack/pull/1) +- Update repo URL by @kvinwang +- Update README.md by @kvinwang +- Remove rproxy and implement our own by @kvinwang +- Fix md syntax by @kvinwang +- Update Cargo.lock by @kvinwang +- Update README.md by @kvinwang +- Fix utf8 decoding error in log by @kvinwang +- Default to show 1 hour logs by @kvinwang +- Implement TLS passthrough by @kvinwang +- Move deployed containers up by @kvinwang +- Optimiza tappd dashboard by @kvinwang +- Sort by create time by @kvinwang +- Support for start/remove by @kvinwang +- Support for reloading VMs by @kvinwang +- Modify manifest when stop vm by @kvinwang +- Use vm name and image name by @kvinwang +- Pretify console.html by @kvinwang +- Add link to tproxy by @kvinwang +- Support for bare log lines by @kvinwang +- Fix cvm log lines by @kvinwang +- Default to use dstack-0.1.0-dev by @kvinwang +- Add CID pool by @kvinwang +- Streaming API for CVM logs by @kvinwang +- Fix v9 mount name by @kvinwang +- Minor log fix by @kvinwang +- Add api to get Docker logs by @kvinwang +- Add subcommand add-caa by @kvinwang +- Don't add wg if exists by @kvinwang +- Better log by @kvinwang +- Soundness CAA setting by @kvinwang +- Support for adding CAA by @kvinwang +- Refine logs by @kvinwang +- Report error when CT log missing by @kvinwang +- CT log support for tproxy by @kvinwang +- Minor rename by @kvinwang +- Minor refactor by @kvinwang +- Use fs_err by @kvinwang +- Add auto renew feature by @kvinwang +- Add some doc comments by @kvinwang +- Adapt yocto by @kvinwang +- Make tdx-guest compatible with kernel 6.6 by @kvinwang +- Make mod tdx-guest compatible with yocto by @kvinwang +- Move tdx-guest src to root by @kvinwang +- Use syncconf instead of setconf by @kvinwang +- Use rinja for tproxy page by @kvinwang +- Use rinja instead of minijinja by @kvinwang +- Fix tests by @kvinwang +- Simplify the config file format by @kvinwang +- Minor rename by @kvinwang +- Mod default build config values by @kvinwang +- Minor HTML label change by @kvinwang +- Truncate rootfs hash to 64 by @kvinwang +- Better permission require in prepare_env.sh by @kvinwang +- Turn /tapp/config to /tapp by @kvinwang +- Show containers in Tappd by @kvinwang +- Fix invalid url by @kvinwang +- Fix incomplate build.sh by @kvinwang +- Fix empty attestation in CaCert by @kvinwang +- Enable ssh passwd login by @kvinwang +- Fix run scripts by @kvinwang +- Portmap for tproxy by @kvinwang +- Move the rpc crates into it's main crate by @kvinwang +- Use rproxy as a library by @kvinwang +- Change default config for kms by @kvinwang +- Teepod can run CVMs now by @kvinwang +- Add rpc List by @kvinwang +- Reconfig wg and proxy on startup by @kvinwang +- Truncate app id to 40 chars by @kvinwang +- Fix wg config issues by @kvinwang +- Optimize makefile by @kvinwang +- Fix a warning by @kvinwang +- Update ubuntu to 20240911 by @kvinwang +- Initramfs works now by @kvinwang +- Update kmfs by @kvinwang +- Update README.md by @kvinwang +- Refactor initrd by @kvinwang +- Create certgen by @kvinwang +- Implement derive key by @kvinwang +- Fix wg & rproxy config issues by @kvinwang +- Gen cert signed by ca file by @kvinwang +- Record empty app-id in MR by @kvinwang +- Fix panic in gen-ra-cert by @kvinwang +- Remvoe ifname from config by @kvinwang +- Use wg-quick to config wg interface by @kvinwang +- Exclude self-ip from the client pool by @kvinwang +- Add tests by @kvinwang +- Add EventLog by @kvinwang +- Better logs display by @kvinwang +- Fix mutlpile instance start failure by @kvinwang +- Fix initramfs hooks by @kvinwang +- Implement vm deployment by @kvinwang +- Port teepod to prpc by @kvinwang +- Add rpc TdxQuote by @kvinwang +- Implement rpc DeriveKey for tappd by @kvinwang +- Implement kdf for rcgen::KeyPair by @kvinwang +- Load app key by @kvinwang +- Use fs-err for better error message by @kvinwang +- Minor rename by @kvinwang +- Refactor kms-rpc file structure by @kvinwang +- Add --get-ra-cert by @kvinwang +- Implement RA RPC by @kvinwang +- Add Attestation extractor by @kvinwang + +### Removed +- Remove a todo comment by @kvinwang +- Remove ubuntu-based image making by @kvinwang +- Remove app_info from cert by @kvinwang +- Remove deps on openssl by @kvinwang +- Remove the account_id workaround by @kvinwang +- Remove error in build.sh by @kvinwang +- Remove unused code by @kvinwang +- Remove certs dir by @kvinwang + +## New Contributors +* @Leechael made their first contribution +* @nanometerzhu made their first contribution +* @h4x3rotab made their first contribution +[unreleased]: https://github.com/Dstack-TEE/dstack/compare/v0.6.1..HEAD +[0.6.1]: https://github.com/Dstack-TEE/dstack/compare/v0.6.0..v0.6.1 +[0.6.0]: https://github.com/Dstack-TEE/dstack/compare/v0.5.11..v0.6.0 +[0.5.5]: https://github.com/Dstack-TEE/dstack/compare/v0.5.4..v0.5.5 +[0.5.4]: https://github.com/Dstack-TEE/dstack/compare/v0.5.3..v0.5.4 +[0.5.3]: https://github.com/Dstack-TEE/dstack/compare/v0.5.2..v0.5.3 +[0.5.2]: https://github.com/Dstack-TEE/dstack/compare/v0.5.1..v0.5.2 +[0.5.1]: https://github.com/Dstack-TEE/dstack/compare/v0.5.0..v0.5.1 +[0.5.0]: https://github.com/Dstack-TEE/dstack/compare/v0.4.2..v0.5.0 +[0.4.2]: https://github.com/Dstack-TEE/dstack/compare/dev-v0.4.0.0..v0.4.2 +[dev-v0.4.0.0]: https://github.com/Dstack-TEE/dstack/compare/v0.3.4..dev-v0.4.0.0 +[0.3.4]: https://github.com/Dstack-TEE/dstack/compare/v0.3.4-beta..v0.3.4 +[0.3.4-beta]: https://github.com/Dstack-TEE/dstack/compare/v0.3.3..v0.3.4-beta +[0.3.3]: https://github.com/Dstack-TEE/dstack/compare/v0.3.2..v0.3.3 +[0.3.2]: https://github.com/Dstack-TEE/dstack/compare/v0.3.1..v0.3.2 + + diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000000..a42d3f073c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,253 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +dstack is a developer-friendly, security-first framework for deploying containerized applications into Intel TDX (Trust Domain Extensions) Trusted Execution Environments (TEEs). The system provides end-to-end security through hardware-rooted attestation, automated key management, and zero-trust networking. + +The monorepo keeps core services and the Rust workspace in `dstack/`, public +SDKs in `sdk/`, guest-OS builders in `os/`, documentation in `docs/`, and +standalone utilities in `tools/`. + +## Architecture + +dstack consists of several core components that interact to provide TEE-based container deployment: + +### Core Components + +- **`dstack-vmm`** (`dstack/vmm/`): Virtual Machine Manager that runs on bare-metal TDX hosts. Orchestrates CVM lifecycle, manages QEMU processes, allocates resources, parses docker-compose files, and provides a web UI (port 9080) for deployment. + +- **`dstack-kms`** (`dstack/kms/`): Key Management System that handles cryptographic key provisioning after TDX quote verification. Derives keys deterministically per application identity and enforces authorization policies defined in smart contracts on Ethereum. + +- **`dstack-gateway`** (`dstack/gateway/`): Reverse proxy providing zero-trust network access. Handles TLS termination, automated ACME certificate provisioning, and traffic routing via ingress mapping rules. + +- **`dstack-guest-agent`** (`dstack/guest-agent/`): Runs inside each CVM to provide runtime services including Docker Compose lifecycle management, TDX quote generation, key provisioning from KMS, and log aggregation. Exposes API via Unix socket at `/var/run/dstack.sock`. + +### Communication Protocols + +- **RA-TLS**: Remote Attestation TLS used for all inter-CVM communication, embedding TDX quotes in X.509 certificates for mutual authentication +- **`prpc`**: Protocol Buffers-based RPC framework used across all service APIs +- **`vsock`**: Host-guest communication channel for metadata and configuration +- **Unix Domain Sockets**: Used for local management (e.g., `vmm.sock`) + +### Additional Components + +- **`certbot`** (`dstack/certbot/`): Automated ACME DNS-01 certificate management +- **`ct_monitor`** (`dstack/ct_monitor/`): Certificate Transparency log monitoring +- **`verifier`** (`dstack/verifier/`): TDX quote verification service using `dcap-qvl` +- **`supervisor`** (`dstack/supervisor/`): Process supervision inside CVMs +- **SDKs** (`sdk/`): Client SDKs in Rust, Python, Go, and JavaScript for interacting with guest-agent APIs + +## Build Commands + +### Rust Components + +```bash +cd dstack + +# Build all components +cargo build --release + +# Build specific components +cargo build --release -p dstack-vmm +cargo build --release -p dstack-kms +cargo build --release -p dstack-gateway +cargo build --release -p dstack-guest-agent +cargo build --release -p dstack-guest-agent-simulator + +# Check code +cargo check --all-features + +# Format code +cargo fmt --all + +# Lint with Clippy +cargo clippy -- -D warnings --allow unused_variables +``` + +### Ethereum Smart Contracts (KMS Auth) + +```bash +cd dstack/kms/auth-eth +git submodule update --init --recursive lib/forge-std \ + lib/openzeppelin-contracts-upgradeable lib/openzeppelin-foundry-upgrades +# Upgrade-safety validator called by `forge test --ffi` +npx --yes @openzeppelin/upgrades-core@^1.37.0 --help > /dev/null + +# Build +forge build # Compile smart contracts + +# Test +forge clean && forge test --ffi # Run Foundry contract tests + +# Local development +anvil # Start local Ethereum node +``` + +The KMS webhook server for these contracts lives in the same directory +(`bun install && bun run check`). + +### Python SDK + +```bash +cd sdk/python +make install # Install dependencies +make test # Run tests +``` + +## Test Commands + +### Running All Tests + +```bash +# Run all Rust tests (requires simulator) +./dstack/run-tests.sh +``` + +This script: +1. Builds the SDK simulator (`sdk/simulator/`) +2. Starts the simulator in background +3. Sets `DSTACK_SIMULATOR_ENDPOINT` and `TAPPD_SIMULATOR_ENDPOINT` +4. Runs `cargo test --all-features -- --show-output` + +### Running Specific Tests + +```bash +cd dstack + +# Run tests for a specific package +cargo test -p dstack-kms --all-features + +# Run a specific test +cargo test --all-features test_name + +# Run tests with output +cargo test --all-features -- --show-output --test-threads=1 +``` + +### Foundry Tests (Ethereum Contracts) + +```bash +cd dstack/kms/auth-eth + +# Run all Foundry tests +forge test --ffi + +# Run with verbosity +forge test -vv + +# Run specific test contract +forge test --match-contract UpgradesWithPluginTest -vv + +# Clean build artifacts +forge clean +``` + +## Code Style Guidelines + +### Logging and Error Messages + +- Start log messages and error messages with lowercase text +- Preserve the conventional capitalization of identifiers and acronyms when they + begin a message (for example, `RIM`, `OCSP`, or `HTTP`) +- Example: `log::info!("starting server on port {}", port);` +- Example: `anyhow::bail!("failed to connect to server");` +- Example: `log::warn!("RIM upstream is unavailable");` + +## Key Security Concepts + +### Attestation Flow + +1. **Quote Generation**: Applications request TDX quotes via `getQuote()` with reportData (up to 64 bytes) +2. **Quote Verification**: `dstack-verifier` validates quotes using `dcap-qvl`, verifies OS image hash, and replays RTMRs from event logs +3. **RTMR Replay**: Compute Runtime Measurement Register values by applying SHA384 hashing to event log entries + +### Key Management + +- **Deterministic Keys**: `getKey(path, purpose)` derives secp256k1 keys using HKDF, with signature chains proving TEE origin +- **TLS Keys**: `getTlsKey()` generates fresh X.509 certificates with optional RA-TLS support +- **Environment Encryption**: Client-side encryption using X25519 ECDH + AES-256-GCM, decrypted only in TEE + +### Smart Contract Integration + +- **DstackKms**: Main KMS contract managing OS image whitelist and app registration +- **DstackApp**: Per-app authorization contract controlling device IDs and compose hash whitelist +- Deployed on Ethereum-compatible networks (Phala Network) + +## Development Workflow + +### Local Development Setup + +1. Build guest-OS artifacts with `make os-image`, which uses the default mkosi + backend (see `docs/building-guest-os.md`). The Yocto backend (`os/yocto/`, + `make os-image-yocto`, `--backend yocto`) is deprecated: never use it for new + images or features. Do not delete `os/yocto/` either: mkosi still reads + patches, units, and scripts from it (`grep -rn yocto os/mkosi`) +2. Download or build guest OS image +3. Run components in separate terminals: + - KMS: `./dstack-kms -c kms.toml` + - Gateway: `sudo ./dstack-gateway -c gateway.toml` + - VMM: `./dstack-vmm -c vmm.toml` + +### Deploying Apps + +- Via Web UI: `http://localhost:9080` (or configured port) +- Via CLI: `./vmm-cli.py` (see `docs/vmm-cli-user-guide.md`) +- Requires: + 1. On-chain app registration (see `docs/onchain-governance.md`) + 2. Adding compose hash to whitelist + 3. Deploying via VMM with App ID + +### Accessing Deployed Apps + +Ingress mapping pattern: `[-[][s|g]].` +- Default: TLS termination to TCP +- `s` suffix: TLS passthrough +- `g` suffix: HTTP/2 with TLS termination (gRPC) + +## Important Files + +- `dstack/Cargo.toml`: Workspace configuration with all Rust crates +- `dstack/vmm/vmm.toml`: VMM configuration (CID pool, port mapping, KMS/gateway URLs) +- `dstack/kms/kms.toml`: KMS configuration (contract addresses, RPC endpoints) +- `dstack/gateway/gateway.toml`: Gateway configuration (domain, certificates, WireGuard) +- `docker-compose.yaml`: App deployment format (normalized to `.app-compose.json`) + +## Common Tasks + +### Adding a New Rust Crate + +1. Create crate directory and `Cargo.toml` +2. Add to workspace members in `dstack/Cargo.toml` +3. Add workspace dependency if it will be used by other crates + +### Modifying RPC APIs + +RPC definitions use `prpc` framework with Protocol Buffers: +- Define `.proto` files in `*/rpc/proto/` +- Use `prpc-build` in `build.rs` to generate Rust code +- Implement service traits in main crate + +### Working with TDX Quotes + +- Pure Rust API: `dstack/tdx-attest/` +- Verification: `dstack/verifier/` using `dcap-qvl` +- Event log parsing: `dstack/cc-eventlog/` + +## Documentation + +- Main README: `README.md` +- Deployment guide: `docs/deployment.md` +- VMM CLI guide: `docs/vmm-cli-user-guide.md` +- Security guide: `docs/security-guide/security-guide.md` +- Design decisions: `docs/design-and-hardening-decisions.md` + +When need more detailed info, try to use deepwiki mcp. + +## Agent Resources + +The `.agent/` directory contains AI assistant resources: +- `CODING_TASTE.md` — dstack code and PR conventions (API design, compat, security reasoning, code style, project structure, PR style) +- `WRITING_GUIDE.md` — Documentation and README writing guidelines (messaging, style, audiences) +- `GPU_TEE_DEPLOYMENT.md` — GPU deployment to Phala Cloud (instance types, docker-compose config, debugging) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..7c0d186a05 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +dstack@phala.network. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..e1143cf5ab --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,163 @@ +# Contributing + +Thank you for your interest in contributing to this project! + +## Branches + +- `next` is the integration mainline and the default branch. Open every pull + request against it unless a maintainer asks otherwise. +- `release/v..x` carries a released line — `release/v0.5.x` is + the current one. It only takes fixes cherry-picked back from `next`; do not + develop on it directly. Patch tags are cut here. + +Name a working branch whatever describes it. CI runs on pull requests, so a +branch gets its checks once a PR is open rather than on every push. + +The default branch was renamed from `master` to `next`. Web links, raw file +URLs, and the REST API redirect, but the old ref name is gone at the git +level: `git fetch origin master` and `git clone -b master` now fail. Update an +existing clone with: + +```bash +git branch -m master next +git fetch origin +git branch -u origin/next next +git remote set-head origin -a +``` + +## Development + +1. Fork the repository +2. Create a feature branch (`git checkout -b feature/amazing-feature`) +3. Make your changes +4. Commit your changes using conventional commits and a DCO sign-off +5. Push to the branch (`git push origin feature/amazing-feature`) +6. Open a Pull Request + +## Repository layout + +- `dstack/` contains the core Rust workspace and component-owned assets. Keep a + component's build, deployment, test, and API documentation next to that + component when it is not useful outside the component. +- `sdk/` contains the public language SDKs and simulator. +- `os/` contains the backend-neutral guest-OS contract, image assembly, common + guest payload, and backend implementations. A file under `os//` + must be specific to that backend. +- `docs/` contains repository-wide developer, operator, architecture, and + security documentation. Do not put a product guide at the repository root. +- `examples/` contains supported end-user examples. +- `tools/` contains cross-component developer/operator utilities. Put a script + here instead of under an OS backend when it also builds or configures the + host, deploys services, or operates on multiple components. +- `.github/` contains GitHub Actions workflows and workflow-only helpers. + +Use the narrowest owning directory. Fixture explanations and component +READMEs should stay with their fixtures/components; general guides should be +linked from the root README and live under `docs/`. + +## Test a guest without TEE hardware + +Development images include the extensible `dstack-tee-simulator`. Its default +platform backend is TDX. On a VM launched with `no_tee`, that backend exposes +the Linux interfaces used by the normal guest software: + +- configfs-tsm quote generation under `/sys/kernel/config/tsm/report`; +- RTMR extension files used by `tdx-attest`; +- a CCEL boot-event fixture. + +This keeps `dstack-prepare`, measurement, encrypted-storage setup, the guest +agent, and attestation APIs on their production code paths. The generated quote +has an intentionally invalid signature, so a production verifier or KMS must +reject it. + +The service uses the default TDX backend. For direct simulator development, the +same selection can be made explicitly with `dstack-tee-simulator --platform +tdx`. New TEE platforms are implemented as separate backends behind the shared +simulator lifecycle. + +Build or install a `dstack-dev-*` image, then deploy without KMS or gateway: + +```bash +dstack deploy ./docker-compose.yml \ + --name no-tee-dev \ + --image dstack-dev-VERSION \ + --no-kms \ + --no-tee +``` + +To exercise persistent TPM-backed app keys as well, install `swtpm` on the VMM +host and select `key_provider=tpm` in the VMM console (or pass `--key-provider +tpm` in tooling that exposes the compose option). The VMM keeps the software +TPM state in the VM work directory so that seal/unseal survives guest restarts. +The software TPM is host-controlled and does not provide hardware isolation. + +The simulator package is installed only in development images. This mode +provides no hardware isolation and must never be used with production +workloads or secrets. Real quote generation, hardware isolation, and KMS +authorization still require TDX or another supported TEE. + +## Developer Certificate of Origin (DCO) + +All contributions must include a sign-off under the [Developer Certificate of +Origin, version 1.1](https://developercertificate.org/). By signing off, you +certify that you wrote the contribution or otherwise have the right to submit +it under this project's open-source license. + +Add the sign-off when creating a commit: + +```bash +git commit -s -m "feat: describe the change" +``` + +Git adds a line such as the following to the commit message, using your Git +identity: + +``` +Signed-off-by: Your Name +``` + +Every commit in a pull request must be signed off. To add a missing sign-off to +the most recent commit, run `git commit --amend --signoff`. For several commits, +use `git rebase --signoff ` before opening or updating the pull +request. + +## Commit Convention + +This project uses [Conventional Commits](https://www.conventionalcommits.org/). Please format your commit messages as: + +``` +: + +[optional body] +``` + +Examples: +- `feat: add user authentication` +- `fix: resolve memory leak in worker process` +- `docs: update API documentation` + +## Changelog + +The changelog is automatically generated using [git-cliff](https://git-cliff.org/). To update the changelog: + +```bash +git-cliff --output CHANGELOG.md +``` + +The changelog follows the [Keep a Changelog](https://keepachangelog.com/) format and includes GitHub integration for PR links and contributor recognition. + +## License + +This project uses SPDX headers for license compliance. You should add appropriate SPDX headers to all your source files. + +We have a script to automatically add SPDX headers based on git blame data: + +```bash +python3 tools/add-spdx-attribution.py --file path/to/file.rs +``` + +Before submitting your changes, verify SPDX compliance using the [REUSE tool](https://github.com/fsfe/reuse-tool): + +```bash +reuse lint +``` diff --git a/Cargo.lock b/Cargo.lock deleted file mode 100644 index 95141ea463..0000000000 --- a/Cargo.lock +++ /dev/null @@ -1,6211 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5fb1d8e4442bd405fdfd1dacb42792696b0cf9cb15882e5d097b742a676d375" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" - -[[package]] -name = "aead" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" -dependencies = [ - "crypto-common", - "generic-array", -] - -[[package]] -name = "aes" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" -dependencies = [ - "cfg-if", - "cipher", - "cpufeatures", -] - -[[package]] -name = "aes-gcm" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" -dependencies = [ - "aead", - "aes", - "cipher", - "ctr", - "ghash", - "subtle", -] - -[[package]] -name = "ahash" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" -dependencies = [ - "cfg-if", - "once_cell", - "version_check", - "zerocopy", -] - -[[package]] -name = "aho-corasick" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" -dependencies = [ - "memchr", -] - -[[package]] -name = "allocator-api2" -version = "0.2.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c6cb57a04249c6480766f7f7cef5467412af1490f8d1e243141daddada3264f" - -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "anstream" -version = "0.6.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1" - -[[package]] -name = "anstyle-parse" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a" -dependencies = [ - "windows-sys 0.52.0", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8" -dependencies = [ - "anstyle", - "windows-sys 0.52.0", -] - -[[package]] -name = "anyhow" -version = "1.0.94" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1fd03a028ef38ba2276dce7e33fcd6369c158a1bca17946c4b1b701891c1ff7" - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" - -[[package]] -name = "asn1-rs" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048" -dependencies = [ - "asn1-rs-derive", - "asn1-rs-impl", - "displaydoc", - "nom", - "num-traits", - "rusticata-macros", - "thiserror 1.0.65", - "time", -] - -[[package]] -name = "asn1-rs-derive" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "965c2d33e53cb6b267e148a4cb0760bc01f4904c1cd4bb4002a085bb016d1490" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", - "synstructure", -] - -[[package]] -name = "asn1-rs-impl" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "asn1_der" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "155a5a185e42c6b77ac7b88a15143d930a9e9727a5b7b77eed417404ab15c247" - -[[package]] -name = "async-stream" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "async-trait" -version = "0.1.82" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a27b8a3a6e1a44fa4c8baf1f653e4172e81486d4941f2237e20dc2d0cf4ddff1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "atomic" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d818003e740b63afc82337e3160717f4f63078720a810b7b903e70a5d1d2994" -dependencies = [ - "bytemuck", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" - -[[package]] -name = "aws-lc-rs" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f95446d919226d587817a7d21379e6eb099b97b45110a7f272a444ca5c54070" -dependencies = [ - "aws-lc-sys", - "mirai-annotations", - "paste", - "untrusted 0.7.1", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "234314bd569802ec87011d653d6815c6d7b9ffb969e9fee5b8b20ef860e8dce9" -dependencies = [ - "bindgen 0.69.4", - "cc", - "cmake", - "dunce", - "fs_extra", - "libc", - "paste", -] - -[[package]] -name = "backtrace" -version = "0.3.74" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-targets 0.52.6", -] - -[[package]] -name = "base16ct" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" - -[[package]] -name = "base64" -version = "0.21.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "base64ct" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c3c1a368f70d6cf7302d78f8f7093da241fb8e8807c05cc9e51a125895a6d5b" - -[[package]] -name = "basic-toml" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "823388e228f614e9558c6804262db37960ec8821856535f5c3f59913140558f8" -dependencies = [ - "serde", -] - -[[package]] -name = "binascii" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" - -[[package]] -name = "bindgen" -version = "0.69.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00dc851838a2120612785d195287475a3ac45514741da670b735818822129a0" -dependencies = [ - "bitflags 2.6.0", - "cexpr", - "clang-sys", - "itertools 0.10.5", - "lazy_static", - "lazycell", - "log", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash 1.1.0", - "shlex", - "syn 2.0.87", - "which 4.4.2", -] - -[[package]] -name = "bindgen" -version = "0.70.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" -dependencies = [ - "bitflags 2.6.0", - "cexpr", - "clang-sys", - "itertools 0.13.0", - "log", - "prettyplease", - "proc-macro2", - "quote", - "regex", - "rustc-hash 1.1.0", - "shlex", - "syn 2.0.87", -] - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" - -[[package]] -name = "bitvec" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c" -dependencies = [ - "funty", - "radium", - "tap", - "wyz", -] - -[[package]] -name = "blake2" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" -dependencies = [ - "digest", -] - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bollard" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97ccca1260af6a459d75994ad5acc1651bcabcbdbc41467cc9786519ab854c30" -dependencies = [ - "base64 0.22.1", - "bollard-stubs", - "bytes", - "futures-core", - "futures-util", - "hex", - "http 1.2.0", - "http-body-util", - "hyper 1.5.1", - "hyper-named-pipe", - "hyper-util", - "hyperlocal", - "log", - "pin-project-lite", - "serde", - "serde_derive", - "serde_json", - "serde_repr", - "serde_urlencoded", - "thiserror 2.0.4", - "tokio", - "tokio-util", - "tower-service", - "url", - "winapi", -] - -[[package]] -name = "bollard-stubs" -version = "1.47.1-rc.27.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f179cfbddb6e77a5472703d4b30436bff32929c0aa8a9008ecf23d1d3cdd0da" -dependencies = [ - "serde", - "serde_repr", - "serde_with", -] - -[[package]] -name = "bon" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9276fe602371cd8a7f70fe68c4db55b2d3e92c570627d6ed0427646edfa5cf47" -dependencies = [ - "bon-macros", - "rustversion", -] - -[[package]] -name = "bon-macros" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94828b84b32b4f3ac3865f692fcdbc46c7d0dd87b29658a391d58a244e1ce45a" -dependencies = [ - "darling", - "ident_case", - "prettyplease", - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.87", -] - -[[package]] -name = "bstr" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40723b8fb387abc38f4f4a37c09073622e41dd12327033091ef8950659e6dc0c" -dependencies = [ - "memchr", - "regex-automata 0.4.8", - "serde", -] - -[[package]] -name = "bumpalo" -version = "3.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" - -[[package]] -name = "byte-slice-cast" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3ac9f8b63eca6fd385229b3675f6cc0dc5c8a5c8a54a59d4f52ffd670d87b0c" - -[[package]] -name = "bytemuck" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94bbb0ad554ad961ddc5da507a12a29b14e4ae5bda06b19f575a3e6079d2e2ae" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "325918d6fe32f23b19878fe4b34794ae41fc19ddbe53b10571a4874d44ffd39b" - -[[package]] -name = "cc" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f34d93e62b03caf570cccc334cbc6c2fceca82f39211051345108adcba3eebdc" -dependencies = [ - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cc-eventlog" -version = "0.3.4" -dependencies = [ - "anyhow", - "fs-err", - "hex", - "insta", - "parity-scale-codec", - "serde", - "serde-human-bytes", - "serde_json", - "sha2", -] - -[[package]] -name = "certbot" -version = "0.3.4" -dependencies = [ - "anyhow", - "bon", - "enum_dispatch", - "fs-err", - "hickory-resolver", - "instant-acme", - "path-absolutize", - "rand 0.8.5", - "rcgen", - "reqwest 0.12.9", - "serde", - "serde_json", - "time", - "tokio", - "tracing", - "tracing-subscriber", - "x509-parser", -] - -[[package]] -name = "certbot-cli" -version = "0.3.4" -dependencies = [ - "anyhow", - "certbot", - "clap", - "documented", - "fs-err", - "rustls 0.23.19", - "serde", - "tokio", - "toml_edit", - "tracing-subscriber", -] - -[[package]] -name = "certgen" -version = "0.3.4" -dependencies = [ - "anyhow", - "clap", - "fs-err", - "ra-tls", -] - -[[package]] -name = "cexpr" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" -dependencies = [ - "nom", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - -[[package]] -name = "chrono" -version = "0.4.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" -dependencies = [ - "android-tzdata", - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-targets 0.52.6", -] - -[[package]] -name = "cipher" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" -dependencies = [ - "crypto-common", - "inout", -] - -[[package]] -name = "clang-sys" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4" -dependencies = [ - "glob", - "libc", - "libloading", -] - -[[package]] -name = "clap" -version = "4.5.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69371e34337c4c984bbe322360c2547210bf632eb2814bbe78a6e87a2935bd2b" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.5.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e24c1b4099818523236a8ca881d2b45db98dadfb4625cf6608c12069fcbbde1" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ac6a0c7b1a9e9a5186361f67dfa1b88213572f427fb9ab038efb2bd8c582dab" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "clap_lex" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1462739cb27611015575c0c11df5df7601141071f07518d56fcc1be504cbec97" - -[[package]] -name = "cmake" -version = "0.1.51" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb1e43aa7fd152b1f968787f7dbcdeb306d1867ff373c69955211876c053f91a" -dependencies = [ - "cc", -] - -[[package]] -name = "cmd_lib" -version = "1.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "371c15a3c178d0117091bd84414545309ca979555b1aad573ef591ad58818d41" -dependencies = [ - "cmd_lib_macros", - "env_logger", - "faccess", - "lazy_static", - "log", - "os_pipe", -] - -[[package]] -name = "cmd_lib_macros" -version = "1.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb844bd05be34d91eb67101329aeba9d3337094c04fd8507d821db7ebb488eaf" -dependencies = [ - "proc-macro-error2", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "colorchoice" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0" - -[[package]] -name = "console" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" -dependencies = [ - "encode_unicode", - "lazy_static", - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "const-oid" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" - -[[package]] -name = "convert_case" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "cookie" -version = "0.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" -dependencies = [ - "percent-encoding", - "time", - "version_check", -] - -[[package]] -name = "core-foundation" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "cpufeatures" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613f8cc01fe9cf1a3eb3d7f488fd2fa8388403e97039e2f73692932e291a770d" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22ec99545bb0ed0ea7bb9b8e1e9122ea386ff8a48c0922e43f36d45ab09e0e80" - -[[package]] -name = "crypto-bigint" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "subtle", - "zeroize", -] - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array", - "rand_core 0.6.4", - "typenum", -] - -[[package]] -name = "ct_monitor" -version = "0.3.4" -dependencies = [ - "anyhow", - "clap", - "hex_fmt", - "ra-rpc", - "regex", - "reqwest 0.12.9", - "serde", - "serde_json", - "tokio", - "tproxy-rpc", - "tracing", - "tracing-subscriber", - "x509-parser", -] - -[[package]] -name = "ctr" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" -dependencies = [ - "cipher", -] - -[[package]] -name = "cuckoofilter" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b810a8449931679f64cd7eef1bbd0fa315801b6d5d9cdc1ace2804d6529eee18" -dependencies = [ - "byteorder", - "fnv", - "rand 0.7.3", -] - -[[package]] -name = "curve25519-dalek" -version = "4.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" -dependencies = [ - "cfg-if", - "cpufeatures", - "curve25519-dalek-derive", - "digest", - "fiat-crypto", - "rustc_version", - "subtle", - "zeroize", -] - -[[package]] -name = "curve25519-dalek-derive" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "darling" -version = "0.20.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.20.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn 2.0.87", -] - -[[package]] -name = "darling_macro" -version = "0.20.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" -dependencies = [ - "darling_core", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "dashmap" -version = "6.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf" -dependencies = [ - "cfg-if", - "crossbeam-utils", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core", -] - -[[package]] -name = "data-encoding" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2" - -[[package]] -name = "dcap-qvl" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e024d399632fb2e97a9501e79779ae9f150118a17ad06333de3bbd42834b84" -dependencies = [ - "anyhow", - "asn1_der", - "base64 0.21.7", - "byteorder", - "chrono", - "const-oid", - "der", - "futures", - "hex", - "log", - "parity-scale-codec", - "pem", - "reqwest 0.11.27", - "ring", - "rustls-webpki 0.102.8", - "scale-info", - "serde", - "serde_bytes", - "serde_json", - "tracing", - "urlencoding", - "x509-cert", -] - -[[package]] -name = "default-net" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c5a6569a908354d49b10db3c516d69aca1eccd97562fd31c98b13f00b73ca66" -dependencies = [ - "dlopen2", - "libc", - "memalloc", - "netlink-packet-core", - "netlink-packet-route", - "netlink-sys", - "once_cell", - "system-configuration", - "windows 0.48.0", -] - -[[package]] -name = "der" -version = "0.7.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" -dependencies = [ - "const-oid", - "der_derive", - "flagset", - "pem-rfc7468", - "zeroize", -] - -[[package]] -name = "der-parser" -version = "9.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cd0a5c643689626bec213c4d8bd4d96acc8ffdb4ad4bb6bc16abf27d5f4b553" -dependencies = [ - "asn1-rs", - "displaydoc", - "nom", - "num-bigint", - "num-traits", - "rusticata-macros", -] - -[[package]] -name = "der_derive" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "deranged" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" -dependencies = [ - "powerfmt", - "serde", -] - -[[package]] -name = "derive_more" -version = "0.99.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "derive_more" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a9b99b9cbbe49445b21764dc0625032a89b145a2642e67603e1c936f5458d05" -dependencies = [ - "derive_more-impl", -] - -[[package]] -name = "derive_more-impl" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" -dependencies = [ - "convert_case", - "proc-macro2", - "quote", - "syn 2.0.87", - "unicode-xid", -] - -[[package]] -name = "devise" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1d90b0c4c777a2cad215e3c7be59ac7c15adf45cf76317009b7d096d46f651d" -dependencies = [ - "devise_codegen", - "devise_core", -] - -[[package]] -name = "devise_codegen" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71b28680d8be17a570a2334922518be6adc3f58ecc880cbb404eaeb8624fd867" -dependencies = [ - "devise_core", - "quote", -] - -[[package]] -name = "devise_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b035a542cf7abf01f2e3c4d5a7acbaebfefe120ae4efc7bde3df98186e4b8af7" -dependencies = [ - "bitflags 2.6.0", - "proc-macro2", - "proc-macro2-diagnostics", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", - "subtle", -] - -[[package]] -name = "dirs" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.48.0", -] - -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "dlopen2" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09b4f5f101177ff01b8ec4ecc81eead416a8aa42819a2869311b3420fa114ffa" -dependencies = [ - "libc", - "once_cell", - "winapi", -] - -[[package]] -name = "documented" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc6db32f0995bc4553d2de888999075acd0dbeef75ba923503f6a724263dc6f3" -dependencies = [ - "documented-macros", - "phf", - "thiserror 1.0.65", -] - -[[package]] -name = "documented-macros" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a394bb35929b58f9a5fd418f7c6b17a4b616efcc1e53e6995ca123948f87e5fa" -dependencies = [ - "convert_case", - "itertools 0.13.0", - "optfield", - "proc-macro2", - "quote", - "strum", - "syn 2.0.87", -] - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "ecdsa" -version = "0.16.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" -dependencies = [ - "der", - "digest", - "elliptic-curve", - "rfc6979", - "signature", - "spki", -] - -[[package]] -name = "either" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" - -[[package]] -name = "elliptic-curve" -version = "0.13.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" -dependencies = [ - "base16ct", - "crypto-bigint", - "digest", - "ff", - "generic-array", - "group", - "pem-rfc7468", - "pkcs8", - "rand_core 0.6.4", - "sec1", - "subtle", - "zeroize", -] - -[[package]] -name = "encode_unicode" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" - -[[package]] -name = "encoding_rs" -version = "0.8.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b45de904aa0b010bce2ab45264d0631681847fa7b6f2eaa7dab7619943bc4f59" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "enum-as-inner" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "enum_dispatch" -version = "0.3.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" -dependencies = [ - "once_cell", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "env_logger" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580" -dependencies = [ - "humantime", - "is-terminal", - "log", - "regex", - "termcolor", -] - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "errno" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - -[[package]] -name = "faccess" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ae66425802d6a903e268ae1a08b8c38ba143520f227a205edf4e9c7e3e26d5" -dependencies = [ - "bitflags 1.3.2", - "libc", - "winapi", -] - -[[package]] -name = "fastrand" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8c02a5121d4ea3eb16a80748c74f5549a5665e4c21333c6098f283870fbdea6" - -[[package]] -name = "ff" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" -dependencies = [ - "rand_core 0.6.4", - "subtle", -] - -[[package]] -name = "fiat-crypto" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" - -[[package]] -name = "figment" -version = "0.10.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" -dependencies = [ - "atomic", - "pear", - "serde", - "serde_json", - "toml", - "uncased", - "version_check", -] - -[[package]] -name = "filetime" -version = "0.2.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35c0522e981e68cbfa8c3f978441a5f34b30b96e146b33cd3359176b50fe8586" -dependencies = [ - "cfg-if", - "libc", - "libredox", - "windows-sys 0.59.0", -] - -[[package]] -name = "fixedbitset" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" - -[[package]] -name = "flagset" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3ea1ec5f8307826a5b71094dd91fc04d4ae75d5709b20ad351c7fb4815c86ec" - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fs-err" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bb60e7409f34ef959985bc9d9c5ee8f5db24ee46ed9775850548021710f807f" -dependencies = [ - "autocfg", -] - -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - -[[package]] -name = "fsevent-sys" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" -dependencies = [ - "libc", -] - -[[package]] -name = "funty" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c" - -[[package]] -name = "futures" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" - -[[package]] -name = "futures-executor" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" - -[[package]] -name = "futures-macro" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "futures-sink" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" - -[[package]] -name = "futures-task" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" - -[[package]] -name = "futures-util" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generator" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc16584ff22b460a382b7feec54b23d2908d858152e5739a120b949293bd74e" -dependencies = [ - "cc", - "libc", - "log", - "rustversion", - "windows 0.48.0", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", - "zeroize", -] - -[[package]] -name = "getrandom" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.9.0+wasi-snapshot-preview1", -] - -[[package]] -name = "getrandom" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" -dependencies = [ - "cfg-if", - "libc", - "wasi 0.11.0+wasi-snapshot-preview1", -] - -[[package]] -name = "getrandom_or_panic" -version = "0.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea1015b5a70616b688dc230cfe50c8af89d972cb132d5a622814d29773b10b9" -dependencies = [ - "rand 0.8.5", - "rand_core 0.6.4", -] - -[[package]] -name = "ghash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" -dependencies = [ - "opaque-debug", - "polyval", -] - -[[package]] -name = "gimli" -version = "0.31.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32085ea23f3234fc7846555e85283ba4de91e21016dc0455a16286d87a292d64" - -[[package]] -name = "git-version" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad568aa3db0fcbc81f2f116137f263d7304f512a1209b35b85150d3ef88ad19" -dependencies = [ - "git-version-macro", -] - -[[package]] -name = "git-version-macro" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53010ccb100b96a67bc32c0175f0ed1426b31b655d562898e57325f81c023ac0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "glob" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" - -[[package]] -name = "group" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" -dependencies = [ - "ff", - "rand_core 0.6.4", - "subtle", -] - -[[package]] -name = "guest-api" -version = "0.3.4" -dependencies = [ - "anyhow", - "http-client", - "prost 0.13.3", - "prpc", - "prpc-build", - "serde", - "serde_json", -] - -[[package]] -name = "h2" -version = "0.3.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81fe527a889e1532da5c525686d96d4c2e74cdd345badf8dfef9f6b39dd5f5e8" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap 2.5.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "h2" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e8ac6999421f49a846c2d4411f337e53497d8ec55d67753beffa43c5d9205" -dependencies = [ - "atomic-waker", - "bytes", - "fnv", - "futures-core", - "futures-sink", - "http 1.2.0", - "indexmap 2.5.0", - "slab", - "tokio", - "tokio-util", - "tracing", -] - -[[package]] -name = "h3" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e7675a0963b47a6d12fe44c279918b4ffb19baee838ac37f48d2722ad5bc6ab" -dependencies = [ - "bytes", - "fastrand", - "futures-util", - "http 1.2.0", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "hash_hasher" -version = "2.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74721d007512d0cb3338cd20f0654ac913920061a4c4d0d8708edb3f2a698c0c" - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" -dependencies = [ - "ahash", - "allocator-api2", -] - -[[package]] -name = "heck" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hermit-abi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" - -[[package]] -name = "hermit-abi" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "hex-literal" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" - -[[package]] -name = "hex_fmt" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b07f60793ff0a4d9cef0f18e63b5357e06209987153a64648c972c1e5aff336f" - -[[package]] -name = "hickory-proto" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07698b8420e2f0d6447a436ba999ec85d8fbf2a398bbd737b82cac4a2e96e512" -dependencies = [ - "async-trait", - "cfg-if", - "data-encoding", - "enum-as-inner", - "futures-channel", - "futures-io", - "futures-util", - "idna 0.4.0", - "ipnet", - "once_cell", - "rand 0.8.5", - "thiserror 1.0.65", - "tinyvec", - "tokio", - "tracing", - "url", -] - -[[package]] -name = "hickory-resolver" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28757f23aa75c98f254cf0405e6d8c25b831b32921b050a66692427679b1f243" -dependencies = [ - "cfg-if", - "futures-util", - "hickory-proto", - "ipconfig", - "lru-cache", - "once_cell", - "parking_lot", - "rand 0.8.5", - "resolv-conf", - "smallvec", - "thiserror 1.0.65", - "tokio", - "tracing", -] - -[[package]] -name = "hkdf" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" -dependencies = [ - "hmac", -] - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest", -] - -[[package]] -name = "home" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3d1354bf6b7235cb4a0576c2619fd4ed18183f689b12b006a0ee7329eeff9a5" -dependencies = [ - "windows-sys 0.52.0", -] - -[[package]] -name = "host-api" -version = "0.3.4" -dependencies = [ - "anyhow", - "http-client", - "prost 0.13.3", - "prpc", - "prpc-build", - "serde", - "serde_json", -] - -[[package]] -name = "hostname" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c731c3e10504cc8ed35cfe2f1db4c9274c3d35fa486e3b31df46f068ef3e867" -dependencies = [ - "libc", - "match_cfg", - "winapi", -] - -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f16ca2af56261c99fba8bac40a10251ce8188205a4c448fbb745a2e4daa76fea" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - -[[package]] -name = "http-body" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" -dependencies = [ - "bytes", - "http 1.2.0", -] - -[[package]] -name = "http-body-util" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" -dependencies = [ - "bytes", - "futures-util", - "http 1.2.0", - "http-body 1.0.1", - "pin-project-lite", -] - -[[package]] -name = "http-client" -version = "0.3.4" -dependencies = [ - "anyhow", - "http-body-util", - "hyper 1.5.1", - "hyper-util", - "hyperlocal", - "log", - "pin-project-lite", - "prpc", - "serde", - "tokio", - "tokio-vsock", - "tower-service", -] - -[[package]] -name = "httparse" -version = "1.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" - -[[package]] -name = "httpdate" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" - -[[package]] -name = "humansize" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7" -dependencies = [ - "libm", -] - -[[package]] -name = "humantime" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" - -[[package]] -name = "hyper" -version = "0.14.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a152ddd61dfaec7273fe8419ab357f33aee0d914c5f4efbf0d96fa749eea5ec9" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.3.26", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", - "want", -] - -[[package]] -name = "hyper" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97818827ef4f364230e16705d4706e2897df2bb60617d6ca15d598025a3c481f" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "h2 0.4.6", - "http 1.2.0", - "http-body 1.0.1", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-named-pipe" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b7d8abf35697b81a825e386fc151e0d503e8cb5fcb93cc8669c376dfd6f278" -dependencies = [ - "hex", - "hyper 1.5.1", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", - "winapi", -] - -[[package]] -name = "hyper-rustls" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec3efd23720e2049821a693cbc7e65ea87c72f1c58ff2f9522ff332b1491e590" -dependencies = [ - "futures-util", - "http 0.2.12", - "hyper 0.14.30", - "rustls 0.21.12", - "tokio", - "tokio-rustls 0.24.1", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08afdbb5c31130e3034af566421053ab03787c640246a446327f550d11bcb333" -dependencies = [ - "futures-util", - "http 1.2.0", - "hyper 1.5.1", - "hyper-util", - "rustls 0.23.19", - "rustls-native-certs", - "rustls-pki-types", - "tokio", - "tokio-rustls 0.26.0", - "tower-service", - "webpki-roots 0.26.6", -] - -[[package]] -name = "hyper-util" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df2dcfbe0677734ab2f3ffa7fa7bfd4706bfdc1ef393f2ee30184aed67e631b4" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http 1.2.0", - "http-body 1.0.1", - "hyper 1.5.1", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "hyperlocal" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "986c5ce3b994526b3cd75578e62554abd09f0899d6206de48b3e96ab34ccc8c7" -dependencies = [ - "hex", - "http-body-util", - "hyper 1.5.1", - "hyper-util", - "pin-project-lite", - "tokio", - "tower-service", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.61" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core 0.52.0", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d20d6b07bfbc108882d88ed8e37d39636dcc260e15e30c45e6ba089610b917c" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "idna" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "impl-trait-for-tuples" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11d7a9f6330b71fea57921c9b61c47ee6e84f72d394754eff6163ae67e7395eb" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "serde", -] - -[[package]] -name = "indexmap" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5" -dependencies = [ - "equivalent", - "hashbrown 0.14.5", - "serde", -] - -[[package]] -name = "inlinable_string" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" - -[[package]] -name = "inotify" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdd168d97690d0b8c412d6b6c10360277f4d7ee495c5d0d5d5fe0854923255cc" -dependencies = [ - "bitflags 1.3.2", - "inotify-sys", - "libc", -] - -[[package]] -name = "inotify-sys" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" -dependencies = [ - "libc", -] - -[[package]] -name = "inout" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" -dependencies = [ - "generic-array", -] - -[[package]] -name = "insta" -version = "1.41.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e9ffc4d4892617c50a928c52b2961cb5174b6fc6ebf252b2fac9d21955c48b8" -dependencies = [ - "console", - "lazy_static", - "linked-hash-map", - "similar", -] - -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if", -] - -[[package]] -name = "instant-acme" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37221e690dcc5d0ea7c1f70decda6ae3495e72e8af06bca15e982193ffdf4fc4" -dependencies = [ - "async-trait", - "base64 0.22.1", - "bytes", - "http 1.2.0", - "http-body 1.0.1", - "http-body-util", - "hyper 1.5.1", - "hyper-rustls 0.27.3", - "hyper-util", - "ring", - "rustls-pki-types", - "serde", - "serde_json", - "thiserror 1.0.65", -] - -[[package]] -name = "intrusive-collections" -version = "0.9.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "189d0897e4cbe8c75efedf3502c18c887b05046e59d28404d4d8e46cbc4d1e86" -dependencies = [ - "memoffset", -] - -[[package]] -name = "iohash" -version = "0.3.4" -dependencies = [ - "anyhow", - "blake2", - "clap", - "fs-err", - "hex_fmt", - "sha2", - "sha3", -] - -[[package]] -name = "ipconfig" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b58db92f96b720de98181bbbe63c831e87005ab460c1bf306eb2622b4707997f" -dependencies = [ - "socket2", - "widestring", - "windows-sys 0.48.0", - "winreg", -] - -[[package]] -name = "ipnet" -version = "2.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddc24109865250148c2e0f3d25d4f0f479571723792d3802153c60922a4fb708" -dependencies = [ - "serde", -] - -[[package]] -name = "is-terminal" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "261f68e344040fbd0edea105bef17c66edf46f984ddb1115b775ce31be948f4b" -dependencies = [ - "hermit-abi 0.4.0", - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" - -[[package]] -name = "jobserver" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" -dependencies = [ - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "keccak" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc2af9a1119c51f12a14607e783cb977bde58bc069ff0c3da1095e635d70654" -dependencies = [ - "cpufeatures", -] - -[[package]] -name = "kms" -version = "0.3.4" -dependencies = [ - "anyhow", - "chrono", - "clap", - "fs-err", - "git-version", - "hex", - "hex_fmt", - "kms-rpc", - "load_config", - "ra-rpc", - "ra-tls", - "rocket", - "serde", - "tracing", - "tracing-subscriber", - "x25519-dalek", - "yasna", -] - -[[package]] -name = "kms-rpc" -version = "0.3.4" -dependencies = [ - "anyhow", - "fs-err", - "parity-scale-codec", - "prost 0.13.3", - "prpc", - "prpc-build", - "serde", - "serde_json", -] - -[[package]] -name = "kqueue" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7447f1ca1b7b563588a205fe93dea8df60fd981423a768bc1c0ded35ed147d0c" -dependencies = [ - "kqueue-sys", - "libc", -] - -[[package]] -name = "kqueue-sys" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b" -dependencies = [ - "bitflags 1.3.2", - "libc", -] - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "lazycell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" - -[[package]] -name = "libc" -version = "0.2.167" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09d6582e104315a817dff97f75133544b2e094ee22447d2acf4a74e189ba06fc" - -[[package]] -name = "libloading" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4979f22fdb869068da03c9f7528f8297c6fd2606bc3a4affe42e6a823fdb8da4" -dependencies = [ - "cfg-if", - "windows-targets 0.52.6", -] - -[[package]] -name = "libm" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058" - -[[package]] -name = "libredox" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" -dependencies = [ - "bitflags 2.6.0", - "libc", - "redox_syscall", -] - -[[package]] -name = "linked-hash-map" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" - -[[package]] -name = "linux-raw-sys" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" - -[[package]] -name = "load_config" -version = "0.3.4" -dependencies = [ - "figment", - "rocket", - "tempfile", - "tracing", -] - -[[package]] -name = "lock_api" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" - -[[package]] -name = "loom" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5" -dependencies = [ - "cfg-if", - "generator", - "scoped-tls", - "serde", - "serde_json", - "tracing", - "tracing-subscriber", -] - -[[package]] -name = "lru-cache" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c" -dependencies = [ - "linked-hash-map", -] - -[[package]] -name = "match_cfg" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffbee8634e0d45d258acb448e7eaab3fce7a0a467395d4d9f228e3c1f01fb2e4" - -[[package]] -name = "matchers" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" -dependencies = [ - "regex-automata 0.1.10", -] - -[[package]] -name = "memalloc" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df39d232f5c40b0891c10216992c2f250c054105cb1e56f0fc9032db6203ecc1" - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" - -[[package]] -name = "memoffset" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" -dependencies = [ - "autocfg", -] - -[[package]] -name = "merlin" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58c38e2799fc0978b65dfff8023ec7843e2330bb462f19198840b34b6582397d" -dependencies = [ - "byteorder", - "keccak", - "rand_core 0.6.4", - "zeroize", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "mime_guess" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" -dependencies = [ - "mime", - "unicase", -] - -[[package]] -name = "minimal-lexical" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" - -[[package]] -name = "miniz_oxide" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1" -dependencies = [ - "adler2", -] - -[[package]] -name = "mio" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec" -dependencies = [ - "hermit-abi 0.3.9", - "libc", - "log", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.52.0", -] - -[[package]] -name = "mirai-annotations" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9be0862c1b3f26a88803c4a49de6889c10e608b3ee9344e6ef5b45fb37ad3d1" - -[[package]] -name = "multer" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" -dependencies = [ - "bytes", - "encoding_rs", - "futures-util", - "http 1.2.0", - "httparse", - "log", - "memchr", - "mime", - "spin", - "tokio", - "tokio-util", - "version_check", -] - -[[package]] -name = "multimap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" - -[[package]] -name = "multimap" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03" -dependencies = [ - "serde", -] - -[[package]] -name = "netlink-packet-core" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72724faf704479d67b388da142b186f916188505e7e0b26719019c525882eda4" -dependencies = [ - "anyhow", - "byteorder", - "netlink-packet-utils", -] - -[[package]] -name = "netlink-packet-route" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053998cea5a306971f88580d0829e90f270f940befd7cf928da179d4187a5a66" -dependencies = [ - "anyhow", - "bitflags 1.3.2", - "byteorder", - "libc", - "netlink-packet-core", - "netlink-packet-utils", -] - -[[package]] -name = "netlink-packet-utils" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ede8a08c71ad5a95cdd0e4e52facd37190977039a4704eb82a283f713747d34" -dependencies = [ - "anyhow", - "byteorder", - "paste", - "thiserror 1.0.65", -] - -[[package]] -name = "netlink-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16c903aa70590cb93691bf97a767c8d1d6122d2cc9070433deb3bbf36ce8bd23" -dependencies = [ - "bytes", - "libc", - "log", -] - -[[package]] -name = "nix" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" -dependencies = [ - "bitflags 2.6.0", - "cfg-if", - "cfg_aliases", - "libc", - "memoffset", -] - -[[package]] -name = "nom" -version = "7.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" -dependencies = [ - "memchr", - "minimal-lexical", -] - -[[package]] -name = "notify" -version = "7.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c533b4c39709f9ba5005d8002048266593c1cfaf3c5f0739d5b8ab0c6c504009" -dependencies = [ - "bitflags 2.6.0", - "filetime", - "fsevent-sys", - "inotify", - "kqueue", - "libc", - "log", - "mio", - "notify-types", - "walkdir", - "windows-sys 0.52.0", -] - -[[package]] -name = "notify-types" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7393c226621f817964ffb3dc5704f9509e107a8b024b489cc2c1b217378785df" -dependencies = [ - "instant", -] - -[[package]] -name = "ntapi" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8a3895c6391c39d7fe7ebc444a87eb2991b2a0bc718fdabd071eec617fc68e4" -dependencies = [ - "winapi", -] - -[[package]] -name = "nu-ansi-term" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84" -dependencies = [ - "overload", - "winapi", -] - -[[package]] -name = "num-bigint" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - -[[package]] -name = "num-integer" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-rational" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", - "libm", -] - -[[package]] -name = "num_cpus" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" -dependencies = [ - "hermit-abi 0.3.9", - "libc", -] - -[[package]] -name = "num_enum" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e613fc340b2220f734a8595782c551f1250e969d87d3be1ae0579e8d4065179" -dependencies = [ - "num_enum_derive", -] - -[[package]] -name = "num_enum_derive" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1844ef2428cc3e1cb900be36181049ef3d3193c63e43026cfe202983b27a56" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "object" -version = "0.36.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "084f1a5821ac4c651660a94a7153d27ac9d8a53736203f58b31945ded098070a" -dependencies = [ - "memchr", -] - -[[package]] -name = "oid-registry" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8d8034d9489cdaf79228eb9f6a3b8d7bb32ba00d6645ebd48eef4077ceb5bd9" -dependencies = [ - "asn1-rs", -] - -[[package]] -name = "once_cell" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" - -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - -[[package]] -name = "openssl-probe" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" - -[[package]] -name = "optfield" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa59f025cde9c698fcb4fcb3533db4621795374065bee908215263488f2d2a1d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "os_pipe" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ffd2b0a5634335b135d5728d84c5e0fd726954b87111f7506a61c502280d982" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - -[[package]] -name = "overload" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" - -[[package]] -name = "p256" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" -dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", - "sha2", -] - -[[package]] -name = "parcelona" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faa7b44ed28561e1d3964bfcb8771c97c6bf85962e87493ebef22218ede304a8" -dependencies = [ - "bstr", - "byteorder", - "parcelona_macros_derive", -] - -[[package]] -name = "parcelona_macros_derive" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ec0a2252bc3809594c903cc8c1b83cbccaba85b11d4728a43a681263f6c132" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "parity-scale-codec" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8be4817d39f3272f69c59fe05d0535ae6456c2dc2fa1ba02910296c7e0a5c590" -dependencies = [ - "arrayvec", - "bitvec", - "byte-slice-cast", - "impl-trait-for-tuples", - "parity-scale-codec-derive", - "rustversion", - "serde", -] - -[[package]] -name = "parity-scale-codec-derive" -version = "3.6.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d830939c76d294956402033aee57a6da7b438f2294eb94864c37b0569053a42c" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "parking_lot" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" -dependencies = [ - "cfg-if", - "libc", - "redox_syscall", - "smallvec", - "windows-targets 0.52.6", -] - -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - -[[package]] -name = "path-absolutize" -version = "3.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4af381fe79fa195b4909485d99f73a80792331df0625188e707854f0b3383f5" -dependencies = [ - "path-dedot", -] - -[[package]] -name = "path-dedot" -version = "3.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07ba0ad7e047712414213ff67533e6dd477af0a4e1d14fb52343e53d30ea9397" -dependencies = [ - "once_cell", -] - -[[package]] -name = "pear" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" -dependencies = [ - "inlinable_string", - "pear_codegen", - "yansi", -] - -[[package]] -name = "pear_codegen" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" -dependencies = [ - "proc-macro2", - "proc-macro2-diagnostics", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "pem" -version = "3.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e459365e590736a54c3fa561947c84837534b8e9af6fc5bf781307e82658fae" -dependencies = [ - "base64 0.22.1", - "serde", -] - -[[package]] -name = "pem-rfc7468" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" -dependencies = [ - "base64ct", -] - -[[package]] -name = "percent-encoding" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" - -[[package]] -name = "petgraph" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" -dependencies = [ - "fixedbitset", - "indexmap 2.5.0", -] - -[[package]] -name = "phf" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" -dependencies = [ - "phf_macros", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3444646e286606587e49f3bcf1679b8cef1dc2c5ecc29ddacaffc305180d464b" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "phf_shared" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" -dependencies = [ - "siphasher 0.3.11", -] - -[[package]] -name = "pin-project" -version = "1.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be57f64e946e500c8ee36ef6331845d40a93055567ec57e8fae13efd33759b95" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c0f5fad0874fc7abcd4d750e76917eaebbecaa2c20bde22e1dbeeba8beb758c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "915a1e146535de9163f3987b8944ed8cf49a18bb0056bcebcdcece385cece4ff" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "pkcs8" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" -dependencies = [ - "der", - "spki", -] - -[[package]] -name = "polyval" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" -dependencies = [ - "cfg-if", - "cpufeatures", - "opaque-debug", - "universal-hash", -] - -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - -[[package]] -name = "ppv-lite86" -version = "0.2.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77957b295656769bb8ad2b6a6b09d897d94f05c41b069aede1fcdaa675eaea04" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "prettyplease" -version = "0.2.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479cf940fbbb3426c32c5d5176f62ad57549a0bb84773423ba8be9d089f5faba" -dependencies = [ - "proc-macro2", - "syn 2.0.87", -] - -[[package]] -name = "primeorder" -version = "0.13.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" -dependencies = [ - "elliptic-curve", -] - -[[package]] -name = "proc-macro-crate" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecf48c7ca261d60b74ab1a7b20da18bede46776b2e55535cb958eb595c5fa7b" -dependencies = [ - "toml_edit", -] - -[[package]] -name = "proc-macro-error" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" -dependencies = [ - "proc-macro-error-attr", - "proc-macro2", - "quote", - "syn 1.0.109", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" -dependencies = [ - "proc-macro2", - "quote", - "version_check", -] - -[[package]] -name = "proc-macro-error-attr2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "proc-macro-error2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" -dependencies = [ - "proc-macro-error-attr2", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "proc-macro2" -version = "1.0.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "proc-macro2-diagnostics" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", - "version_check", - "yansi", -] - -[[package]] -name = "prost" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "444879275cb4fd84958b1a1d5420d15e6fcf7c235fe47f053c9c2a80aceb6001" -dependencies = [ - "bytes", - "prost-derive 0.9.0", -] - -[[package]] -name = "prost" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b0487d90e047de87f984913713b85c601c05609aad5b0df4b4573fbf69aa13f" -dependencies = [ - "bytes", - "prost-derive 0.13.3", -] - -[[package]] -name = "prost-build" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62941722fb675d463659e49c4f3fe1fe792ff24fe5bbaa9c08cd3b98a1c354f5" -dependencies = [ - "bytes", - "heck 0.3.3", - "itertools 0.10.5", - "lazy_static", - "log", - "multimap 0.8.3", - "petgraph", - "prost 0.9.0", - "prost-types 0.9.0", - "regex", - "tempfile", - "which 4.4.2", -] - -[[package]] -name = "prost-build" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1318b19085f08681016926435853bbf7858f9c082d0999b80550ff5d9abe15" -dependencies = [ - "bytes", - "heck 0.5.0", - "itertools 0.13.0", - "log", - "multimap 0.10.0", - "once_cell", - "petgraph", - "prettyplease", - "prost 0.13.3", - "prost-types 0.13.3", - "regex", - "syn 2.0.87", - "tempfile", -] - -[[package]] -name = "prost-derive" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9cc1a3263e07e0bf68e96268f37665207b49560d98739662cdfaae215c720fe" -dependencies = [ - "anyhow", - "itertools 0.10.5", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "prost-derive" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9552f850d5f0964a4e4d0bf306459ac29323ddfbae05e35a7c0d35cb0803cc5" -dependencies = [ - "anyhow", - "itertools 0.13.0", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "prost-types" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534b7a0e836e3c482d2693070f982e39e7611da9695d4d1f5a4b186b51faef0a" -dependencies = [ - "bytes", - "prost 0.9.0", -] - -[[package]] -name = "prost-types" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4759aa0d3a6232fb8dbdb97b61de2c20047c68aca932c7ed76da9d788508d670" -dependencies = [ - "prost 0.13.3", -] - -[[package]] -name = "prpc" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e36dbacc22fa64d2059cc8df1e929ab9100804ae2011548b6679f923c1172f42" -dependencies = [ - "anyhow", - "async-trait", - "derive_more 1.0.0", - "hex", - "hex_fmt", - "parity-scale-codec", - "prost 0.13.3", - "prpc-serde-bytes", - "serde", - "serde_json", - "serde_qs", -] - -[[package]] -name = "prpc-build" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5034baf630735948c9df3cd637f77c2897413934ba1f201068d168080ab4e510" -dependencies = [ - "either", - "fs-err", - "heck 0.5.0", - "itertools 0.13.0", - "log", - "multimap 0.10.0", - "proc-macro2", - "prost 0.13.3", - "prost-build 0.13.3", - "prost-build 0.9.0", - "prost-types 0.13.3", - "quote", - "syn 2.0.87", - "template-quote", -] - -[[package]] -name = "prpc-serde-bytes" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fac0855066edbf6bdcb42beb02cd9063d12d8d6d44b9a0c2f15a30e6ddd11f5" -dependencies = [ - "proc-macro2", - "syn 2.0.87", -] - -[[package]] -name = "quick-error" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" - -[[package]] -name = "quinn" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c7c5fdde3cdae7203427dc4f0a68fe0ed09833edc525a03456b153b79828684" -dependencies = [ - "bytes", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash 2.0.0", - "rustls 0.23.19", - "socket2", - "thiserror 1.0.65", - "tokio", - "tracing", -] - -[[package]] -name = "quinn-proto" -version = "0.11.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fadfaed2cd7f389d0161bb73eeb07b7b78f8691047a6f3e73caaeae55310a4a6" -dependencies = [ - "bytes", - "rand 0.8.5", - "ring", - "rustc-hash 2.0.0", - "rustls 0.23.19", - "slab", - "thiserror 1.0.65", - "tinyvec", - "tracing", -] - -[[package]] -name = "quinn-udp" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e346e016eacfff12233c243718197ca12f148c84e1e84268a896699b41c71780" -dependencies = [ - "cfg_aliases", - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.59.0", -] - -[[package]] -name = "quote" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "ra-rpc" -version = "0.3.4" -dependencies = [ - "anyhow", - "bon", - "prpc", - "ra-tls", - "reqwest 0.12.9", - "rocket", - "rocket-vsock-listener", - "serde", - "serde_json", - "tracing", -] - -[[package]] -name = "ra-tls" -version = "0.3.4" -dependencies = [ - "anyhow", - "bon", - "cc-eventlog", - "dcap-qvl", - "elliptic-curve", - "fs-err", - "hex", - "hkdf", - "p256", - "rcgen", - "ring", - "rustls-pki-types", - "serde", - "serde_json", - "sha2", - "sha3", - "tracing", - "x509-parser", - "yasna", -] - -[[package]] -name = "radium" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" - -[[package]] -name = "rand" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" -dependencies = [ - "getrandom 0.1.16", - "libc", - "rand_chacha 0.2.2", - "rand_core 0.5.1", - "rand_hc", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" -dependencies = [ - "ppv-lite86", - "rand_core 0.5.1", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" -dependencies = [ - "getrandom 0.1.16", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.15", -] - -[[package]] -name = "rand_hc" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" -dependencies = [ - "rand_core 0.5.1", -] - -[[package]] -name = "rayon" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b418a60154510ca1a002a752ca9714984e21e4241e804d32555251faf8b78ffa" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1465873a3dfdaa8ae7cb14b4383657caab0b3e8a0aa9ae8e04b044854c8dfce2" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "rcgen" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54077e1872c46788540de1ea3d7f4ccb1983d12f9aa909b234468676c1a36779" -dependencies = [ - "pem", - "ring", - "rustls-pki-types", - "time", - "x509-parser", - "yasna", -] - -[[package]] -name = "redox_syscall" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0884ad60e090bf1345b93da0a5de8923c93884cd03f40dfcfddd3b4bee661853" -dependencies = [ - "bitflags 2.6.0", -] - -[[package]] -name = "redox_users" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" -dependencies = [ - "getrandom 0.2.15", - "libredox", - "thiserror 1.0.65", -] - -[[package]] -name = "ref-cast" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf0a6f84d5f1d581da8b41b47ec8600871962f2a528115b542b362d4b744931" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcc303e793d3734489387d205e9b186fac9c6cfacedd98cbb2e8a5943595f3e6" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "ref-swap" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09c30c54dffee5b40af088d5d50aa3455c91a0127164b51f0215efc4cb28fb3c" - -[[package]] -name = "regex" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata 0.4.8", - "regex-syntax 0.8.5", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" -dependencies = [ - "regex-syntax 0.6.29", -] - -[[package]] -name = "regex-automata" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax 0.8.5", -] - -[[package]] -name = "regex-syntax" -version = "0.6.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" - -[[package]] -name = "regex-syntax" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" - -[[package]] -name = "reqwest" -version = "0.11.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" -dependencies = [ - "base64 0.21.7", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "h2 0.3.26", - "hickory-resolver", - "http 0.2.12", - "http-body 0.4.6", - "hyper 0.14.30", - "hyper-rustls 0.24.2", - "ipnet", - "js-sys", - "log", - "mime", - "once_cell", - "percent-encoding", - "pin-project-lite", - "rustls 0.21.12", - "rustls-pemfile 1.0.4", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper 0.1.2", - "system-configuration", - "tokio", - "tokio-rustls 0.24.1", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "webpki-roots 0.25.4", - "winreg", -] - -[[package]] -name = "reqwest" -version = "0.12.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f" -dependencies = [ - "base64 0.22.1", - "bytes", - "encoding_rs", - "futures-core", - "futures-util", - "hickory-resolver", - "http 1.2.0", - "http-body 1.0.1", - "http-body-util", - "hyper 1.5.1", - "hyper-rustls 0.27.3", - "hyper-util", - "ipnet", - "js-sys", - "log", - "mime", - "once_cell", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls 0.23.19", - "rustls-pemfile 2.1.3", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper 1.0.1", - "tokio", - "tokio-rustls 0.26.0", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "webpki-roots 0.26.6", - "windows-registry", -] - -[[package]] -name = "resolv-conf" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52e44394d2086d010551b14b53b1f24e31647570cd1deb0379e2c21b329aba00" -dependencies = [ - "hostname", - "quick-error", -] - -[[package]] -name = "rfc6979" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" -dependencies = [ - "hmac", - "subtle", -] - -[[package]] -name = "ring" -version = "0.17.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.15", - "libc", - "spin", - "untrusted 0.9.0", - "windows-sys 0.52.0", -] - -[[package]] -name = "rinja" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dc4940d00595430b3d7d5a01f6222b5e5b51395d1120bdb28d854bb8abb17a5" -dependencies = [ - "humansize", - "itoa", - "percent-encoding", - "rinja_derive", -] - -[[package]] -name = "rinja_derive" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d9ed0146aef6e2825f1b1515f074510549efba38d71f4554eec32eb36ba18b" -dependencies = [ - "basic-toml", - "memchr", - "mime", - "mime_guess", - "proc-macro2", - "quote", - "rinja_parser", - "rustc-hash 2.0.0", - "serde", - "syn 2.0.87", -] - -[[package]] -name = "rinja_parser" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93f9a866e2e00a7a1fb27e46e9e324a6f7c0e7edc4543cae1d38f4e4a100c610" -dependencies = [ - "memchr", - "nom", - "serde", -] - -[[package]] -name = "rocket" -version = "0.6.0-dev" -source = "git+https://github.com/rwf2/Rocket?branch=master#ebfcbd2c759dc232e210b59c3a4a56f66f22f4a3" -dependencies = [ - "async-stream", - "async-trait", - "binascii", - "bytes", - "cookie", - "either", - "figment", - "futures", - "http 1.2.0", - "hyper 1.5.1", - "hyper-util", - "indexmap 2.5.0", - "libc", - "memchr", - "multer", - "num_cpus", - "parking_lot", - "pin-project-lite", - "rand 0.8.5", - "ref-cast", - "ref-swap", - "rocket_codegen", - "rocket_http", - "rustls 0.23.19", - "rustls-pemfile 2.1.3", - "s2n-quic-h3", - "serde", - "serde_json", - "state", - "tempfile", - "thread_local", - "time", - "tinyvec", - "tokio", - "tokio-rustls 0.26.0", - "tokio-stream", - "tokio-util", - "tracing", - "tracing-subscriber", - "ubyte", - "version_check", - "x509-parser", - "yansi", -] - -[[package]] -name = "rocket-apitoken" -version = "0.1.0" -source = "git+https://github.com/kvinwang/rocket-apitoken?branch=dev#7b5c1e864217b928e08913886c1a3ddd849e254c" -dependencies = [ - "rocket", -] - -[[package]] -name = "rocket-vsock-listener" -version = "0.3.4" -dependencies = [ - "anyhow", - "derive_more 1.0.0", - "pin-project", - "rocket", - "serde", - "thiserror 2.0.4", - "tokio", - "tokio-vsock", -] - -[[package]] -name = "rocket_codegen" -version = "0.6.0-dev" -source = "git+https://github.com/rwf2/Rocket?branch=master#ebfcbd2c759dc232e210b59c3a4a56f66f22f4a3" -dependencies = [ - "devise", - "glob", - "indexmap 2.5.0", - "proc-macro2", - "quote", - "rocket_http", - "syn 2.0.87", - "unicode-xid", - "version_check", -] - -[[package]] -name = "rocket_http" -version = "0.6.0-dev" -source = "git+https://github.com/rwf2/Rocket?branch=master#ebfcbd2c759dc232e210b59c3a4a56f66f22f4a3" -dependencies = [ - "cookie", - "either", - "indexmap 2.5.0", - "memchr", - "pear", - "percent-encoding", - "ref-cast", - "serde", - "stable-pattern", - "state", - "time", - "tinyvec", - "uncased", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-hash" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "583034fd73374156e66797ed8e5b0d5690409c9226b22d87cb7f19821c05d152" - -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - -[[package]] -name = "rusticata-macros" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" -dependencies = [ - "nom", -] - -[[package]] -name = "rustix" -version = "0.38.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85" -dependencies = [ - "bitflags 2.6.0", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.59.0", -] - -[[package]] -name = "rustls" -version = "0.21.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" -dependencies = [ - "log", - "ring", - "rustls-webpki 0.101.7", - "sct", -] - -[[package]] -name = "rustls" -version = "0.23.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "934b404430bb06b3fae2cba809eb45a1ab1aecd64491213d7c3301b88393f8d1" -dependencies = [ - "aws-lc-rs", - "log", - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki 0.102.8", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcaf18a4f2be7326cd874a5fa579fae794320a0f388d365dca7e480e55f83f8a" -dependencies = [ - "openssl-probe", - "rustls-pemfile 2.1.3", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pemfile" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" -dependencies = [ - "base64 0.21.7", -] - -[[package]] -name = "rustls-pemfile" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "196fe16b00e106300d3e45ecfcb764fa292a535d7326a29a5875c579c7417425" -dependencies = [ - "base64 0.22.1", - "rustls-pki-types", -] - -[[package]] -name = "rustls-pki-types" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16f1201b3c9a7ee8039bcadc17b7e605e2945b27eee7631788c1bd2b0643674b" - -[[package]] -name = "rustls-webpki" -version = "0.101.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" -dependencies = [ - "ring", - "untrusted 0.9.0", -] - -[[package]] -name = "rustls-webpki" -version = "0.102.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9" -dependencies = [ - "aws-lc-rs", - "ring", - "rustls-pki-types", - "untrusted 0.9.0", -] - -[[package]] -name = "rustversion" -version = "1.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955d28af4278de8121b7ebeb796b6a45735dc01436d898801014aced2773a3d6" - -[[package]] -name = "ryu" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" - -[[package]] -name = "s2n-codec" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d13164318e22dae500fc06642d3c7064692b797be32fa2b2b207b500622a41e" -dependencies = [ - "byteorder", - "zerocopy", -] - -[[package]] -name = "s2n-codec" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "850377b1f41a7ab9f503fc24676f83348a123e0d38cb46b6b05148bb37fdd641" -dependencies = [ - "byteorder", - "bytes", - "zerocopy", -] - -[[package]] -name = "s2n-quic" -version = "1.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9001e28ac66b347fd7da74d32d1b47f2e8f21dbe5d6168764e19d1f7c94abf5b" -dependencies = [ - "bytes", - "cfg-if", - "cuckoofilter", - "futures", - "hash_hasher", - "rand 0.8.5", - "rand_chacha 0.3.1", - "s2n-codec 0.46.0", - "s2n-quic-core 0.46.0", - "s2n-quic-crypto", - "s2n-quic-platform", - "s2n-quic-rustls", - "s2n-quic-transport", - "tokio", - "zerocopy", - "zeroize", -] - -[[package]] -name = "s2n-quic-core" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d5f5c09558c2eece5eeffa27f1a7c9e8f03942081ba713415f3ffb4d5d7404b" -dependencies = [ - "byteorder", - "cfg-if", - "hex-literal", - "num-rational", - "num-traits", - "pin-project-lite", - "s2n-codec 0.45.0", - "subtle", - "zerocopy", -] - -[[package]] -name = "s2n-quic-core" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3812c691786fce11b953923a018a8aa06dea3723bb2a2393fb3ed257e9c34284" -dependencies = [ - "atomic-waker", - "byteorder", - "bytes", - "cfg-if", - "crossbeam-utils", - "hex-literal", - "num-rational", - "num-traits", - "once_cell", - "pin-project-lite", - "s2n-codec 0.46.0", - "subtle", - "tracing", - "zerocopy", -] - -[[package]] -name = "s2n-quic-crypto" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79a44934ca63a71fc0a8c4358ece9700340bb951c52f5fdc98f96eb09e9eecdd" -dependencies = [ - "aws-lc-rs", - "cfg-if", - "lazy_static", - "ring", - "s2n-codec 0.46.0", - "s2n-quic-core 0.46.0", - "zeroize", -] - -[[package]] -name = "s2n-quic-h3" -version = "0.1.0" -source = "git+https://github.com/SergioBenitez/s2n-quic-h3.git?rev=6613956#66139567216fd59c44c58ca792711f755fdfaa2b" -dependencies = [ - "bytes", - "futures", - "h3", - "s2n-quic", - "s2n-quic-core 0.45.0", - "tracing", -] - -[[package]] -name = "s2n-quic-platform" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d144224056280cffc36729d852a16fea0a7e753c3b6f17da463bbb732468f4d0" -dependencies = [ - "cfg-if", - "futures", - "lazy_static", - "libc", - "s2n-quic-core 0.46.0", - "socket2", - "tokio", -] - -[[package]] -name = "s2n-quic-rustls" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c973d29e9b6669473f205b47d015480d7e79b103dfbd1c789184d9adc31af05" -dependencies = [ - "bytes", - "rustls 0.23.19", - "rustls-pemfile 2.1.3", - "s2n-codec 0.46.0", - "s2n-quic-core 0.46.0", - "s2n-quic-crypto", -] - -[[package]] -name = "s2n-quic-transport" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f55bcf34cd3fce8b1852d2d7c4e0f5a0f98d081afeaddd37ef839b8898be8d" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "hashbrown 0.14.5", - "intrusive-collections", - "once_cell", - "s2n-codec 0.46.0", - "s2n-quic-core 0.46.0", - "siphasher 1.0.1", - "smallvec", -] - -[[package]] -name = "safe-write" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2a91448d36438f815f130716530ccdb3ea6ffec2e0c02f8d035ab66dd87209a" -dependencies = [ - "fs-err", -] - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scale-info" -version = "2.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca070c12893629e2cc820a9761bedf6ce1dcddc9852984d1dc734b8bd9bd024" -dependencies = [ - "bitvec", - "cfg-if", - "derive_more 0.99.18", - "parity-scale-codec", - "scale-info-derive", -] - -[[package]] -name = "scale-info-derive" -version = "2.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d35494501194174bda522a32605929eefc9ecf7e0a326c26db1fdd85881eb62" -dependencies = [ - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "schannel" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9aaafd5a2b6e3d657ff009d82fbd630b6bd54dd4eb06f21693925cdf80f9b8b" -dependencies = [ - "windows-sys 0.59.0", -] - -[[package]] -name = "schnorrkel" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de18f6d8ba0aad7045f5feae07ec29899c1112584a38509a84ad7b04451eaa0" -dependencies = [ - "aead", - "arrayref", - "arrayvec", - "curve25519-dalek", - "getrandom_or_panic", - "merlin", - "rand_core 0.6.4", - "serde_bytes", - "sha2", - "subtle", - "zeroize", -] - -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "sct" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" -dependencies = [ - "ring", - "untrusted 0.9.0", -] - -[[package]] -name = "sd-notify" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1be20c5f7f393ee700f8b2f28ea35812e4e212f40774b550cd2a93ea91684451" - -[[package]] -name = "sec1" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" -dependencies = [ - "base16ct", - "der", - "generic-array", - "pkcs8", - "subtle", - "zeroize", -] - -[[package]] -name = "security-framework" -version = "2.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" -dependencies = [ - "bitflags 2.6.0", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea4a292869320c0272d7bc55a5a6aafaff59b4f63404a003887b679a2e05b4b6" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "semver" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61697e0a1c7e512e84a621326239844a24d8207b4669b41bc18b32ea5cbf988b" - -[[package]] -name = "serde" -version = "1.0.215" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6513c1ad0b11a9376da888e3e0baa0077f1aed55c17f50e7b2397136129fb88f" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde-human-bytes" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ef65cb41f3f9cef63c431193229067e8b98b53c4d4c4ed38a8ca87c4d07676" -dependencies = [ - "hex", - "serde", -] - -[[package]] -name = "serde_bytes" -version = "0.11.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "387cc504cb06bb40a96c8e04e951fe01854cf6bc921053c954e4a606d9675c6a" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_derive" -version = "1.0.215" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad1e866f866923f252f05c889987993144fb74e722403468a4ebd70c3cd756c0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "serde_json" -version = "1.0.133" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7fceb2473b9166b2294ef05efcb65a3db80803f0b03ef86a5fc88a2b85ee377" -dependencies = [ - "indexmap 2.5.0", - "itoa", - "memchr", - "ryu", - "serde", -] - -[[package]] -name = "serde_qs" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd34f36fe4c5ba9654417139a9b3a20d2e1de6012ee678ad14d240c22c78d8d6" -dependencies = [ - "percent-encoding", - "serde", - "thiserror 1.0.65", -] - -[[package]] -name = "serde_repr" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c64451ba24fc7a6a2d60fc75dd9c83c90903b19028d4eff35e88fc1e86564e9" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "serde_spanned" -version = "0.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb5b1b31579f3811bf615c144393417496f152e12ac8b7663bf664f4a815306d" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_with" -version = "3.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cecfa94848272156ea67b2b1a53f20fc7bc638c4a46d2f8abde08f05f4b857" -dependencies = [ - "base64 0.22.1", - "chrono", - "hex", - "indexmap 1.9.3", - "indexmap 2.5.0", - "serde", - "serde_derive", - "serde_json", - "time", -] - -[[package]] -name = "sha2" -version = "0.10.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793db75ad2bcafc3ffa7c68b215fee268f537982cd901d132f89c6343f3a3dc8" -dependencies = [ - "cfg-if", - "cpufeatures", - "digest", -] - -[[package]] -name = "sha3" -version = "0.10.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" -dependencies = [ - "digest", - "keccak", -] - -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "shared_child" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09fa9338aed9a1df411814a5b2252f7cd206c55ae9bf2fa763f8de84603aa60c" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signal-hook-registry" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" -dependencies = [ - "libc", -] - -[[package]] -name = "signature" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "digest", - "rand_core 0.6.4", -] - -[[package]] -name = "similar" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e" - -[[package]] -name = "siphasher" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" - -[[package]] -name = "siphasher" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" - -[[package]] -name = "slab" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] - -[[package]] -name = "smallvec" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" - -[[package]] -name = "socket2" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "spin" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" - -[[package]] -name = "spki" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" -dependencies = [ - "base64ct", - "der", -] - -[[package]] -name = "stable-pattern" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4564168c00635f88eaed410d5efa8131afa8d8699a612c80c455a0ba05c21045" -dependencies = [ - "memchr", -] - -[[package]] -name = "state" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b8c4a4445d81357df8b1a650d0d0d6fbbbfe99d064aa5e02f3e4022061476d8" -dependencies = [ - "loom", -] - -[[package]] -name = "strip-ansi-escapes" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55ff8ef943b384c414f54aefa961dd2bd853add74ec75e7ac74cf91dba62bcfa" -dependencies = [ - "vte", -] - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "strum" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" -dependencies = [ - "strum_macros", -] - -[[package]] -name = "strum_macros" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.87", -] - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "supervisor" -version = "0.3.4" -dependencies = [ - "anyhow", - "bon", - "clap", - "dashmap", - "fs-err", - "git-version", - "libc", - "load_config", - "notify", - "rocket", - "serde", - "serde_json", - "tokio", - "tracing", - "tracing-subscriber", -] - -[[package]] -name = "supervisor-client" -version = "0.3.4" -dependencies = [ - "anyhow", - "clap", - "fs-err", - "futures", - "http 1.2.0", - "http-body-util", - "http-client", - "hyper 1.5.1", - "hyper-util", - "hyperlocal", - "log", - "serde", - "serde_json", - "supervisor", - "tokio", - "tracing-subscriber", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" - -[[package]] -name = "sync_wrapper" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "sysinfo" -version = "0.33.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "948512566b1895f93b1592c7574baeb2de842f224f2aab158799ecadb8ebbb46" -dependencies = [ - "core-foundation-sys", - "libc", - "memchr", - "ntapi", - "rayon", - "windows 0.57.0", -] - -[[package]] -name = "system-configuration" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" -dependencies = [ - "bitflags 1.3.2", - "core-foundation", - "system-configuration-sys", -] - -[[package]] -name = "system-configuration-sys" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "tailf" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d8fddaad13d98a99b3579b0a3684708e5cb448a98a850755b4becb1c034e274" -dependencies = [ - "bon", - "tokio", -] - -[[package]] -name = "tap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" - -[[package]] -name = "tappd" -version = "0.3.4" -dependencies = [ - "anyhow", - "base64 0.22.1", - "bollard", - "chrono", - "clap", - "cmd_lib", - "default-net", - "figment", - "fs-err", - "git-version", - "guest-api", - "hex", - "host-api", - "load_config", - "ra-rpc", - "ra-tls", - "rcgen", - "reqwest 0.12.9", - "rinja", - "rocket", - "rocket-vsock-listener", - "sd-notify", - "serde", - "serde_json", - "sha2", - "sysinfo", - "tappd-rpc", - "tdx-attest", - "tokio", - "tracing", - "tracing-subscriber", -] - -[[package]] -name = "tappd-rpc" -version = "0.3.4" -dependencies = [ - "anyhow", - "parity-scale-codec", - "prost 0.13.3", - "prpc", - "prpc-build", - "serde", - "serde_json", -] - -[[package]] -name = "tdx-attest" -version = "0.3.4" -dependencies = [ - "anyhow", - "cc-eventlog", - "fs-err", - "hex", - "insta", - "num_enum", - "parity-scale-codec", - "serde", - "serde-human-bytes", - "serde_json", - "sha2", - "tdx-attest-sys", - "thiserror 2.0.4", -] - -[[package]] -name = "tdx-attest-sys" -version = "0.3.4" -dependencies = [ - "bindgen 0.70.1", - "cc", -] - -[[package]] -name = "tdxctl" -version = "0.3.4" -dependencies = [ - "aes-gcm", - "anyhow", - "clap", - "cmd_lib", - "curve25519-dalek", - "fs-err", - "getrandom 0.2.15", - "hex", - "hex_fmt", - "host-api", - "kms-rpc", - "parity-scale-codec", - "ra-rpc", - "ra-tls", - "rand 0.8.5", - "regex", - "schnorrkel", - "serde", - "serde-human-bytes", - "serde_json", - "sha2", - "tdx-attest", - "tokio", - "toml", - "tproxy-rpc", - "tracing", - "tracing-subscriber", - "x25519-dalek", -] - -[[package]] -name = "teepod" -version = "0.3.4" -dependencies = [ - "anyhow", - "bon", - "clap", - "dirs", - "fs-err", - "git-version", - "guest-api", - "hex", - "host-api", - "humantime", - "kms-rpc", - "load_config", - "path-absolutize", - "ra-rpc", - "rocket", - "rocket-apitoken", - "rocket-vsock-listener", - "safe-write", - "serde", - "serde_json", - "sha2", - "shared_child", - "strip-ansi-escapes", - "supervisor-client", - "tailf", - "teepod-rpc", - "tokio", - "tracing", - "tracing-subscriber", - "uuid", - "which 7.0.0", -] - -[[package]] -name = "teepod-rpc" -version = "0.3.4" -dependencies = [ - "anyhow", - "parity-scale-codec", - "prost 0.13.3", - "prpc", - "prpc-build", - "serde", - "serde_json", -] - -[[package]] -name = "tempfile" -version = "3.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28cce251fcbc87fac86a866eeb0d6c2d536fc16d06f184bb61aeae11aa4cee0c" -dependencies = [ - "cfg-if", - "fastrand", - "once_cell", - "rustix", - "windows-sys 0.59.0", -] - -[[package]] -name = "template-quote" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc002ce9580af57b063e49f50f3f0da0682a42897a1f42b2f523893163319e5f" -dependencies = [ - "quote", - "template-quote-impl", -] - -[[package]] -name = "template-quote-impl" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "771674c8b6053d12596dbc4edb19babd846eba27cd47e0e432f7dc2beac23b16" -dependencies = [ - "proc-macro-error", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "thiserror" -version = "1.0.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d11abd9594d9b38965ef50805c5e469ca9cc6f197f883f717e0269a3057b3d5" -dependencies = [ - "thiserror-impl 1.0.65", -] - -[[package]] -name = "thiserror" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f49a1853cf82743e3b7950f77e0f4d622ca36cf4317cba00c767838bac8d490" -dependencies = [ - "thiserror-impl 2.0.4", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae71770322cbd277e69d762a16c444af02aa0575ac0d174f0b9562d3b37f8602" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8381894bb3efe0c4acac3ded651301ceee58a15d47c2e34885ed1908ad667061" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "thread_local" -version = "1.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" -dependencies = [ - "cfg-if", - "once_cell", -] - -[[package]] -name = "time" -version = "0.3.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35e7868883861bd0e56d9ac6efcaaca0d6d5d82a2a7ec8209ff492c07cf37b21" -dependencies = [ - "deranged", - "itoa", - "num-conv", - "powerfmt", - "serde", - "time-core", - "time-macros", -] - -[[package]] -name = "time-core" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" - -[[package]] -name = "time-macros" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2834e6017e3e5e4b9834939793b282bc03b37a3336245fa820e35e233e2a85de" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "tinyvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "445e881f4f6d382d5f27c034e25eb92edd7c784ceab92a0937db7f2e9471b938" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cec9b21b0450273377fc97bd4c33a8acffc8c996c987a7c5b319a0083707551" -dependencies = [ - "backtrace", - "bytes", - "libc", - "mio", - "parking_lot", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.52.0", -] - -[[package]] -name = "tokio-macros" -version = "2.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "693d596312e88961bc67d7f1f97af8a70227d9f90c31bba5806eec004978d752" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "tokio-rustls" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" -dependencies = [ - "rustls 0.21.12", - "tokio", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" -dependencies = [ - "rustls 0.23.19", - "rustls-pki-types", - "tokio", -] - -[[package]] -name = "tokio-stream" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f4e6ce100d0eb49a2734f8c0812bcd324cf357d21810932c5df6b96ef2b86f1" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61e7c3654c13bcd040d4a03abee2c75b1d14a37b423cf5a813ceae1cc903ec6a" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-vsock" -version = "0.6.0" -source = "git+https://github.com/kvinwang/tokio-vsock?branch=shared-self-accept#dd9778742ceb98ee39d68ad527b8d80f3178c172" -dependencies = [ - "bytes", - "futures", - "libc", - "tokio", - "vsock", -] - -[[package]] -name = "toml" -version = "0.8.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.22.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5" -dependencies = [ - "indexmap 2.5.0", - "serde", - "serde_spanned", - "toml_datetime", - "winnow", -] - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tproxy" -version = "0.3.4" -dependencies = [ - "anyhow", - "bytes", - "certbot", - "clap", - "cmd_lib", - "fs-err", - "futures", - "git-version", - "hex", - "hickory-resolver", - "insta", - "ipnet", - "load_config", - "nix", - "parcelona", - "pin-project", - "ra-rpc", - "rand 0.8.5", - "rinja", - "rocket", - "rustls 0.23.19", - "safe-write", - "serde", - "serde_json", - "shared_child", - "smallvec", - "tokio", - "tokio-rustls 0.26.0", - "tproxy-rpc", - "tracing", - "tracing-subscriber", -] - -[[package]] -name = "tproxy-rpc" -version = "0.3.4" -dependencies = [ - "anyhow", - "parity-scale-codec", - "prost 0.13.3", - "prpc", - "prpc-build", - "serde", - "serde_json", -] - -[[package]] -name = "tracing" -version = "0.1.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" -dependencies = [ - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "tracing-core" -version = "0.1.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" -dependencies = [ - "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "parking_lot", - "regex", - "sharded-slab", - "smallvec", - "thread_local", - "tracing", - "tracing-core", - "tracing-log", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "typenum" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" - -[[package]] -name = "ubyte" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f720def6ce1ee2fc44d40ac9ed6d3a59c361c80a75a7aa8e75bb9baed31cf2ea" -dependencies = [ - "serde", -] - -[[package]] -name = "uncased" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" -dependencies = [ - "serde", - "version_check", -] - -[[package]] -name = "unicase" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" -dependencies = [ - "version_check", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75" - -[[package]] -name = "unicode-ident" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" - -[[package]] -name = "unicode-normalization" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-segmentation" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4c87d22b6e3f4a18d4d40ef354e97c90fcb14dd91d7dc0aa9d8a1172ebf7202" - -[[package]] -name = "unicode-xid" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "229730647fbc343e3a80e463c1db7f78f3855d3f3739bee0dda773c9a037c90a" - -[[package]] -name = "universal-hash" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" -dependencies = [ - "crypto-common", - "subtle", -] - -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" -dependencies = [ - "form_urlencoded", - "idna 0.5.0", - "percent-encoding", -] - -[[package]] -name = "urlencoding" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "uuid" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8c5f0a0af699448548ad1a2fbf920fb4bee257eae39953ba95cb84891a0446a" -dependencies = [ - "getrandom 0.2.15", -] - -[[package]] -name = "valuable" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "vsock" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e8b4d00e672f147fc86a09738fadb1445bd1c0a40542378dfb82909deeee688" -dependencies = [ - "libc", - "nix", -] - -[[package]] -name = "vte" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5022b5fbf9407086c180e9557be968742d839e68346af7792b8592489732197" -dependencies = [ - "utf8parse", - "vte_generate_state_changes", -] - -[[package]] -name = "vte_generate_state_changes" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e369bee1b05d510a7b4ed645f5faa90619e05437111783ea5848f28d97d3c2e" -dependencies = [ - "proc-macro2", - "quote", -] - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.9.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "wasm-bindgen" -version = "0.2.93" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5" -dependencies = [ - "cfg-if", - "once_cell", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.93" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn 2.0.87", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61e9300f63a621e96ed275155c108eb6f843b6a26d053f122ab69724559dc8ed" -dependencies = [ - "cfg-if", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.93" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.93" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.93" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484" - -[[package]] -name = "web-sys" -version = "0.3.70" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f20c57d8d7db6d3b86154206ae5d8fba62dd39573114de97c2cb0578251f8e1" - -[[package]] -name = "webpki-roots" -version = "0.26.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841c67bff177718f1d4dfefde8d8f0e78f9b6589319ba88312f567fc5841a958" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "which" -version = "4.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" -dependencies = [ - "either", - "home", - "once_cell", - "rustix", -] - -[[package]] -name = "which" -version = "7.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9cad3279ade7346b96e38731a641d7343dd6a53d55083dd54eadfa5a1b38c6b" -dependencies = [ - "either", - "home", - "rustix", - "winsafe", -] - -[[package]] -name = "widestring" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7219d36b6eac893fa81e84ebe06485e7dcbb616177469b142df14f1f4deb1311" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" -dependencies = [ - "windows-sys 0.59.0", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" -dependencies = [ - "windows-core 0.57.0", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-core" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-core" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2ed2439a290666cd67ecce2b0ffaad89c2a56b976b736e6ece670297897832d" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-result 0.1.2", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-implement" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "windows-interface" -version = "0.57.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "windows-registry" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e400001bb720a623c1c69032f8e3e4cf09984deec740f007dd2b03ec864804b0" -dependencies = [ - "windows-result 0.2.0", - "windows-strings", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-result" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-result" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-strings" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" -dependencies = [ - "windows-result 0.2.0", - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "winnow" -version = "0.6.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68a9bda4691f099d435ad181000724da8e5899daa10713c2d432552b9ccd3a6f" -dependencies = [ - "memchr", -] - -[[package]] -name = "winreg" -version = "0.50.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" -dependencies = [ - "cfg-if", - "windows-sys 0.48.0", -] - -[[package]] -name = "winsafe" -version = "0.0.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" - -[[package]] -name = "wyz" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f360fc0b24296329c78fda852a1e9ae82de9cf7b27dae4b7f62f118f77b9ed" -dependencies = [ - "tap", -] - -[[package]] -name = "x25519-dalek" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" -dependencies = [ - "curve25519-dalek", - "rand_core 0.6.4", - "serde", - "zeroize", -] - -[[package]] -name = "x509-cert" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" -dependencies = [ - "const-oid", - "der", - "spki", -] - -[[package]] -name = "x509-parser" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcbc162f30700d6f3f82a24bf7cc62ffe7caea42c0b2cba8bf7f3ae50cf51f69" -dependencies = [ - "asn1-rs", - "data-encoding", - "der-parser", - "lazy_static", - "nom", - "oid-registry", - "ring", - "rusticata-macros", - "thiserror 1.0.65", - "time", -] - -[[package]] -name = "yansi" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" -dependencies = [ - "is-terminal", -] - -[[package]] -name = "yasna" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" -dependencies = [ - "time", -] - -[[package]] -name = "zerocopy" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" -dependencies = [ - "byteorder", - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.7.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "zeroize" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] diff --git a/Cargo.toml b/Cargo.toml deleted file mode 100644 index 4195deb3b2..0000000000 --- a/Cargo.toml +++ /dev/null @@ -1,165 +0,0 @@ -[workspace.package] -version = "0.3.4" -authors = ["Kevin Wang ", "Leechael "] -edition = "2021" -license = "MIT" - -[workspace] -members = [ - "kms", - "kms/rpc", - "ra-rpc", - "ra-tls", - "tdx-attest-sys", - "tdx-attest", - "tdxctl", - "iohash", - "tappd", - "tappd/rpc", - "teepod", - "teepod/rpc", - "tproxy", - "tproxy/rpc", - "certgen", - "certbot", - "certbot/cli", - "ct_monitor", - "cc-eventlog", - "supervisor", - "supervisor/client", - "rocket-vsock-listener", - "http-client", - "host-api", - "guest-api", - "load_config", -] -resolver = "2" - -[workspace.dependencies] -# Internal dependencies -ra-rpc = { path = "ra-rpc", default-features = false } -ra-tls = { path = "ra-tls" } -tproxy-rpc = { path = "tproxy/rpc" } -kms-rpc = { path = "kms/rpc" } -tappd-rpc = { path = "tappd/rpc" } -teepod-rpc = { path = "teepod/rpc" } -cc-eventlog = { path = "cc-eventlog" } -supervisor = { path = "supervisor" } -supervisor-client = { path = "supervisor/client" } -tdx-attest = { path = "tdx-attest" } -tdx-attest-sys = { path = "tdx-attest-sys" } -certbot = { path = "certbot" } -rocket-vsock-listener = { path = "rocket-vsock-listener" } -host-api = { path = "host-api", default-features = false } -guest-api = { path = "guest-api", default-features = false } -http-client = { path = "http-client", default-features = false } -load_config = { path = "load_config" } - -# Core dependencies -anyhow = "1.0.94" -chrono = "0.4.38" -clap = { version = "4.5.22", features = ["derive", "string"] } -dashmap = "6.1.0" -fs-err = "3.0.0" -path-absolutize = "3.1.1" -futures = "0.3.31" -git-version = "0.3.9" -libc = "0.2.167" -log = "0.4.22" -notify = "7.0.0" -rand = "0.8.5" -tracing = "0.1.40" -tracing-subscriber = { version = "0.3.18", features = ["env-filter"] } -safe-write = "0.1.1" -nix = "0.29.0" -sd-notify = "0.4.3" - -# Serialization/Parsing -bon = "3.2.0" -base64 = "0.22.1" -hex = "0.4.3" -hex_fmt = "0.3.0" -prost = "0.13.3" -scale = { version = "3.6.12", package = "parity-scale-codec", features = ["derive"] } -serde = { version = "1.0.210", features = ["derive"] } -serde-human-bytes = "0.1.0" -serde_json = "1.0" -toml = "0.8.19" -toml_edit = { version = "0.22.22", features = ["serde"] } -yasna = "0.5.2" -bytes = "1.9.0" -figment = "0.10.19" - -# Networking/HTTP -bollard = "0.18.1" -http = "1.2.0" -http-body-util = "0.1.2" -hyper = { version = "1.5.1", features = ["client", "http1"] } -hyper-util = { version = "0.1.10", features = ["client", "client-legacy", "http1"] } -hyperlocal = "0.9.1" -ipnet = { version = "2.10.1", features = ["serde"] } -reqwest = { version = "0.12.9", default-features = false, features = ["json", "rustls-tls", "charset", "hickory-dns"] } -rocket = { git = "https://github.com/rwf2/Rocket", branch = "master", features = ["mtls"] } -rocket-apitoken = { git = "https://github.com/kvinwang/rocket-apitoken", branch = "dev" } -tokio = { version = "1.42.0" } -tokio-vsock = "0.6.0" -sysinfo = "0.33.0" -default-net = "0.22.0" - -# Cryptography/Security -aes-gcm = "0.10.3" -curve25519-dalek = "4.1.3" -dcap-qvl = "0.1.6" -elliptic-curve = { version = "0.13.8", features = ["pkcs8"] } -getrandom = "0.2.15" -hkdf = "0.12.4" -p256 = "0.13.2" -ring = "0.17.8" -rustls = "0.23.19" -rustls-pki-types = "1.8.0" -schnorrkel = "0.11.4" -sha2 = "0.10.8" -sha3 = "0.10.8" -blake2 = "0.10.6" -tokio-rustls = { version = "0.26.0", features = ["ring"] } -x25519-dalek = { version = "2.0.1", features = ["static_secrets"] } - -# Certificate/DNS -hickory-resolver = "0.24.1" -instant-acme = "0.7.2" -rcgen = { version = "0.13.1", features = ["pem"] } -x509-parser = "0.16.0" - -# RPC/Protocol -prpc = "0.5.0" -prpc-build = "0.5.1" - -# Development/Testing -bindgen = "0.70.1" -cc = "1.2.2" -documented = "0.9.1" -enum_dispatch = "0.3.13" -insta = "1.41.1" -num_enum = "0.7.3" -thiserror = "2.0.4" -derive_more = "1.0.0" -tempfile = "3.14.0" - -# Utilities -dirs = "5.0.1" -humantime = "2.1.0" -parcelona = "0.4.3" -pin-project = "1.1.7" -regex = "1.11.1" -rinja = "0.3.5" -shared_child = "1.0.1" -strip-ansi-escapes = "0.2.0" -tailf = "0.1.2" -time = "0.3.37" -uuid = { version = "1.11.0", features = ["v4"] } -which = "7.0.0" -smallvec = "1.13.2" -cmd_lib = "1.9.5" - -[patch.crates-io] -tokio-vsock = { git = "https://github.com/kvinwang/tokio-vsock", branch = "shared-self-accept" } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/Apache-2.0.txt b/LICENSES/Apache-2.0.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/LICENSES/Apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSES/BSD-2-Clause-Patent.txt b/LICENSES/BSD-2-Clause-Patent.txt new file mode 100644 index 0000000000..31de6e498e --- /dev/null +++ b/LICENSES/BSD-2-Clause-Patent.txt @@ -0,0 +1,19 @@ +Copyright (c) + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +Subject to the terms and conditions of this license, each copyright holder and contributor hereby grants to those receiving rights under this license a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except for failure to satisfy the conditions of this license) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer this software, where such license applies only to those patent claims, already acquired or hereafter acquired, licensable by such copyright holder or contributor that are necessarily infringed by: + +(a) their Contribution(s) (the licensed copyrights of copyright holders and non-copyrightable additions of contributors, in source or binary form) alone; or + +(b) combination of their Contribution(s) with the work of authorship to which such Contribution(s) was added by such copyright holder or contributor, if, at the time the Contribution is added, such addition causes such combination to be necessarily infringed. The patent license shall not apply to any other combinations which include the Contribution. + +Except as expressly stated above, no rights or licenses from any copyright holder or contributor is granted under this license, whether expressly, by implication, estoppel or otherwise. + +DISCLAIMER + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/LICENSES/BSD-3-Clause.txt b/LICENSES/BSD-3-Clause.txt new file mode 100644 index 0000000000..086d3992cb --- /dev/null +++ b/LICENSES/BSD-3-Clause.txt @@ -0,0 +1,11 @@ +Copyright (c) . + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000000..0e259d42c9 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/GPL-2.0-only.txt b/LICENSES/GPL-2.0-only.txt new file mode 100644 index 0000000000..17cb286430 --- /dev/null +++ b/LICENSES/GPL-2.0-only.txt @@ -0,0 +1,117 @@ +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. + +Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. + +1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. + + c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. + +4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. + +6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. + +7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. + +10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the program's name and an idea of what it does. Copyright (C) yyyy name of author + + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. + +signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice diff --git a/LICENSES/LGPL-2.1-or-later.txt b/LICENSES/LGPL-2.1-or-later.txt new file mode 100644 index 0000000000..c6487f4fdf --- /dev/null +++ b/LICENSES/LGPL-2.1-or-later.txt @@ -0,0 +1,176 @@ +GNU LESSER GENERAL PUBLIC LICENSE + +Version 2.1, February 1999 + +Copyright (C) 1991, 1999 Free Software Foundation, Inc. +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] + +Preamble + +The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. + +To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. + +Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. + +When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. + +We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. + +For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. + +Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. + +GNU LESSER GENERAL PUBLIC LICENSE +TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". + +A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. + +The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) + +"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. + +Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. + +1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. + +You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. + +2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. + +(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. + +3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. + +Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of the Library into a program that is not a library. + +4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. + +5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. + +However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. + +When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. + +6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: + + a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. + + e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. + +For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. + +It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. + +7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. + + b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. + +9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. + +10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. + +11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. + +This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. + +12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. + +13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. + +14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. + +NO WARRANTY + +15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Libraries + +If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). + +To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. + + one line to give the library's name and an idea of what it does. + Copyright (C) year name of author + + This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: + +Yoyodyne, Inc., hereby disclaims all copyright interest in +the library `Frob' (a library for tweaking knobs) written +by James Random Hacker. + +signature of Ty Coon, 1 April 1990 +Ty Coon, President of Vice +That's all there is to it! diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt new file mode 100644 index 0000000000..d817195dad --- /dev/null +++ b/LICENSES/MIT.txt @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile index f7947f6673..ab7900f6f1 100644 --- a/Makefile +++ b/Makefile @@ -1,18 +1,73 @@ -DOMAIN := local -TO := ./certs +# SPDX-FileCopyrightText: © 2026 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 -.PHONY: clean run all certs +# Submodules for the deprecated Yocto backend. +OS_YOCTO_SUBMODULES := \ + os/yocto/deps/bitbake \ + os/yocto/deps/openembedded-core \ + os/yocto/deps/meta-yocto \ + os/yocto/deps/meta-confidential-compute \ + os/yocto/deps/meta-virtualization \ + os/yocto/deps/meta-openembedded \ + os/yocto/deps/meta-rust-bin \ + os/yocto/deps/meta-security -all: +.PHONY: help core core-check core-test sdk-test os os-image os-repro-check \ + os-image-mkosi os-repro-check-mkosi os-yocto os-deps os-image-yocto os-repro-check-yocto -certs: ${TO} +help: + @echo "dstack monorepo targets:" + @echo " core build the Rust workspace" + @echo " core-check check the Rust workspace" + @echo " core-test test the Rust workspace with the simulator" + @echo " sdk-test run all public SDK tests" + @echo " os build the guest OS natively with the default (mkosi) backend" + @echo " os-image build one production guest image with mkosi in the pinned container" + @echo " os-repro-check build twice with mkosi and compare outputs byte for byte" + @echo "" + @echo "Deprecated Yocto targets (do not use for new work; use the mkosi targets above):" + @echo " os-yocto build the guest OS natively with Yocto" + @echo " os-deps initialize only the Yocto dependency submodules" + @echo " os-image-yocto build one production guest image with Yocto" + @echo " os-repro-check-yocto build twice with Yocto and compare outputs" -${TO}: - mkdir -p ${TO} - cargo run --bin certgen -- generate --domain ${DOMAIN} --output-dir ${TO} +core: + cargo build --manifest-path dstack/Cargo.toml -run: - $(MAKE) -C mkguest run +core-check: + cargo check --manifest-path dstack/Cargo.toml --workspace -clean: - rm -rf ${TO} +core-test: + ./dstack/run-tests.sh + +sdk-test: + cd sdk && ./run-tests.sh + +os: + ./os/build.sh + +# The mkosi backend vendors no submodules, so these do not depend on os-deps. +os-image: + ./os/mkosi/repro-build/repro-build.sh + +os-repro-check: + ./os/mkosi/repro-build/repro-build.sh -c + +# Aliases kept for existing callers. +os-image-mkosi: os-image + +os-repro-check-mkosi: os-repro-check + +# Deprecated Yocto backend. Kept only to rebuild existing Yocto images. +os-yocto: + ./os/build.sh --backend yocto + +os-deps: + git submodule update --init --depth 1 -- $(OS_YOCTO_SUBMODULES) + +os-image-yocto: os-deps + cd os/yocto/repro-build && ./repro-build.sh -n + +os-repro-check-yocto: os-deps + cd os/yocto/repro-build && ./repro-build.sh diff --git a/README.md b/README.md index f2e6daefa2..e001b84c3f 100644 --- a/README.md +++ b/README.md @@ -1,426 +1,274 @@ -# Dstack +
-Dstack is a **developer friendly** and **security first** SDK to simplify the deployment of arbitrary Docker-based apps into TEE. +![dstack](./dstack-logo.svg) -Main features: +### The open framework for confidential AI. -- 🔒 Deploy Docker apps securely in TEE in minutes -- 🛠️ Use familiar tools - just write a docker-compose.yaml -- 🔑 Safely manage secrets and sensitive data -- 📡 Expose services via built-in TLS termination +[![GitHub Stars](https://img.shields.io/github/stars/dstack-tee/dstack?style=flat-square&logo=github)](https://github.com/Dstack-TEE/dstack/stargazers) +[![License](https://img.shields.io/github/license/dstack-tee/dstack?style=flat-square)](https://github.com/Dstack-TEE/dstack/blob/next/LICENSE) +[![REUSE status](https://api.reuse.software/badge/github.com/Dstack-TEE/dstack)](https://api.reuse.software/info/github.com/Dstack-TEE/dstack) +[![Plumber Score](https://score.getplumber.io/github.com/Dstack-TEE/dstack.svg?style=flat-square)](https://score.getplumber.io/github.com/Dstack-TEE/dstack) +[![Ask DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/Dstack-TEE/dstack) +[![Telegram](https://img.shields.io/badge/Telegram-2CA5E0?style=flat-square&logo=telegram&logoColor=white)](https://t.me/+UO4bS4jflr45YmUx) -Dstack is community driven. Open sourced and built by [Kevin Wang](https://github.com/kvinwang) and many others from [Phala Network](https://github.com/Phala-Network), inspired by [Andrew Miller](https://github.com/amiller) (Flashbots & Teleport), and contributed by [Neithermind](https://github.com/neithermind) and [many others](#contributors). +Original Contributors: Hang Yin, Kevin Wang, Andrew Miller -![](./docs/assets/org-contributors-2024-12-26.png) +[Documentation](https://docs.phala.com/dstack) · [Security](./SECURITY.md) · [Examples](https://github.com/Dstack-TEE/dstack-examples) · [Community](https://t.me/+UO4bS4jflr45YmUx) -# Overview +
-Components in Dstack: +--- -- `teepod`: A service running in bare TDX host to manage CVMs -- `tproxy`: A reverse proxy to forward TLS connections to CVMs -- `kms`: A KMS server to generate keys for CVMs -- `tappd`: A service running in CVM to serve containers' key derivation and attestation requests -- `meta-dstack`: A Yocto meta layer to build CVM guest images +## What is dstack? -The overall architecture is shown below: -![arch](./docs/assets/arch.png) +dstack is the open framework for confidential AI — deploy AI applications with cryptographic privacy guarantees. -# Directory structure +AI providers ask users to trust them with sensitive data. But trust doesn't scale, and trust can't be verified. With dstack, your containers run inside confidential VMs (Intel TDX) with native support for NVIDIA Confidential Computing (H100, Blackwell). Users can cryptographically verify exactly what's running: private AI with your existing Docker workflow. -```text -dstack/ - kms/ A prototype KMS server - tappd/ A service running in CVM to serve containers' key derivation and attestation requests. - tdxctl/ A CLI tool getting TDX quote, extending RTMR, generating cert for RA-TLS, etc. - teepod/ A service running in bare TDX host to manage CVMs - tproxy/ A reverse proxy to forward TLS connections to CVMs - certbot/ A tool to automatically obtain and renew TLS certificates for tproxy - ra-rpc/ RA-TLS support for pRPC - ra-tls/ RA-TLS support library - tdx-attest/ Guest library for getting TDX quote and extending RTMR -``` - -# Build and play locally - -## Prerequisites - -- A TDX host machine setup following [canonical/tdx](https://github.com/canonical/tdx) -- Public IPv4 address assigned to the machine -- A domain name you can modify DNS records - -## Install dependencies - -```bash -# for Ubuntu 24.04 -sudo apt install -y build-essential chrpath diffstat lz4 wireguard-tools mkisofs -# install rust -curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -``` +## Supported Platforms -## Build and run +| Platform | Status | Attestation | +|----------|--------|-------------| +| **Bare metal TDX** | Available | TDX | +| **Bare metal AMD SEV-SNP** | Available | SEV-SNP | +| **[Phala Cloud](https://cloud.phala.network)** | Available | TDX | +| **GCP Confidential VMs** | Available | TDX + TPM | +| **AWS Nitro Enclaves** | Available | NSM | -```bash -git clone https://github.com/Dstack-TEE/meta-dstack.git --recursive -cd meta-dstack/ -source dev-setup +## Features -mkdir build -cd build -../build.sh -# This outputs the following message: -# Config file ../build-config.sh created, please edit it to configure the build +**Zero friction onboarding** +- **Docker Compose native**: Bring your docker-compose.yaml as-is. No SDK, no code changes. +- **Encrypted by default**: Network traffic and disk storage encrypted out of the box. -vim ../build-config.sh -``` +**Hardware-rooted security** +- **Private by hardware**: Data encrypted in memory, inaccessible even to the host. +- **Reproducible OS**: Deterministic builds mean anyone can verify the OS image hash. +- **Workload identity**: Every app gets an attested identity users can verify cryptographically. +- **Confidential GPUs**: Native support for NVIDIA Confidential Computing (H100, Blackwell). -Now edit the config file. The following configurations values must be changed properly according to your environment: - -```bash -# The internal port for teepod to listen to requests from you -TEEPOD_RPC_LISTEN_PORT=9080 -# The start CID for teepod to allocate to CVMs -TEEPOD_CID_POOL_START=20000 - -# The internal port for kms to listen to requests from CVMs -KMS_RPC_LISTEN_PORT=9043 -# The internal port for tproxy to listen to requests from CVMs -TPROXY_RPC_LISTEN_PORT=9070 - -# WireGuard interface name for tproxy -TPROXY_WG_INTERFACE=tproxy-kvin -# WireGuard listening port for tproxy -TPROXY_WG_LISTEN_PORT=9182 -# WireGuard server IP for tproxy -TPROXY_WG_IP=10.0.3.1 -# WireGuard client IP range -TPROXY_WG_CLIENT_IP_RANGE=10.0.3.0/24 -# The public port for tproxy to listen to requests that would be forwarded to app in CVMs -TPROXY_SERVE_PORT=9443 - -# The public domain name for tproxy. Please set a wildacard DNS record (e.g. *.app.kvin.wang in this example) -# for this domain that points the IP address of your TDX host. -TPROXY_PUBLIC_DOMAIN=app.kvin.wang -# The path to the TLS certificate for tproxy's public endpoint -TPROXY_CERT=/etc/rproxy/certs/cert.pem -# The path to the TLS key for tproxy's public endpoint -TPROXY_KEY=/etc/rproxy/certs/key.pem -``` +**Trustless operations** +- **Isolated keys**: Per-app keys derived in TEE. Survives hardware failure. Never exposed to operators. +- **Code governance**: Updates follow predefined rules (e.g., multi-party approval). Operators can't swap code or access secrets. -Run build.sh again to build the artifacts. +## Getting Started -```bash -../build.sh +**Try it now:** Chat with LLMs running in TEE at [chat.redpill.ai](https://chat.redpill.ai). Click the shield icon to verify attestations from Intel TDX and NVIDIA GPUs. -# If everything is okay, you should see the built artifacts in the `build` directory. -$ ls -certs images kms kms.toml run teepod teepod.toml tproxy tproxy.toml +**Deploy your own:** -# The wireguard interface should be set up: -$ ifconfig tproxy-kvin -tproxy-kvin: flags=209 mtu 1420 - inet 10.0.3.1 netmask 255.255.255.0 destination 10.0.3.1 - unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 1000 (UNSPEC) - RX packets 4839 bytes 839320 (839.3 KB) - RX errors 0 dropped 0 overruns 0 frame 0 - TX packets 3836 bytes 507540 (507.5 KB) - TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0 +```yaml +# docker-compose.yaml +services: + vllm: + image: vllm/vllm-openai:latest + runtime: nvidia + command: --model Qwen/Qwen2.5-7B-Instruct + ports: + - "8000:8000" ``` -Now you can open 3 terminals to start the components: - -1. Run `./kms` -2. Run `sudo ./tproxy` -3. Run `./teepod` - -## Deploy an App -Open the teepod webpage [http://localhost:9080](http://localhost:9080)(change the port according to your configuration) on your local machine to deploy a `docker-compose.yaml` file: - -![teepod](./docs/assets/teepod.png) - -After the container deployed, it should need some time to start the CVM and the containers. Time would be vary depending on your workload. +Deploy to a self-hosted TDX machine with the `dstackup install` -> `dstack deploy` workflow, or use [Phala Cloud](https://cloud.phala.network) for managed infrastructure. AMD SEV-SNP hosts use the same workflow when the selected guest image includes `digest.txt`. -- Click the [Logs] button to see the logs of the CVM, you can see if the container is finished starting there. +Setting up dstack on your own hardware? Start with the [self-hosted quick onboarding guide](./docs/onboarding.md) -- Once the container is running, you can click the [Dashboard] button to see some information of the container. And the logs of the containers can be seen in the [Dashboard] page. +Building or customizing the guest OS itself? Follow the [guest-OS build guide](./docs/building-guest-os.md). - ![tappd](./docs/assets/tappd.png) +Developing without TEE hardware? Use a development image with +[no-TEE mode and swtpm](./docs/development-without-tee.md). -- You can open tproxy's dashboard at [https://localhost:9070](https://localhost:9070) to see the CVM's wireguard ip address, as shown below: +## Architecture -![tproxy](./docs/assets/tproxy.png) +![Architecture](./docs/assets/arch.png) -## Pass Secrets to Apps -When deploying a new App, you can pass private data via Encrypted Environment Variables. These variables can be referenced in the docker-compose.yaml file as shown below: +### Repository layout -![secret](./docs/assets/secret.png) - -The environment variables will be encrypted in the client-side and decrypted in the CVM before being passed to the containers. - -## Access the App - -Once the app is deployed and listening on an HTTP port, you can access the HTTP service via tproxy's public domain. The ingress mapping rules are: - -- `[s].` maps to port `80` or `443` if with `s` in the CVM. -- `-[s].` maps to port `` in the CVM. - -For example, `3327603e03f5bd1f830812ca4a789277fc31f577-8080.app.kvin.wang` maps to port `8080` in the CVM. - -Where the `` can be either the app id or the instance id. If the app id is used, one of the instances will be selected by the load balancer. -If the `id-port` part ends with `s`, it means the TLS connection will be passthrough to the app rather than terminating at tproxy. - -You can also ssh into the CVM to inspect more information, if your deployment uses the image `dstack-x.x.x-dev`: - -```bash -# The IP address of the CVM can be found in the tproxy dashboard. -ssh root@10.0.3.2 +```text +dstack/ Core services, Rust crates, host and guest runtime code +sdk/ Stable public SDK paths +os/ Guest-OS payload, image contract, and build backends +docs/ User and operator documentation +tools/ Standalone development and security tools ``` -## Getting TDX quote in docker container +The default and recommended OS backend is mkosi under `os/mkosi/`. The Yocto +backend under `os/yocto/` is deprecated and kept only to rebuild existing +images; do not use it for new work. Shared rootfs payload and release assembly +stay outside the backends so they are not duplicated. See +[`os/README.md`](./os/README.md). -To get a TDX quote within app containers: +Scripts follow the same ownership boundaries: component-specific helpers stay +beside their component under `dstack/`; files installed into every guest live +in `os/common/rootfs/`; backend-neutral image tooling lives in `os/image/`; +mkosi-only helpers live in `os/mkosi/scripts/` (deprecated Yocto-only helpers +in `os/yocto/scripts/`); and repository-wide standalone utilities live in +`tools/`. -1. Mount `/var/run/tappd.sock` to the target container in `docker-compose.yaml` +Your container runs inside a Confidential VM, such as Intel TDX or AMD SEV-SNP, with optional GPU isolation via NVIDIA Confidential Computing. The CPU TEE protects application logic; the GPU TEE protects model weights and inference data. - ```yaml - version: '3' - services: - nginx: - image: nginx:latest - volumes: - - /var/run/tappd.sock:/var/run/tappd.sock - ports: - - "8080:80" - restart: always - ``` +**Core components:** -2. Execute the quote request command in the container. +- **Guest Agent**: Runs inside each CVM. Generates TDX attestation quotes so users can verify exactly what's running. Provisions per-app cryptographic keys from KMS. Encrypts local storage. Apps interact via `/var/run/dstack.sock`. - ```bash - # The argument report_data accepts binary data encoding in hex string. - # The actual report_data passing the to the underlying TDX driver is sha2_256(report_data). - curl -X POST --unix-socket /var/run/tappd.sock -d '{"report_data": "0x1234deadbeef"}' http://localhost/prpc/Tappd.TdxQuote?json | jq . - ``` +- **KMS**: Runs in its own TEE. Verifies TDX quotes before releasing keys. Enforces authorization policies defined in on-chain smart contracts — operators cannot bypass these checks. Derives deterministic keys bound to each app's attested identity. -## Container logs +- **Gateway**: Terminates TLS at the edge and provisions ACME certificates automatically. Routes traffic to CVMs. All internal communication uses RA-TLS for mutual attestation. -Container logs can be obtained from the CVM's `dashboard` page or by curl: +- **VMM**: Runs on bare-metal TDX hosts. Parses docker-compose files directly — no app changes needed. Boots CVMs from a reproducible OS image. Allocates CPU, memory, and confidential GPU resources. -```bash -curl 'http://.app.kvin.wang:9090/logs/?since=0&until=0&follow=true&text=true×tamps=true&bare=true' -``` +[Full security model →](./docs/security/security-model.md) -Replace `` and `` with actual values. Available parameters: +## Security and Trust -- since=0: Starting Unix timestamp for log retrieval -- until=0: Ending Unix timestamp for log retrieval -- follow: Enables continuous log streaming -- text: Returns human-readable text instead of base64 encoding -- timestamps: Adds timestamps to each log line -- bare: Returns the raw log lines without json format +Security docs are linked here so deployers and reviewers can quickly find the trust model, production guidance, audit, and the status of already-answered public findings. -The response of the RPC looks like: -``` -$ curl 'http://0.0.0.0:9190/logs/zk-provider-server?text×tamps' -{"channel":"stdout","message":"2024-09-29T03:05:45.209507046Z Initializing Rust backend...\n"} -{"channel":"stdout","message":"2024-09-29T03:05:45.209543047Z Calling Rust function: init\n"} -{"channel":"stdout","message":"2024-09-29T03:05:45.209544957Z [2024-09-29T03:05:44Z INFO rust_prover] Initializing...\n"} -{"channel":"stdout","message":"2024-09-29T03:05:45.209546381Z [2024-09-29T03:05:44Z INFO rust_prover::groth16] Starting setup process\n"} -``` +- [Security Overview](./docs/security/) - entry point for users, operators, researchers, and AI agents +- [Security Model](./docs/security/security-model.md) - threat model, trust boundaries, and verification checklist +- [Public Security Reports](./docs/security/public-security-reports.md) - public status for security reports and related hardening work +- [Security Best Practices](./docs/security/security-best-practices.md) - production settings and hardening guidance +- [Security Audit](./docs/security/dstack-audit.pdf) - third-party audit by zkSecurity +- [Report a Vulnerability](./SECURITY.md) - use GitHub's private security reporting path -## Reverse proxy: TLS Passthrough +Please do not disclose exploitable vulnerabilities in public GitHub issues. Use the private reporting path in [SECURITY.md](./SECURITY.md). -The build configuration for TLS Passthrough is: +## SDKs -```bash -TPROXY_LISTEN_PORT_PASSTHROUGH=9008 -``` +Apps communicate with the guest agent via HTTP over `/var/run/dstack.sock`. Use the [HTTP API](./sdk/curl/api.md) directly with curl, or use a language SDK: -With this configuration, tproxy listens port `9008` for incoming TLS connections and forwards them to the appropriate Tapp based on `SNI`, where SNI represents your custom domain and the forwarding destination is determined by your DNS records. +| Language | Install | Docs | +|----------|---------|------| +| Python | `pip install dstack-sdk` | [README](./sdk/python/README.md) | +| TypeScript | `npm install @phala/dstack-sdk` | [README](./sdk/js/README.md) | +| Rust | `cargo add dstack-sdk` | [README](./sdk/rust/README.md) | +| Go | `go get github.com/Dstack-TEE/dstack/sdk/go/dstack` | [README](./sdk/go/README.md) | -For example, assuming I've deployed an app at `3327603e03f5bd1f830812ca4a789277fc31f577`, as shown below: +## Documentation -![appid](./docs/assets/appid.png) +**For Developers** +- [Confidential AI](./docs/confidential-ai.md) - Inference, agents, and training with hardware privacy +- [Usage Guide](./docs/usage.md) - Deploying and managing apps +- [Verification](./docs/verification.md) - How to verify TEE attestation -Now, I want to use my custom domain `tapp-nginx.kvin.wang` to access the Tapp. I need to set up two DNS records with my DNS provider (Cloudflare in my case): +**For Operators** +- [Hardware Enablement](./docs/hardware-enablement.md) - Prepare a TDX or AMD SEV-SNP host +- [AMD SEV-SNP](./docs/amd-sev-snp.md) - Image, attestation, and key-release requirements +- [TDX Hardware Key Provider](./docs/tdx-seal-key-provider.md) - Recover a CVM's keys from TDX sealing without a KMS +- [Self-hosted Quick Onboarding](./docs/onboarding.md) - First app on one host +- [Build the Guest OS](./docs/building-guest-os.md) - Build and verify bootable images from source +- [Deployment](./docs/deployment.md) - Self-hosting on TDX or AMD SEV-SNP hardware +- [Upgrading to 0.6](./docs/upgrading-to-0.6.md) - Upgrading from dstack 0.5.x +- [On-Chain Governance](./docs/onchain-governance.md) - Smart contract authorization +- [Gateway](./docs/dstack-gateway.md) - Gateway configuration -1. `A` or `CNAME` record to point the domain to the tdx machine: +**Reference** +- [Guest Agent API v1](./docs/guest-api-v1.md) - Key derivation, signature chains, and the versioned guest API +- [Guest Agent API v0](./docs/guest-api-v0.md) - The frozen legacy surface, for clients that still speak the unversioned API +- [Guest Agent API access control](./docs/guest-api-auth.md) - Scopes, tokens, and anonymous access on port 8090 +- [App Compose Format](./docs/normalized-app-compose.md) - Compose file specification +- [Intel TDX Attestation](./docs/attestation-tdx.md) - Measurement and runtime-event verification +- [Native TEE Interfaces](./docs/native-tee-interfaces.md) - Advanced compatibility with Linux TEE devices and configfs-tsm +- [VMM CLI Guide](./docs/vmm-cli-user-guide.md) - Command-line reference +- [Design Decisions](./docs/design-and-hardening-decisions.md) - Architecture rationale +- [FAQ](./docs/faq.md) - Frequently asked questions - ![tapp-dns-a](./docs/assets/tapp-dns-a.png) +## FAQ -2. `TXT` record to instruct the Tproxy to direct the request to the specified Tapp: +
+Why not use AWS Nitro / Azure Confidential VMs / GCP directly? - ![tapp-dns-txt](./docs/assets/tapp-dns-txt.png) +You can — but you'll build everything yourself: attestation verification, key management, Docker orchestration, certificate provisioning, and governance. dstack provides all of this out of the box. -Where +| Approach | Docker native | GPU TEE | Key management | Attestation tooling | Open source | +|----------|:-------------:|:-------:|:--------------:|:-------------------:|:-----------:| +| **dstack** | ✓ | ✓ | ✓ | ✓ | ✓ | +| AWS Nitro Enclaves | - | - | Manual | Manual | - | +| Azure Confidential VMs | - | Preview | Manual | Manual | - | +| GCP Confidential Computing | - | - | Manual | Manual | - | -`_tapp-address.tapp-nginx.kvin.wang` means configuring the tapp destination address of domain `tapp-nginx.kvin.wang`. +Cloud providers give you the hardware primitive. dstack gives you the full stack: reproducible OS images, automatic attestation, per-app key derivation, TLS certificates, and smart contract governance. No vendor lock-in. -The TXT record value `3327603e03f5bd1f830812ca4a789277fc31f577:8043` means that requests sent to `tapp-nginx.kvin.wang` will be processed by Tapp `3327603e03f5bd1f830812ca4a789277fc31f577` on port `8043` +
-Given the config `TPROXY_LISTEN_PORT_PASSTHROUGH=9008`, now we can go to [`https://tapp-nginx.kvin.wang:9008`](https://tapp-nginx.kvin.wang:9008) and the request will be handled by the service listening on `8043` in Tapp `3327603e03f5bd1f830812ca4a789277fc31f577`. +
+How is this different from SGX/Gramine? -## Upgrade an App +SGX requires porting applications to enclaves. dstack uses full-VM isolation (Intel TDX) — bring your Docker containers as-is. Plus GPU TEE support that SGX doesn't offer. -Got to the teepod webpage, click the [Upgrade] button, select or paste the compose file you want to upgrade to, and click the [Upgrade] button again. -Upon successful initiation of the upgrade, you'll see a message prompting you to run the following command in your terminal to authorize the upgrade through KMS: +
-```shell -./kms-allow-upgrade.sh -``` - -The app id does not change after the upgrade. Stop and start the app to apply the upgrade. +
+What's the performance overhead? -## HTTPS Certificate Transparency +Minimal. Intel TDX adds ~2-5% overhead for CPU workloads. NVIDIA Confidential Computing has negligible impact on GPU inference. The main cost is memory encryption, which is hardware-accelerated on supported CPUs. -In the tutorial above, we used a TLS certificate with a private key external to the TEE (Tproxy-CVM here). To establish trust, we need to generate and maintain the certificate's private key within the TEE and provide evidence that all TLS certificates for the domain were originate solely from Tproxy-CVM. +
-By combining Certificate Transparency Logs and CAA DNS records, we can make best effort to minimize security risks. Here's our approach: +
+Is this production-ready? -- Set CAA records to allow only the account created in Tproxy-CVM to request Certificates. -- Launch a program to monitor Certificate Transparency Log and give alarm once any certificate issued to a pubkey that isn’t generated by Tproxy. +Yes. dstack powers production AI infrastructure at [OpenRouter](https://openrouter.ai/provider/phala) and [NEAR AI](https://x.com/ilblackdragon/status/1962920246148268235). The framework has been [audited by zkSecurity](./docs/security/dstack-audit.pdf) and is a Linux Foundation Confidential Computing Consortium project. -### Configurations +
-To launch Certbot, you need to own a domain hosted on Cloudflare. Obtain an API token with DNS operation permissions from the Cloudflare dashboard. Configure it in the `build-config.sh`: +
+Can I run this on my own hardware? -```bash -# The directory to store the auto obtained TLS certificate and key -TPROXY_CERT=${CERBOT_WORKDIR}/live/cert.pem -TPROXY_KEY=${CERBOT_WORKDIR}/live/key.pem +Yes. dstack runs on supported TEE-capable servers, including Intel TDX-capable hardware. See the [deployment guide](./docs/deployment.md) for self-hosting instructions. You can also use [Phala Cloud](https://cloud.phala.network) for managed infrastructure. -# for certbot -CF_ZONE_ID=cc0a40... -CF_API_TOKEN=g-DwMH... -# ACME_URL=https://acme-v02.api.letsencrypt.org/directory -ACME_URL=https://acme-staging-v02.api.letsencrypt.org/directory -``` +
-Then re-run the ../build.sh: +
+What TEE hardware is supported? -```bash -../build.sh -``` +- **GCP**: Intel TDX (Confidential VMs) +- **AWS**: Nitro Enclaves (NSM attestation) +- **Bare metal**: Intel TDX (4th/5th Gen Xeon) and AMD SEV-SNP (Milan, Genoa, Turin) with dstack OS 0.6.6 or later +- **GPUs**: NVIDIA Confidential Computing (H100, Blackwell) -### Launch certbot - -Then run the certbot in the `build/` and you will see the following log: -```text -$ RUST_LOG=info,certbot=debug ./certbot renew -c certbot.toml -2024-10-25T07:41:00.682990Z INFO certbot::bot: creating new ACME account -2024-10-25T07:41:00.869246Z INFO certbot::bot: created new ACME account: https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853 -2024-10-25T07:41:00.869270Z INFO certbot::bot: setting CAA records -2024-10-25T07:41:00.869276Z DEBUG certbot::acme_client: setting guard CAA records for app.kvin.wang -2024-10-25T07:41:01.740767Z DEBUG certbot::acme_client: removing existing CAA record app.kvin.wang 0 issuewild "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168578683" -2024-10-25T07:41:01.991298Z DEBUG certbot::acme_client: removing existing CAA record app.kvin.wang 0 issue "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168578683" -2024-10-25T07:41:02.216751Z DEBUG certbot::acme_client: setting CAA records for app.kvin.wang, 0 issue "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853" -2024-10-25T07:41:02.424217Z DEBUG certbot::acme_client: setting CAA records for app.kvin.wang, 0 issuewild "letsencrypt.org;validationmethods=dns-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853" -2024-10-25T07:41:02.663824Z DEBUG certbot::acme_client: removing guard CAA records for app.kvin.wang -2024-10-25T07:41:03.095564Z DEBUG certbot::acme_client: generating new cert key pair -2024-10-25T07:41:03.095678Z DEBUG certbot::acme_client: requesting new certificates for *.app.kvin.wang -2024-10-25T07:41:03.095699Z DEBUG certbot::acme_client: creating new order -2024-10-25T07:41:03.250382Z DEBUG certbot::acme_client: order is pending, waiting for authorization -2024-10-25T07:41:03.283600Z DEBUG certbot::acme_client: creating dns record for app.kvin.wang -2024-10-25T07:41:04.027882Z DEBUG certbot::acme_client: challenge not found, waiting 500ms tries=2 domain="_acme-challenge.app.kvin.wang" -2024-10-25T07:41:04.600711Z DEBUG certbot::acme_client: challenge not found, waiting 1s tries=3 domain="_acme-challenge.app.kvin.wang" -2024-10-25T07:41:05.642300Z DEBUG certbot::acme_client: challenge not found, waiting 2s tries=4 domain="_acme-challenge.app.kvin.wang" -2024-10-25T07:41:07.715947Z DEBUG certbot::acme_client: challenge not found, waiting 4s tries=5 domain="_acme-challenge.app.kvin.wang" -2024-10-25T07:41:11.724831Z DEBUG certbot::acme_client: challenge not found, waiting 8s tries=6 domain="_acme-challenge.app.kvin.wang" -2024-10-25T07:41:19.815990Z DEBUG certbot::acme_client: challenge not found, waiting 16s tries=7 domain="_acme-challenge.app.kvin.wang" -2024-10-25T07:41:35.852790Z DEBUG certbot::acme_client: setting challenge ready for https://acme-staging-v02.api.letsencrypt.org/acme/chall-v3/14584884443/mQ-I2A -2024-10-25T07:41:35.934425Z DEBUG certbot::acme_client: challenges are ready, waiting for order to be ready -2024-10-25T07:41:37.972434Z DEBUG certbot::acme_client: order is ready, uploading csr -2024-10-25T07:41:38.052901Z DEBUG certbot::acme_client: order is processing, waiting for challenge to be accepted -2024-10-25T07:41:40.088190Z DEBUG certbot::acme_client: order is valid, getting certificate -2024-10-25T07:41:40.125988Z DEBUG certbot::acme_client: removing dns record 6ab5724e8fa7e3e8f14e93333a98866a -2024-10-25T07:41:40.377379Z DEBUG certbot::acme_client: stored new cert in /home/kvin/codes/meta-dstack/dstack/build/run/certbot/backup/2024-10-25T07:41:40.377174477Z -2024-10-25T07:41:40.377472Z INFO certbot::bot: checking if certificate needs to be renewed -2024-10-25T07:41:40.377719Z DEBUG certbot::acme_client: will expire in Duration { seconds: 7772486, nanoseconds: 622281542 } -2024-10-25T07:41:40.377752Z INFO certbot::bot: certificate /home/kvin/codes/meta-dstack/dstack/build/run/certbot/live/cert.pem is up to date -``` +
-Where the command did are: +
+How do users verify my deployment? -- Registered to letsencrypt and got a new account `https://acme-staging-v02.api.letsencrypt.org/acme/acct/168601853` -- Auto set CAA records for the domain on cloudflare, you can open the CF dashboard to see the record: +Your app exposes attestation quotes via the SDK. Users verify these quotes using [dstack-verifier](https://github.com/Dstack-TEE/dstack/tree/next/dstack/verifier), [dcap-qvl](https://github.com/Phala-Network/dcap-qvl), or the [Trust Center](https://trust.phala.com). See the [verification guide](./docs/verification.md) for details. - ![certbot-caa](./docs/assets/certbot-caa.png) +
-- Auto requested a new certificate from Let's Encrypt. Automatically renews the certificate to maintain its validity +## Trusted by -### Launch Tproxy +- [OpenRouter](https://openrouter.ai/provider/phala) - Confidential AI inference providers powered by dstack +- [NEAR AI](https://x.com/ilblackdragon/status/1962920246148268235) - Private AI infrastructure powered by dstack -Execute tproxy with `sudo ./tproxy`, then access the web portal to check the Tproxy-CVM managed Let's Encrypt account. The account's private key remains securely sealed within the TEE. +dstack is a Linux Foundation [Confidential Computing Consortium](https://confidentialcomputing.io/2025/10/02/welcoming-phala-to-the-confidential-computing-consortium/) open source project. -![tproxy-accountid](./docs/assets/tproxy-accountid.png) - -## Certificate transparency log monitor - -To enhance security, we've limited TLS certificate issuance to Tproxy via CAA records. However, since these records can be modified through Cloudflare's domain management, we need to implement global CA certificate monitoring to maintain security oversight. - -`ct_monitor` tracks Certificate Transparency logs via [https://crt.sh](https://crt.sh/?q=app.kvin.wang), comparing their public key with the ones got from Tproxy RPC. It immediately alerts when detecting unauthorized certificates not issued through Tproxy: - -```text -$ ./ct_monitor -t https://localhost:9010/prpc -d app.kvin.wang -2024-10-25T08:12:11.366463Z INFO ct_monitor: monitoring app.kvin.wang... -2024-10-25T08:12:11.366488Z INFO ct_monitor: fetching known public keys from https://localhost:9010/prpc -2024-10-25T08:12:11.566222Z INFO ct_monitor: got 2 known public keys -2024-10-25T08:12:13.142122Z INFO ct_monitor: ✅ checked log id=14705660685 -2024-10-25T08:12:13.802573Z INFO ct_monitor: ✅ checked log id=14705656674 -2024-10-25T08:12:14.494944Z ERROR ct_monitor: ❌ error in CTLog { id: 14666084839, issuer_ca_id: 295815, issuer_name: "C=US, O=Let's Encrypt, CN=R11", common_name: "kvin.wang", name_value: "*.app.kvin.wang", not_before: "2024-09-24T02:23:15", not_after: "2024-12-23T02:23:14", serial_number: "03ae796f56a933c8ff7e32c7c0d662a253d4", result_count: 1, entry_timestamp: "2024-09-24T03:21:45.825" } -2024-10-25T08:12:14.494998Z ERROR ct_monitor: error: certificate has issued to unknown pubkey: 30820122300d06092a864886f70d01010105000382010f003082010a02820101009de65c767caf117880626d1acc1ee78f3c6a992e3fe458f34066f92812ac550190a67e49ebf4f537003c393c000a8ec3e114da088c0cb02ffd0881fd39a2b32cc60d2e9989f0efab3345bee418262e0179d307d8d361fd0837f85d17eab92ec6f4126247e614aa01f4efcc05bc6303a8be68230f04326c9e85406fc4d234e9ce92089253b11d002cdf325582df45d5da42981cd546cbd2e9e49f0fa6636e747a345aaf8cefa02556aa258e1f7f90906be8fe51567ac9626f35bc46837e4f3203387fee59c71cea400000007c24e7537debc1941b36ff1612990233e4c219632e35858b1771f17a71944adf6c657dd7303583e3aeed199bd36a3152f49980f4f30203010001 -``` +## Community -# Troubleshooting +[Telegram](https://t.me/+UO4bS4jflr45YmUx) · [GitHub Discussions](https://github.com/Dstack-TEE/dstack/discussions) · [Examples](https://github.com/Dstack-TEE/dstack-examples) -### Error from teepod: qemu-system-x86_64: -device vhost-vsock-pci,guest-cid=: vhost-vsock: unable to set guest cid: Address already in use +For enterprise support and licensing, [book a call](https://cal.com/team/phala/founders) or email us at support@phala.network. -`teepod` may throw this error when creating a new VM if the [Unix Socket CID](https://man7.org/linux/man-pages/man7/vsock.7.html) is occupied. To solve the problem, first, you should list the occupied CID: +[![Repobeats](https://repobeats.axiom.co/api/embed/0a001cc3c1f387fae08172a9e116b0ec367b8971.svg)](https://github.com/Dstack-TEE/dstack/pulse) -```bash -ps aux | grep 'guest-cid=' -``` +## Cite -Then choose a new range of the CID not conflicting with the CID in use. You can change `build/teepod.toml` file and restart `teepod`. This error should disappear. For example, you may find 33000-34000 free to use: +If you use dstack in your research, please cite: -```toml -[cvm] -cid_start = 33000 -cid_pool_size = 1000 +```bibtex +@article{zhou2025dstack, + title={Dstack: A Zero Trust Framework for Confidential Containers}, + author={Zhou, Shunfan and Wang, Kevin and Yin, Hang}, + journal={arXiv preprint arXiv:2509.11555}, + year={2025} +} ``` -When building the dstack from scratch, you should change the CID configs in `build-config.sh` instead, because `teepod.toml` file is generated by `build.sh`. Its content is derived from `build-config.sh`. - -You may encounter this problem when upgrading from an older version of dstack, because CID was introduced in `build-config.sh` in later versions. In such case, please follow the docs to add the missing entries in `build-config.sh` and rebuild dstack. - -# Contributors - -Dstack is proudly built by open source and Pi-rateship contributors: - -- Phala Network: [Kevin Wang](https://github.com/kvinwang), [Shelven Zhou](https://github.com/shelvenzhou), [Leechael](https://github.com/leechael) -- Teleport: [Andrew Miller](https://github.com/amiller), [Sxy Sun](https://github.com/sxysun) -- Flashbots: [Tina](https://github.com/CarboClanC), [Mateusz](https://github.com/Ruteri), [Dmarz](https://github.com/dmarzzz), [Moe](https://github.com/MoeMahhouk) -- Ithaca: [Georgios](https://github.com/gakonst) -- Fabric: [@gaoist](https://x.com/gaoist) -- And many more... - -The inspiration for this work stems from [Andrew Miller](https://github.com/amiller)’s pioneering concept of a [Docker-based P2P TEE SDK](https://collective.flashbots.net/t/dstack-speedrunning-a-p2p-confidential-vm/3876). - -This project cannot be built without standing on the shoulders of giants: - -- [konvera/meta-confidential-compute](https://github.com/konvera/meta-confidential-compute) - -Special acknowledgment to [Flashbots](https://github.com/flashbots) for building a community around TEE. The TEE Hacker House initiative, organized by [Flashbots](https://github.com/flashbots) and led by [Tina](https://github.com/CarboClanC), has brought together TEE builders to develop tools for TEE-Web3 integration. This collaborative journey has generated invaluable insights for advancing secure, confidential environments within Web3. - -Together, we’re shaping the future of TEE in Web3, paving the way for more secure and developer-accessible confidential computing! - -For a full list of the direct contributors to this repo, see [Contributors](https://github.com/Dstack-TEE/dstack/contributors) on GitHub. - - -# License +## Media Kit -Copyright 2024 Phala Network and Contributors. +Logo and branding assets: [dstack-logo-kit](./docs/assets/dstack-logo-kit/) -Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at +## License -[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) +The dstack-owned source, SDKs, documentation, tools, guest OS backend, and +image-assembly code are Apache-2.0. Embedded and third-party components retain +their own license declarations and notices. See file-level SPDX declarations +and [`REUSE.toml`](./REUSE.toml) for the exact scope. diff --git a/REUSE.toml b/REUSE.toml new file mode 100644 index 0000000000..6e7e20c645 --- /dev/null +++ b/REUSE.toml @@ -0,0 +1,270 @@ +version = 1 +SPDX-PackageName = "dstack" +SPDX-PackageSupplier = "Phala Network " +SPDX-PackageDownloadLocation = "https://github.com/Dstack-TEE/dstack" + +# Non source files + +[[annotations]] +path = [ + "*.md", + ".agent/**/*.md", + ".claude/**/*.md", + "docs/**/*.md", + "dstack/**/*.md", + "examples/**/*.md", + "formal/**/*.md", + "sdk/**/*.md", + "tools/**/*.md", + "os/README.md", + "os/common/**/*.md", + "os/image/**/*.md", +] +SPDX-FileCopyrightText = "Copyright (c) 2024-2025 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = "**/requirements.txt" +SPDX-FileCopyrightText = "Copyright (c) 2024-2025 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = [ + "**/package.json", + "**/openapi.json", + "**/tsconfig.json", + "**/tsconfig.node.json", + "**/tsconfig.browser.json", + "dstack/kms/auth-eth/.oxlintrc.json", + "dstack/kms/auth-eth/slither.config.json", + "**/package-lock.json", + "dstack/kms/auth-eth/.openzeppelin/unknown-2035.json", + "tools/sca/examples/heartbeat/config.json", + "tools/sca/examples/hello-c/config.json", + "tools/sca/examples/heartbeat/rootfs/etc/heartbeat/interval", + "sdk/simulator/*.json", + "sdk/fixtures/sealed-env/*.json", + "sdk/tests/compose-hash-fixture.json", + "sdk/go/dstack/go.sum", + "sdk/go/ratls/go.sum", + "dstack/kms/dstack-app/builder/shared/builder-pinned-packages.txt", + "dstack/kms/dstack-app/builder/shared/pinned-packages.txt", + "dstack/gateway/dstack-app/builder/shared/builder-pinned-packages.txt", + "dstack/gateway/dstack-app/builder/shared/pinned-packages.txt", +] +SPDX-FileCopyrightText = "Copyright (c) 2024-2025 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = [ + "dstack/gateway/templates/wg.conf", + "dstack/guest-agent/templates/metrics.tpl", +] +SPDX-FileCopyrightText = "Copyright (c) 2024-2025 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = [ + ".cursorrules", + ".mailmap", + ".gitignore", + "dstack/**/.gitignore", + "dstack/**/.npmignore", + "docs/**/.gitignore", + "examples/**/.gitignore", + "formal/.gitignore", + "formal/lake-manifest.json", + "formal/lean-toolchain", + "os/common/**/.gitignore", + "os/image/**/.gitignore", + "sdk/**/.gitignore", + "sdk/**/.npmignore", + "tools/**/.gitignore", +] +SPDX-FileCopyrightText = "Copyright (c) 2024-2025 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = [ + "os/common/nvidia/**", + "os/common/rootfs/**", + "os/common/scripts/**", +] +SPDX-FileCopyrightText = "Copyright (c) 2024-2025 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +[[annotations]] +path = [ + "docs/security/dstack-audit.pdf", + "dstack_Technical_Charter_Final_10-17-2025.pdf", + "sdk/simulator/quote.hex", + "sdk/simulator/attestation.bin", + "sdk/go/ratls/tdx-lite-v0-get-tls-key.pem", + "sdk/go/ratls/tdx-lite-v1-issue-cert.pem", + "dstack/ra-tls/assets/tdx_quote", + "dstack/cc-eventlog/samples/ccel.bin", + "dstack/cc-eventlog/samples/tpm_eventlog.bin", + "dstack/tpm-attest/tests/tpm_quote_sample.bin", + "dstack/tpm-qvl/certs/gcp-root-ca.pem", + "dstack/dstack-attest/tests/nitro_attestation.bin", + "dstack/dstack-attest/tests/nitro_attestation_dbg.bin", + "dstack/dstack-attest/tests/sev_snp_attestation.bin", + "dstack/dstack-attest/tests/sev_snp_ask.pem", + "dstack/dstack-attest/tests/sev_snp_vcek.pem", + "dstack/sev-snp-qvl/testdata/amd-milan.crl", + "dstack/nsm-attest/tests/nitro_attestation.bin", + "dstack/nsm-qvl/tests/nitro_attestation.bin", + "dstack/nsm-qvl/certs/AWS_NitroEnclaves_Root-G1.pem", + "dstack/tpm-qvl/certs/AWS_NitroEnclaves_Root-G1.pem", +] +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +# Backend-neutral OS contract + +[[annotations]] +path = "os/spec/*.json" +SPDX-FileCopyrightText = "Copyright (c) 2026 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +# dstack-owned OS backend + +[[annotations]] +path = "os/yocto/**" +SPDX-FileCopyrightText = "Copyright (c) Hashforest Technology LLC" +SPDX-License-Identifier = "Apache-2.0" + +# Experimental Debian/mkosi guest OS backend. Supplies the copyright for the +# formats that cannot carry a header; everything that can now does. It is +# deliberately not precedence = "override", so a patch backported from an +# upstream project keeps that project's license instead of being relabelled +# Apache-2.0. +[[annotations]] +path = "os/mkosi/**" +SPDX-FileCopyrightText = "© 2026 Phala Network " +SPDX-License-Identifier = "Apache-2.0" + +# Legacy cross-component tools kept outside the Yocto backend. + +[[annotations]] +path = "tools/vm-runner/**" +SPDX-FileCopyrightText = "Copyright (c) Hashforest Technology LLC" +SPDX-License-Identifier = "Apache-2.0" + +# Artworks + + +[[annotations]] +path = [ + "docs/assets/**", + "docs/security-guide/assets/**", + "dstack-logo.svg", +] +SPDX-FileCopyrightText = "Copyright (c) 2024-2025 The Project Contributors" +SPDX-License-Identifier = "Apache-2.0" + +# Scripts with SPDX-like content (false positive prevention) + +[[annotations]] +path = "tools/add-spdx-attribution.py" +SPDX-FileCopyrightText = "© 2025 Phala Network " +SPDX-License-Identifier = "Apache-2.0" +precedence = "override" + +# Vendor code + +[[annotations]] +path = "dstack/kms/auth-eth/lib/openzeppelin-contracts-upgradeable/**" +SPDX-FileCopyrightText = "Copyright (c) 2016-2025 Zeppelin Group Ltd" +SPDX-License-Identifier = "MIT" +precedence = "override" + +[[annotations]] +path = "dstack/kms/auth-eth/lib/openzeppelin-foundry-upgrades/**" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "MIT" +precedence = "override" + +[[annotations]] +path = "dstack/kms/auth-eth/lib/forge-std/**" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "Apache-2.0" +precedence = "override" + +# ktls 6.0.2 plus rustls/ktls#70; see dstack/vendor/README.md. +[[annotations]] +path = "dstack/vendor/ktls/**" +SPDX-FileCopyrightText = "Copyright (c) 2022 Amos Wenger " +SPDX-License-Identifier = "MIT OR Apache-2.0" +precedence = "override" + +# Generated files + +[[annotations]] +path = "**/*.lock" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "**/*.lockb" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "**/*.snap" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "**/src/generated.rs" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "**/src/generated/*" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "dstack/gateway/assets/*" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "dstack/guest-api/src/generated/*" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "dstack/dstack-util/tests/fixtures/*" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "dstack/verifier/fixtures/*" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "dstack/verifier/builder/shared/*.txt" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "dstack/guest-agent/fixtures/*" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = [ + "dstack/gateway/test-run/e2e/certs/*", + "dstack/gateway/test-run/e2e/configs/*", + "dstack/gateway/test-run/e2e/pebble-config.json", +] +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" + +[[annotations]] +path = "dstack/crates/qemu-acpi/fixtures/*.bin" +SPDX-FileCopyrightText = "NONE" +SPDX-License-Identifier = "CC0-1.0" diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000..e0d9537358 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,28 @@ +# Security + +Use this file for vulnerability reports. For the security model, production guidance, audit, and already-answered public findings, start with [Security Documentation](./docs/security/). + +## Report a vulnerability + +If you believe you found a vulnerability, please use [GitHub's private security reporting features](https://docs.github.com/en/code-security/how-tos/report-and-fix-vulnerabilities/report-privately) for this repository. If GitHub private reporting is unavailable, contact security@phala.network. + +Do not open public GitHub issues for exploitable vulnerabilities or details that could help exploit production deployments. + +Use private reporting for issues that could expose secrets, bypass attestation or authorization, compromise KMS keys, weaken workload isolation, or enable unauthorized code or configuration changes in production deployments. + +## Maintainer response + +dstack is a non-profit open-source project. Maintainers will make a best-effort +attempt to acknowledge, assess, and address valid reports, and coordinate +disclosure where appropriate. We do not offer a bug bounty or other monetary +reward, and cannot commit to a response or remediation timeline. + +## Public security questions + +Use public issues only for questions about documented behavior, documentation gaps, already-public findings, or hardening ideas that do not include an exploit path. + +Before opening a public security question, check [Public Security Reports](./docs/security/public-security-reports.md). It records public report status and related hardening or roadmap work. + +## Production trust boundary + +Development settings are not production-safe merely because they are present in the codebase. Production deployments must rely on measured configuration, expected TEE measurements, authorization policy, and attestation verification. The [Security Model](./docs/security/security-model.md#development-modes-are-auditable-not-production-safe) is the source of truth for what dstack treats as a production guarantee. diff --git a/basefiles/app-compose.service b/basefiles/app-compose.service deleted file mode 100644 index 5a14bb2f9a..0000000000 --- a/basefiles/app-compose.service +++ /dev/null @@ -1,17 +0,0 @@ -[Unit] -Description=App Compose Service -Wants=docker.service -After=docker.service tboot.service - -[Service] -Type=oneshot -RemainAfterExit=true -EnvironmentFile=-/tapp/env -WorkingDirectory=/tapp -ExecStart=/bin/app-compose.sh -ExecStop=/bin/docker compose stop -StandardOutput=journal+console -StandardError=journal+console - -[Install] -WantedBy=multi-user.target diff --git a/basefiles/app-compose.sh b/basefiles/app-compose.sh deleted file mode 100644 index 1f6c394792..0000000000 --- a/basefiles/app-compose.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh -tdxctl notify-host -e "boot.progress" -d "starting containers" || true - -docker compose up --remove-orphans -d || true -chmod +x /usr/bin/containerd-shim-runc-v2 -systemctl restart docker - -if ! docker compose up --remove-orphans -d; then - tdxctl notify-host -e "boot.error" -d "failed to start containers" - exit 1 -fi -tdxctl notify-host -e "boot.progress" -d "done" || true diff --git a/basefiles/journald.conf b/basefiles/journald.conf deleted file mode 100644 index a0c19b17e6..0000000000 --- a/basefiles/journald.conf +++ /dev/null @@ -1,8 +0,0 @@ -[Journal] -Storage=persistent -SystemMaxUse=1G -SystemKeepFree=2G -SystemMaxFileSize=100M -SystemMaxFiles=10 -RuntimeMaxUse=0 -ReadKMsg=yes diff --git a/basefiles/llmnr.conf b/basefiles/llmnr.conf deleted file mode 100644 index 4b0ccf845d..0000000000 --- a/basefiles/llmnr.conf +++ /dev/null @@ -1,2 +0,0 @@ -[Resolve] -LLMNR=no \ No newline at end of file diff --git a/basefiles/tappd.init b/basefiles/tappd.init deleted file mode 100644 index c27ee3cbb1..0000000000 --- a/basefiles/tappd.init +++ /dev/null @@ -1,87 +0,0 @@ -#!/bin/sh -# -# SPDX-License-Identifier: GPL-2.0-only -# - -### BEGIN INIT INFO -# Provides: tappd -# Required-Start: $network $local_fs -# Required-Stop: $network $local_fs -# Default-Start: 2 3 4 5 -# Default-Stop: 0 1 6 -# Short-Description: Start tappd daemon -# Description: Start the tappd daemon -### END INIT INFO - -# Source function library. -. /etc/init.d/functions - -prog="tappd" -exec="/usr/bin/$prog" -pidfile="/var/run/$prog.pid" -lockfile="/var/lock/subsys/$prog" -logfile="/var/log/$prog" - -[ -e /etc/default/$prog ] && . /etc/default/$prog - -start() { - [ -x $exec ] || exit 5 - - printf "Starting $prog:\t" - if ! [ -f $pidfile ]; then - $exec $DAEMON_OPTS & - echo $! > $pidfile - touch $lockfile - success - echo - else - failure - echo - printf "$pidfile still exists...\n" - exit 7 - fi -} - -stop() { - echo -n "Stopping $prog: " - killproc $prog - retval=$? - echo - [ $retval -eq 0 ] && rm -f $lockfile - return $retval -} - -restart() { - stop - start -} - -rh_status() { - status $prog -} - -rh_status_q() { - rh_status >/dev/null 2>&1 -} - -case "$1" in - start) - rh_status_q && exit 0 - $1 - ;; - stop) - rh_status_q || exit 0 - $1 - ;; - restart) - $1 - ;; - status) - rh_status - ;; - *) - echo "Usage: $0 {start|stop|status|restart}" - exit 2 -esac - -exit $? diff --git a/basefiles/tappd.service b/basefiles/tappd.service deleted file mode 100644 index 1027992e5a..0000000000 --- a/basefiles/tappd.service +++ /dev/null @@ -1,16 +0,0 @@ -[Unit] -Description=Tappd Service -After=network.target tboot.service - -[Service] -OOMScoreAdjust=-1000 -ExecStartPre=-/bin/rm -f /var/run/tappd.sock -ExecStart=/bin/tappd --watchdog -Restart=always -User=root -Group=root -Type=notify -WatchdogSec=30s - -[Install] -WantedBy=multi-user.target diff --git a/basefiles/tboot.service b/basefiles/tboot.service deleted file mode 100644 index a3d67e1d3b..0000000000 --- a/basefiles/tboot.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -Description=Guest Boot Service -After=network.target -Before=app-compose.service tappd.service - -[Service] -Type=oneshot -ExecStart=/bin/tboot.sh -RemainAfterExit=yes -StandardOutput=journal+console -StandardError=journal+console - -[Install] -WantedBy=multi-user.target diff --git a/basefiles/tboot.sh b/basefiles/tboot.sh deleted file mode 100755 index 857e31266a..0000000000 --- a/basefiles/tboot.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh -# Temporarily disable container auto-start -# This will be re-enabled later by app-compose.sh -chmod -x /usr/bin/containerd-shim-runc-v2 - -tdxctl tboot diff --git a/basefiles/tdx-attest.conf b/basefiles/tdx-attest.conf deleted file mode 100644 index d7c6361ae4..0000000000 --- a/basefiles/tdx-attest.conf +++ /dev/null @@ -1 +0,0 @@ -port=4050 \ No newline at end of file diff --git a/basefiles/wg-checker.service b/basefiles/wg-checker.service deleted file mode 100644 index eac7b60758..0000000000 --- a/basefiles/wg-checker.service +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=WireGuard Endpoint Checker Service -After=network-online.target tboot.service -Wants=network-online.target - -[Service] -Type=simple -ExecStart=/bin/wg-checker.sh -Restart=always -RestartSec=10 -StandardOutput=journal+console -StandardError=journal+console - -[Install] -WantedBy=multi-user.target diff --git a/basefiles/wg-checker.sh b/basefiles/wg-checker.sh deleted file mode 100644 index ab72ec7892..0000000000 --- a/basefiles/wg-checker.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/sh - -get_conf_endpoint() { - grep "Endpoint" /etc/wireguard/wg0.conf | awk "{print \$3}" -} - -get_current_endpoint() { - wg show wg0 endpoints | awk "{print \$2}" -} - -check_endpoint() { - CONF_ENDPOINT=$(get_conf_endpoint) - CURRENT_ENDPOINT=$(get_current_endpoint) - - if [ "$CURRENT_ENDPOINT" != "$CONF_ENDPOINT" ]; then - echo "Wg endpoint changed from $CONF_ENDPOINT to $CURRENT_ENDPOINT." - wg syncconf wg0 <(wg-quick strip wg0) - fi -} - -while true; do - if [ -f /etc/wireguard/wg0.conf ]; then - check_endpoint - fi - sleep 10 -done diff --git a/cargo-check-all.sh b/cargo-check-all.sh deleted file mode 100755 index caf0e2ec49..0000000000 --- a/cargo-check-all.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh -find . -name Cargo.toml -exec dirname {} \; | while read dir; do - echo "Checking $dir..." - (cd "$dir" && cargo check) -done diff --git a/cc-eventlog/Cargo.toml b/cc-eventlog/Cargo.toml deleted file mode 100644 index f8269275f0..0000000000 --- a/cc-eventlog/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "cc-eventlog" -version.workspace = true -authors.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -anyhow.workspace = true -fs-err.workspace = true -hex.workspace = true -scale.workspace = true -serde.workspace = true -serde-human-bytes.workspace = true -serde_json.workspace = true -sha2.workspace = true - -[dev-dependencies] -insta.workspace = true diff --git a/cc-eventlog/src/codecs.rs b/cc-eventlog/src/codecs.rs deleted file mode 100644 index de5438ec55..0000000000 --- a/cc-eventlog/src/codecs.rs +++ /dev/null @@ -1,72 +0,0 @@ -use std::ops::Deref; - -use scale::{Decode, Input}; - -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct VecOf { - len: I, - inner: Vec, -} - -impl Default for VecOf { - fn default() -> Self { - Self { - len: I::default(), - inner: Vec::default(), - } - } -} - -impl + Copy, T: Decode> Decode for VecOf { - fn decode(input: &mut In) -> Result { - let decoded_len = I::decode(input)?; - let len = decoded_len.into() as usize; - let mut inner = Vec::with_capacity(len); - for _ in 0..len { - inner.push(T::decode(input)?); - } - Ok(Self { - len: decoded_len, - inner, - }) - } -} - -impl VecOf { - pub fn into_inner(self) -> Vec { - self.inner - } - - pub fn length(&self) -> I - where - I: Clone, - { - self.len.clone() - } -} - -impl Deref for VecOf { - type Target = Vec; - - fn deref(&self) -> &Self::Target { - &self.inner - } -} - -impl From<(I, Vec)> for VecOf { - fn from((len, vec): (I, Vec)) -> Self { - Self { len, inner: vec } - } -} - -impl AsRef<[T]> for VecOf { - fn as_ref(&self) -> &[T] { - &self.inner - } -} - -impl From> for Vec { - fn from(value: VecOf) -> Self { - value.inner - } -} diff --git a/cc-eventlog/src/lib.rs b/cc-eventlog/src/lib.rs deleted file mode 100644 index 8fc189695d..0000000000 --- a/cc-eventlog/src/lib.rs +++ /dev/null @@ -1,297 +0,0 @@ -use crate::codecs::VecOf; -use anyhow::{Context, Result}; -use scale::Decode; -use serde::{Deserialize, Serialize}; -use tcg::{TcgDigest, TcgEfiSpecIdEvent}; - -mod codecs; -mod tcg; - -/// The path to the userspace TDX event log file. -pub const RUNTIME_EVENT_LOG_FILE: &str = "/run/log/tdx_mr3/tdx_events.log"; -/// The path to boottime ccel file. -const CCEL_FILE: &str = "/sys/firmware/acpi/tables/data/CCEL"; - -/// This is the common struct for tcg event logs to be delivered in different formats. -/// Currently TCG supports several event log formats defined in TCG_PCClient Spec, -/// Canonical Eventlog Spec, etc. -/// This struct provides the functionality to convey event logs in different format -/// according to request. -#[derive(Clone, scale::Decode)] -pub struct TcgEventLog { - /// IMR index, starts from 1 - pub imr_index: u32, - /// Event type - pub event_type: u32, - /// List of digests - pub digests: VecOf, - /// Raw event data - pub event: VecOf, -} - -/// This is the TDX event log format that is used to store the event log in the TDX guest. -/// It is a simplified version of the TCG event log format, containing only a single digest -/// and the raw event data. The IMR index is zero-based, unlike the TCG event log format -/// which is one-based. -/// -/// As for RTMR3, the digest extended is calculated as `sha384(event_type.to_ne_bytes() || b":" || event || b":" || event_payload)`. -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct TdxEventLog { - /// IMR index, starts from 0 - pub imr: u32, - /// Event type - pub event_type: u32, - /// Digest - #[serde(with = "serde_human_bytes")] - pub digest: [u8; 48], - /// Event name - pub event: String, - /// Event payload - #[serde(with = "serde_human_bytes")] - pub event_payload: Vec, -} - -fn event_digest(ty: u32, event: &str, payload: &[u8]) -> [u8; 48] { - use sha2::Digest; - let mut hasher = sha2::Sha384::new(); - hasher.update(ty.to_ne_bytes()); - hasher.update(b":"); - hasher.update(event.as_bytes()); - hasher.update(b":"); - hasher.update(payload); - hasher.finalize().into() -} - -impl TdxEventLog { - pub fn new(imr: u32, event_type: u32, event: String, event_payload: Vec) -> Self { - let digest = event_digest(event_type, &event, &event_payload); - Self { - imr, - event_type, - digest, - event, - event_payload, - } - } - - pub fn new_str(imr: u32, event_type: u32, event: &str, event_payload: &str) -> Self { - Self::new( - imr, - event_type, - event.to_string(), - event_payload.as_bytes().to_vec(), - ) - } - - pub fn validate(&self) -> Result<()> { - if self.imr != 3 { - // TODO: validate other imrs - return Ok(()); - } - let digest = event_digest(self.event_type, &self.event, &self.event_payload); - if digest != self.digest { - return Err(anyhow::anyhow!("invalid digest")); - } - Ok(()) - } -} - -impl TryFrom for TdxEventLog { - type Error = anyhow::Error; - - fn try_from(value: TcgEventLog) -> Result { - if value.digests.len() != 1 { - return Err(anyhow::anyhow!( - "expected 1 digest, got {}", - value.digests.len() - )); - } - let digest = value - .digests - .into_inner() - .into_iter() - .next() - .context("digest not found")? - .hash - .try_into() - .ok() - .context("invalid digest size")?; - Ok(TdxEventLog { - imr: value - .imr_index - .checked_sub(1) - .context("invalid imr index")?, - event_type: value.event_type, - digest, - event: Default::default(), - event_payload: value.event.into(), - }) - } -} - -impl core::fmt::Debug for TcgEventLog { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("TcgEventLog") - .field("imr_index", &self.imr_index) - .field("event_type", &self.event_type) - .field( - "digests", - &self - .digests - .iter() - .map(|d| hex::encode(&d.hash)) - .collect::>(), - ) - .field("event", &hex::encode(&self.event)) - .finish() - } -} - -const fn alg_id_to_digest_size(alg_id: u16) -> Option { - use tcg::*; - match alg_id { - TPM_ALG_SHA1 => Some(20), - TPM_ALG_SHA256 => Some(32), - TPM_ALG_SHA384 => Some(48), - TPM_ALG_SHA512 => Some(64), - _ => None, - } -} - -#[derive(Clone, Debug)] -pub struct EventLogs { - pub spec_id_header_event: TcgEfiSpecIdEvent, - pub event_logs: Vec, -} - -impl scale::Decode for TcgDigest { - fn decode(input: &mut I) -> Result { - let algo_id = u16::decode(input)?; - let digest_size = - alg_id_to_digest_size(algo_id).ok_or(scale::Error::from("Unsupported algorithm ID"))?; - let mut digest_data = vec![0; digest_size as usize]; - input - .read(&mut digest_data) - .map_err(|_| scale::Error::from("failed to read digest_data"))?; - Ok(TcgDigest { - algo_id, - hash: digest_data, - }) - } -} - -impl EventLogs { - pub fn decode(input: &mut &[u8]) -> Result { - let (_spec_id_header, spec_id_header_event) = - parse_spec_id_event_log(input).context("Failed to parse spec id event")?; - let mut event_logs = vec![]; - loop { - // A tmp head_buffer is used to peek the imr and event type - let head_buffer = &mut &input[..]; - let imr = u32::decode(head_buffer).context("failed to decode imr")?; - if imr == 0xFFFFFFFF { - break; - } - let event_log = TcgEventLog::decode(input).context("Failed to parse event log")?; - event_logs.push(event_log); - } - Ok(EventLogs { - spec_id_header_event, - event_logs, - }) - } - - pub fn decode_from_ccel_file() -> Result { - let data = fs_err::read(CCEL_FILE).context("Failed to read CCEL")?; - Self::decode(&mut data.as_slice()) - } - - pub fn into_tdx_event_logs(self) -> Result> { - self.event_logs - .into_iter() - .map(TdxEventLog::try_from) - .collect() - } - - pub fn to_tdx_event_logs(&self) -> Result> { - self.event_logs - .iter() - .cloned() - .map(TdxEventLog::try_from) - .collect() - } -} - -fn parse_spec_id_event_log( - input: &mut I, -) -> Result<(TcgEventLog, TcgEfiSpecIdEvent)> { - #[derive(Decode)] - struct Header { - imr_index: u32, - header_event_type: u32, - digest_hash: [u8; 20], - header_event: VecOf, - } - - let decoded_header = Header::decode(input).context("failed to decode log_item")?; - // Parse EFI Spec Id Event structure - let input = &mut decoded_header.header_event.as_slice(); - let spec_id_event = - TcgEfiSpecIdEvent::decode(input).context("failed to decode TcgEfiSpecIdEvent")?; - - let digests = vec![TcgDigest { - algo_id: tcg::TPM_ALG_ERROR, - hash: decoded_header.digest_hash.to_vec(), - }]; - let spec_id_header = TcgEventLog { - imr_index: decoded_header.imr_index, - event_type: decoded_header.header_event_type, - digests: (digests.len() as u32, digests).into(), - event: decoded_header.header_event, - }; - Ok((spec_id_header, spec_id_event)) -} - -fn read_runtime_event_logs() -> Result> { - let data = match fs_err::read_to_string(RUNTIME_EVENT_LOG_FILE) { - Ok(data) => data, - Err(e) => { - if e.kind() == std::io::ErrorKind::NotFound { - return Ok(vec![]); - } - return Err(e).context("Failed to read user event log"); - } - }; - let mut event_logs = vec![]; - for line in data.lines() { - if line.trim().is_empty() { - continue; - } - let event_log = - serde_json::from_str::(line).context("Failed to decode user event log")?; - event_logs.push(event_log); - } - Ok(event_logs) -} - -/// Read both boottime and runtime event logs. -pub fn read_event_logs() -> Result> { - let mut event_logs = EventLogs::decode_from_ccel_file()?.to_tdx_event_logs()?; - event_logs.extend(read_runtime_event_logs()?); - Ok(event_logs) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parse_ccel() { - let boot_time_data = include_bytes!("../samples/ccel.bin"); - let event_logs = EventLogs::decode(&mut boot_time_data.as_slice()).unwrap(); - insta::assert_debug_snapshot!(&event_logs.event_logs); - let tdx_event_logs = event_logs.to_tdx_event_logs().unwrap(); - let json = serde_json::to_string_pretty(&tdx_event_logs).unwrap(); - insta::assert_snapshot!(json); - } -} diff --git a/cc-eventlog/src/tcg.rs b/cc-eventlog/src/tcg.rs deleted file mode 100644 index c18714a51d..0000000000 --- a/cc-eventlog/src/tcg.rs +++ /dev/null @@ -1,203 +0,0 @@ -#![allow(dead_code)] - -use crate::codecs::VecOf; - -pub const TPM_ALG_ERROR: u16 = 0x0; -pub const TPM_ALG_RSA: u16 = 0x1; -pub const TPM_ALG_SHA1: u16 = 0x4; -pub const TPM_ALG_SHA256: u16 = 0xB; -pub const TPM_ALG_SHA384: u16 = 0xC; -pub const TPM_ALG_SHA512: u16 = 0xD; -pub const TPM_ALG_ECDSA: u16 = 0x18; - -pub const TCG_PCCLIENT_FORMAT: u8 = 1; -pub const TCG_CANONICAL_FORMAT: u8 = 2; - -// digest format: (algo id, hash value) -#[derive(Clone, Debug)] -pub struct TcgDigest { - pub algo_id: u16, - pub hash: Vec, -} - -// traits a Tcg IMR should have -pub trait TcgIMR { - fn max_index() -> u8; - fn get_index(&self) -> u8; - fn get_tcg_digest(&self, algo_id: u16) -> TcgDigest; - fn is_valid_index(index: u8) -> Result; - fn is_valid_algo(algo_id: u16) -> Result; -} - -/*** - TCG EventType defined at - https://trustedcomputinggroup.org/wp-content/uploads/PC-Client-Platform-Firmware-Profile-Version-1.06-Revision-52_pub.pdf -*/ -pub const EV_PREBOOT_CERT: u32 = 0x0; -pub const EV_POST_CODE: u32 = 0x1; -pub const EV_UNUSED: u32 = 0x2; -pub const EV_NO_ACTION: u32 = 0x3; -pub const EV_SEPARATOR: u32 = 0x4; -pub const EV_ACTION: u32 = 0x5; -pub const EV_EVENT_TAG: u32 = 0x6; -pub const EV_S_CRTM_CONTENTS: u32 = 0x7; -pub const EV_S_CRTM_VERSION: u32 = 0x8; -pub const EV_CPU_MICROCODE: u32 = 0x9; -pub const EV_PLATFORM_CONFIG_FLAGS: u32 = 0xa; -pub const EV_TABLE_OF_DEVICES: u32 = 0xb; -pub const EV_COMPACT_HASH: u32 = 0xc; -pub const EV_IPL: u32 = 0xd; -pub const EV_IPL_PARTITION_DATA: u32 = 0xe; -pub const EV_NONHOST_CODE: u32 = 0xf; -pub const EV_NONHOST_CONFIG: u32 = 0x10; -pub const EV_NONHOST_INFO: u32 = 0x11; -pub const EV_OMIT_BOOT_DEVICE_EVENTS: u32 = 0x12; -pub const EV_POST_CODE2: u32 = 0x13; - -pub const EV_EFI_EVENT_BASE: u32 = 0x80000000; -pub const EV_EFI_VARIABLE_DRIVER_CONFIG: u32 = EV_EFI_EVENT_BASE + 0x1; -pub const EV_EFI_VARIABLE_BOOT: u32 = EV_EFI_EVENT_BASE + 0x2; -pub const EV_EFI_BOOT_SERVICES_APPLICATION: u32 = EV_EFI_EVENT_BASE + 0x3; -pub const EV_EFI_BOOT_SERVICES_DRIVER: u32 = EV_EFI_EVENT_BASE + 0x4; -pub const EV_EFI_RUNTIME_SERVICES_DRIVER: u32 = EV_EFI_EVENT_BASE + 0x5; -pub const EV_EFI_GPT_EVENT: u32 = EV_EFI_EVENT_BASE + 0x6; -pub const EV_EFI_ACTION: u32 = EV_EFI_EVENT_BASE + 0x7; -pub const EV_EFI_PLATFORM_FIRMWARE_BLOB: u32 = EV_EFI_EVENT_BASE + 0x8; -pub const EV_EFI_HANDOFF_TABLES: u32 = EV_EFI_EVENT_BASE + 0x9; -pub const EV_EFI_PLATFORM_FIRMWARE_BLOB2: u32 = EV_EFI_EVENT_BASE + 0xa; -pub const EV_EFI_HANDOFF_TABLES2: u32 = EV_EFI_EVENT_BASE + 0xb; -pub const EV_EFI_VARIABLE_BOOT2: u32 = EV_EFI_EVENT_BASE + 0xc; -pub const EV_EFI_GPT_EVENT2: u32 = EV_EFI_EVENT_BASE + 0xd; -pub const EV_EFI_HCRTM_EVENT: u32 = EV_EFI_EVENT_BASE + 0x10; -pub const EV_EFI_VARIABLE_AUTHORITY: u32 = EV_EFI_EVENT_BASE + 0xe0; -pub const EV_EFI_SPDM_FIRMWARE_BLOB: u32 = EV_EFI_EVENT_BASE + 0xe1; -pub const EV_EFI_SPDM_FIRMWARE_CONFIG: u32 = EV_EFI_EVENT_BASE + 0xe2; -pub const EV_EFI_SPDM_DEVICE_POLICY: u32 = EV_EFI_EVENT_BASE + 0xe3; -pub const EV_EFI_SPDM_DEVICE_AUTHORITY: u32 = EV_EFI_EVENT_BASE + 0xe4; - -pub const IMA_MEASUREMENT_EVENT: u32 = 0x14; - -/*** - TCG IMR Event struct defined at - https://trustedcomputinggroup.org/wp-content/uploads/TCG_EFI_Platform_1_22_Final_-v15.pdf. - Definition: - typedef struct tdTCG_PCR_EVENT2{ - UINT32 pcrIndex; - UINT32 eventType; - TPML_DIGEST_VALUES digests; - UINT32 eventSize; - BYTE event[eventSize]; - } TCG_PCR_EVENT2; -*/ -#[derive(Clone)] -pub struct TcgImrEvent { - pub imr_index: u32, - pub event_type: u32, - pub digests: Vec, - pub event_size: u32, - pub event: Vec, -} - -impl std::fmt::Debug for TcgImrEvent { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("TcgImrEvent") - .field("imr_index", &self.imr_index) - .field("event_type", &self.event_type) - .field( - "digests", - &self - .digests - .iter() - .map(|d| hex::encode(&d.hash)) - .collect::>(), - ) - .field("event", &hex::encode(&self.event)) - .finish() - } -} - -/*** - TCG TCG_PCClientPCREvent defined at - https://trustedcomputinggroup.org/wp-content/uploads/TCG_PCClientSpecPlat_TPM_2p0_1p04_pub.pdf. - Definition: - typedef tdTCG_PCClientPCREvent { - UINT32 pcrIndex; - UINT32 eventType; - BYTE digest[20]; - UINT32 eventDataSize; - BYTE event[eventDataSize]; //This is actually a TCG_EfiSpecIDEventStruct - } TCG_PCClientPCREvent; -*/ -#[derive(Clone)] -pub struct TcgPcClientImrEvent { - pub imr_index: u32, - pub event_type: u32, - pub digest: [u8; 20], - pub event_size: u32, - pub event: Vec, -} - -/*** - TCG TCG_EfiSpecIDEventStruct defined at - https://trustedcomputinggroup.org/wp-content/uploads/EFI-Protocol-Specification-rev13-160330final.pdf. - Definition: - typedef struct tdTCG_EfiSpecIdEventStruct { - BYTE[16] signature; - UINT32 platformClass; - UINT8 specVersionMinor; - UINT8 specVersionMajor; - UINT8 specErrata; - UINT8 uintnSize; - UINT32 numberOfAlgorithms; - TCG_EfiSpecIdEventAlgorithmSize[numberOfAlgorithms] digestSizes; - UINT8 vendorInfoSize; - BYTE[VendorInfoSize] vendorInfo; - } TCG_EfiSpecIDEventStruct; -*/ -#[derive(Clone, scale::Decode, Debug)] -pub struct TcgEfiSpecIdEvent { - pub signature: [u8; 16], - pub platform_class: u32, - pub spec_version_minor: u8, - pub spec_version_major: u8, - pub spec_errata: u8, - pub uintn_ize: u8, - pub digest_sizes: VecOf, - pub vendor_info: VecOf, -} - -impl Default for TcgEfiSpecIdEvent { - fn default() -> Self { - Self::new() - } -} - -impl TcgEfiSpecIdEvent { - pub fn new() -> TcgEfiSpecIdEvent { - TcgEfiSpecIdEvent { - signature: [0; 16], - platform_class: 0, - spec_version_minor: 0, - spec_version_major: 0, - spec_errata: 0, - uintn_ize: 0, - digest_sizes: Default::default(), - vendor_info: Default::default(), - } - } -} - -/*** - TCG TCG_EfiSpecIdEventAlgorithmSize defined at - https://trustedcomputinggroup.org/wp-content/uploads/EFI-Protocol-Specification-rev13-160330final.pdf. - Definiton: - typedef struct tdTCG_EfiSpecIdEventAlgorithmSize { - UINT16 algorithmId; - UINT16 digestSize; - } TCG_EfiSpecIdEventAlgorithmSize; -*/ -#[derive(Clone, scale::Decode, Debug)] -pub struct TcgEfiSpecIdEventAlgorithmSize { - pub algo_id: u16, - pub digest_size: u16, -} diff --git a/certbot/Cargo.toml b/certbot/Cargo.toml deleted file mode 100644 index 207fb42817..0000000000 --- a/certbot/Cargo.toml +++ /dev/null @@ -1,28 +0,0 @@ -[package] -name = "certbot" -version.workspace = true -authors.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -anyhow.workspace = true -bon.workspace = true -enum_dispatch.workspace = true -fs-err.workspace = true -hickory-resolver.workspace = true -instant-acme.workspace = true -path-absolutize.workspace = true -rcgen.workspace = true -reqwest.workspace = true -serde.workspace = true -serde_json.workspace = true -time.workspace = true -tokio.workspace = true -tracing.workspace = true -x509-parser.workspace = true - -[dev-dependencies] -rand.workspace = true -tokio = { workspace = true, features = ["full"] } -tracing-subscriber.workspace = true diff --git a/certbot/cli/Cargo.toml b/certbot/cli/Cargo.toml deleted file mode 100644 index e37bb4c573..0000000000 --- a/certbot/cli/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "certbot-cli" -version.workspace = true -authors.workspace = true -edition.workspace = true -license.workspace = true - -[[bin]] -name = "certbot" -path = "src/main.rs" - -[dependencies] -anyhow.workspace = true -certbot.workspace = true -clap.workspace = true -documented.workspace = true -fs-err.workspace = true -serde.workspace = true -tokio = { workspace = true, features = ["full"] } -toml_edit.workspace = true -tracing-subscriber.workspace = true -rustls.workspace = true diff --git a/certbot/cli/src/main.rs b/certbot/cli/src/main.rs deleted file mode 100644 index 01af5ed40b..0000000000 --- a/certbot/cli/src/main.rs +++ /dev/null @@ -1,185 +0,0 @@ -use std::{path::PathBuf, time::Duration}; - -use anyhow::{Context, Result}; -use certbot::{CertBotConfig, WorkDir}; -use clap::Parser; -use documented::DocumentedFields; -use fs_err as fs; -use serde::{Deserialize, Serialize}; -use toml_edit::ser::to_document; - -#[derive(Parser)] -enum Command { - /// Automatically renew certificates if they are close to expiration - Renew { - /// Path to the configuration file - #[arg(short, long, default_value = "certbot.toml")] - config: PathBuf, - /// Run only once and exit - #[arg(long)] - once: bool, - }, - /// Initialize the configuration file - Init { - /// Path to the configuration file - #[arg(short, long, default_value = "certbot.toml")] - config: PathBuf, - }, - /// Set CAA record for the domain - SetCaa { - /// Path to the configuration file - #[arg(short, long, default_value = "certbot.toml")] - config: PathBuf, - }, - /// Generate configuration template - Cfg { - /// Write to file - #[arg(short, long)] - write_to: Option, - }, -} - -#[derive(Parser)] -struct Args { - #[command(subcommand)] - command: Command, -} - -#[derive(Deserialize, Serialize, DocumentedFields)] -struct Config { - /// Path to the working directory - workdir: PathBuf, - /// ACME server URL - acme_url: String, - /// Cloudflare API token - cf_api_token: String, - /// Cloudflare zone ID - cf_zone_id: String, - /// Auto set CAA record - auto_set_caa: bool, - /// Domain to issue certificates for - domain: String, - /// Renew interval in seconds - renew_interval: u64, - /// Number of days before expiration to trigger renewal - renew_days_before: u64, - /// Renew timeout in seconds - renew_timeout: u64, -} - -impl Default for Config { - fn default() -> Self { - Self { - workdir: ".".into(), - acme_url: "https://acme-staging-v02.api.letsencrypt.org/directory".into(), - cf_api_token: "".into(), - cf_zone_id: "".into(), - auto_set_caa: true, - domain: "example.com".into(), - renew_interval: 3600, - renew_days_before: 10, - renew_timeout: 120, - } - } -} - -impl Config { - fn to_commented_toml(&self) -> Result { - let mut doc = to_document(self)?; - - for (i, (mut key, _value)) in doc.iter_mut().enumerate() { - let decor = key.leaf_decor_mut(); - let docstring = Self::FIELD_DOCS[i]; - - let mut comment = String::new(); - for line in docstring.lines() { - let line = if line.is_empty() { - String::from("#\n") - } else { - format!("# {line}\n") - }; - comment.push_str(&line); - } - decor.set_prefix(comment); - } - Ok(doc.to_string()) - } -} - -fn load_config(config: &PathBuf) -> Result { - let config: Config = toml_edit::de::from_str(&fs::read_to_string(config)?)?; - let workdir = WorkDir::new(&config.workdir); - let renew_interval = Duration::from_secs(config.renew_interval); - let renew_expires_in = Duration::from_secs(config.renew_days_before * 24 * 60 * 60); - let renew_timeout = Duration::from_secs(config.renew_timeout); - let bot_config = CertBotConfig::builder() - .acme_url(config.acme_url) - .cert_dir(workdir.backup_dir()) - .cert_file(workdir.cert_path()) - .key_file(workdir.key_path()) - .auto_create_account(true) - .cert_subject_alt_names(vec![config.domain]) - .cf_zone_id(config.cf_zone_id) - .cf_api_token(config.cf_api_token) - .renew_interval(renew_interval) - .renew_timeout(renew_timeout) - .renew_expires_in(renew_expires_in) - .credentials_file(workdir.account_credentials_path()) - .auto_set_caa(config.auto_set_caa) - .build(); - Ok(bot_config) -} - -async fn renew(config: &PathBuf, once: bool) -> Result<()> { - let bot_config = load_config(config).context("Failed to load configuration")?; - let bot = bot_config - .build_bot() - .await - .context("Failed to build bot")?; - if once { - bot.run_once().await?; - } else { - bot.run().await; - } - Ok(()) -} - -#[tokio::main] -async fn main() -> Result<()> { - { - use tracing_subscriber::{fmt, EnvFilter}; - let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); - fmt().with_env_filter(filter).init(); - } - rustls::crypto::ring::default_provider() - .install_default() - .expect("Failed to install default crypto provider"); - - let args = Args::parse(); - match args.command { - Command::Renew { config, once } => { - renew(&config, once).await?; - } - Command::Init { config } => { - let config = load_config(&config).context("Failed to load configuration")?; - // The build_bot() will trigger the initialization and create Account if not exists - let _bot = config.build_bot().await.context("Failed to build bot")?; - } - Command::SetCaa { config } => { - let bot_config = load_config(&config).context("Failed to load configuration")?; - let bot = bot_config - .build_bot() - .await - .context("Failed to build bot")?; - bot.set_caa().await?; - } - Command::Cfg { write_to } => { - let toml_str = Config::default().to_commented_toml()?; - match write_to { - Some(path) => fs::write(path, toml_str)?, - None => println!("{}", toml_str), - } - } - } - Ok(()) -} diff --git a/certbot/src/acme_client.rs b/certbot/src/acme_client.rs deleted file mode 100644 index 7bcee1ca32..0000000000 --- a/certbot/src/acme_client.rs +++ /dev/null @@ -1,529 +0,0 @@ -use anyhow::{bail, Context, Result}; -use fs_err as fs; -use hickory_resolver::error::ResolveErrorKind; -use instant_acme::{ - Account, AccountCredentials, AuthorizationStatus, ChallengeType, Identifier, NewAccount, - NewOrder, Order, OrderStatus, -}; -use rcgen::{CertificateParams, DistinguishedName, KeyPair}; -use serde::{Deserialize, Serialize}; -use std::{ - collections::BTreeSet, - path::{Path, PathBuf}, - time::Duration, -}; -use tokio::time::sleep; -use tracing::{debug, error, info}; -use x509_parser::prelude::{GeneralName, Pem}; - -use super::dns01_client::{Dns01Api, Dns01Client}; - -/// A AcmeClient instance. -pub struct AcmeClient { - account: Account, - credentials: Credentials, - dns01_client: Dns01Client, -} - -#[derive(Debug, Clone)] -struct Challenge { - id: String, - acme_domain: String, - url: String, - dns_value: String, -} - -#[derive(Serialize, Deserialize)] -pub(crate) struct Credentials { - pub(crate) account_id: String, - credentials: AccountCredentials, -} - -impl AcmeClient { - pub async fn load(dns01_client: Dns01Client, encoded_credentials: &str) -> Result { - let credentials: Credentials = serde_json::from_str(encoded_credentials)?; - let account = Account::from_credentials(credentials.credentials).await?; - let credentials: Credentials = serde_json::from_str(encoded_credentials)?; - Ok(Self { - account, - dns01_client, - credentials, - }) - } - - /// Create a new account. - pub async fn new_account(acme_url: &str, dns01_client: Dns01Client) -> Result { - let (account, credentials) = Account::create( - &NewAccount { - contact: &[], - terms_of_service_agreed: true, - only_return_existing: false, - }, - acme_url, - None, - ) - .await - .context("failed to create new account")?; - let credentials = Credentials { - account_id: account.id().to_string(), - credentials, - }; - Ok(Self { - account, - dns01_client, - credentials, - }) - } - - /// Dump the account credentials to a JSON string. - pub fn dump_credentials(&self) -> Result { - Ok(serde_json::to_string(&self.credentials)?) - } - - /// Read the account ID from the encoded credentials. - pub fn account_id(&self) -> &str { - &self.credentials.account_id - } - - pub async fn set_caa_records(&self, domains: &[String]) -> Result<()> { - let account_id = self.account_id(); - let content = format!("letsencrypt.org;validationmethods=dns-01;accounturi={account_id}"); - let base_names = domains - .iter() - .map(|name| name.strip_prefix("*.").unwrap_or(name)) - .collect::>(); - - for base_name in base_names { - // 1. Set ";" to guard timing gap between the operations. - debug!("setting guard CAA records for {base_name}"); - let guard0 = self - .dns01_client - .add_caa_record(base_name, 0, "issue", ";") - .await?; - let guard1 = self - .dns01_client - .add_caa_record(base_name, 0, "issuewild", ";") - .await?; - // 2. Remove the existing constraints - for record in self.dns01_client.get_records(base_name).await? { - if record.id == guard0 || record.id == guard1 { - continue; - } - if record.r#type == "CAA" { - debug!( - "removing existing CAA record {} {}", - record.name, record.content - ); - self.dns01_client.remove_record(&record.id).await?; - } - } - // 3. Set the new constraints - debug!("setting CAA records for {base_name}, 0 issue \"{content}\""); - self.dns01_client - .add_caa_record(base_name, 0, "issue", &content) - .await?; - debug!("setting CAA records for {base_name}, 0 issuewild \"{content}\""); - self.dns01_client - .add_caa_record(base_name, 0, "issuewild", &content) - .await?; - debug!("removing guard CAA records for {base_name}"); - // 4. Remove the guards - self.dns01_client.remove_record(&guard0).await?; - self.dns01_client.remove_record(&guard1).await?; - } - Ok(()) - } - - /// Request new certificates for the given domains. - /// - /// Returns the new certificates encoded in PEM format. - pub async fn request_new_certificate(&self, key: &str, domains: &[String]) -> Result { - let mut challenges = Vec::new(); - let result = self - .request_new_certificate_inner(key, domains, &mut challenges) - .await; - for challenge in &challenges { - debug!("removing dns record {}", challenge.id); - if let Err(err) = self.dns01_client.remove_record(&challenge.id).await { - error!("failed to remove dns record {}: {err}", challenge.id); - } - } - result - } - - /// Auto renew given certificate - /// - /// Checks if the certificate is about to expire and renews it if necessary. - pub async fn renew_cert_if_needed( - &self, - cert_pem: &str, - key_pem: &str, - expires_in: Duration, - ) -> Result> { - if !need_renew(cert_pem, expires_in)? { - return Ok(None); - } - let cert = self - .renew_cert(cert_pem, key_pem) - .await - .context("failed to renew cert")?; - Ok(Some(cert)) - } - - /// Renew given certificate - pub async fn renew_cert(&self, cert_pem: &str, key_pem: &str) -> Result { - let domains = - extract_subject_alt_names(cert_pem).context("failed to extract subject alt names")?; - let cert = self - .request_new_certificate(key_pem, &domains) - .await - .context("failed to request new certificates")?; - Ok(cert) - } - - /// Auto renew given certificate - pub async fn auto_renew( - &self, - live_cert_pem_path: impl AsRef, - live_key_pem_path: impl AsRef, - backup_dir: impl AsRef, - expires_in: Duration, - ) -> Result { - let live_cert_pem = fs::read_to_string(live_cert_pem_path.as_ref())?; - let live_key_pem = fs::read_to_string(live_key_pem_path.as_ref())?; - let Some(new_cert) = self - .renew_cert_if_needed(&live_cert_pem, &live_key_pem, expires_in) - .await? - else { - return Ok(false); - }; - self.store_cert( - live_cert_pem_path.as_ref(), - live_key_pem_path.as_ref(), - &new_cert, - &live_key_pem, - backup_dir.as_ref(), - )?; - info!( - "renewed certificate for {}", - live_cert_pem_path.as_ref().display() - ); - Ok(true) - } - - fn store_cert( - &self, - live_cert_pem_path: &Path, - live_key_pem_path: &Path, - cert_pem: &str, - key_pem: &str, - backup_dir: impl AsRef, - ) -> Result<()> { - use path_absolutize::Absolutize; - - // Put the new cert in {backup_dir}/%Y%m%d_%H%M%S/cert.pem - let cert_dir = self.new_cert_dir(backup_dir.as_ref())?; - let backup_path = cert_dir.absolutize()?; - let cert_path = backup_path.join("cert.pem"); - let key_path = backup_path.join("key.pem"); - fs::write(&cert_path, cert_pem)?; - fs::write(&key_path, key_pem)?; - debug!("stored new cert in {}", cert_dir.display()); - - // symlink live_cert_pem_path to the new cert - ln_force(cert_path, live_cert_pem_path)?; - ln_force(key_path, live_key_pem_path)?; - Ok(()) - } - - /// Auto renew given certificate - pub async fn create_cert_if_needed( - &self, - domains: &[String], - live_cert_pem_path: impl AsRef, - live_key_pem_path: impl AsRef, - backup_dir: impl AsRef, - ) -> Result<()> { - if live_cert_pem_path.as_ref().exists() && live_key_pem_path.as_ref().exists() { - return Ok(()); - } - let key_pem = if live_key_pem_path.as_ref().exists() { - debug!("using existing cert key pair"); - fs::read_to_string(live_key_pem_path.as_ref())? - } else { - debug!("generating new cert key pair"); - let key = KeyPair::generate().context("failed to generate key")?; - key.serialize_pem() - }; - let cert_pem = self.request_new_certificate(&key_pem, domains).await?; - self.store_cert( - live_cert_pem_path.as_ref(), - live_key_pem_path.as_ref(), - &cert_pem, - &key_pem, - backup_dir.as_ref(), - )?; - Ok(()) - } -} - -impl AcmeClient { - async fn authorize(&self, order: &mut Order, challenges: &mut Vec) -> Result<()> { - let authorizations = order - .authorizations() - .await - .context("failed to get authorizations")?; - for authz in &authorizations { - match authz.status { - AuthorizationStatus::Pending => {} - AuthorizationStatus::Valid => continue, - _ => bail!("unsupported authorization status: {:?}", authz.status), - } - - let challenge = authz - .challenges - .iter() - .find(|c| c.r#type == ChallengeType::Dns01) - .context("no dns01 challenge found")?; - - let Identifier::Dns(identifier) = &authz.identifier; - - let dns_value = order.key_authorization(challenge).dns_value(); - debug!("creating dns record for {}", identifier); - let acme_domain = format!("_acme-challenge.{identifier}"); - self.dns01_client - .remove_txt_records(&acme_domain) - .await - .context("failed to remove existing dns record")?; - let id = self - .dns01_client - .add_txt_record(&acme_domain, &dns_value) - .await - .context("failed to create dns record")?; - challenges.push(Challenge { - id, - acme_domain, - url: challenge.url.clone(), - dns_value, - }); - } - Ok(()) - } - - /// Self check the TXT records for the given challenges. - async fn check_dns(&self, challenges: &[Challenge]) -> Result<()> { - let mut delay = Duration::from_millis(250); - let mut tries = 1u8; - - let mut unsettled_challenges = challenges.to_vec(); - - 'outer: loop { - use hickory_resolver::AsyncResolver; - - sleep(delay).await; - - let dns_resolver = - AsyncResolver::tokio_from_system_conf().context("failed to create dns resolver")?; - - while let Some(challenge) = unsettled_challenges.pop() { - let settled = match dns_resolver.txt_lookup(&challenge.acme_domain).await { - Ok(record) => record - .iter() - .any(|txt| txt.to_string() == challenge.dns_value), - Err(err) => { - let ResolveErrorKind::NoRecordsFound { .. } = err.kind() else { - bail!( - "failed to lookup dns record {}: {err}", - challenge.acme_domain - ); - }; - false - } - }; - if !settled { - delay *= 2; - tries += 1; - if tries < 10 { - debug!( - tries, - domain = &challenge.acme_domain, - "challenge not found, waiting {delay:?}" - ); - } else { - bail!("dns record not found"); - } - unsettled_challenges.push(challenge); - continue 'outer; - } - } - break; - } - Ok(()) - } - - async fn request_new_certificate_inner( - &self, - key: &str, - domains: &[String], - challenges: &mut Vec, - ) -> Result { - debug!("requesting new certificates for {}", domains.join(", ")); - debug!("creating new order"); - let identifiers = domains - .iter() - .map(|name| Identifier::Dns(name.clone())) - .collect::>(); - let mut order = self - .account - .new_order(&NewOrder { - identifiers: &identifiers, - }) - .await - .context("failed to cread new order")?; - let mut challenges_ready = false; - loop { - order.refresh().await.context("failed to refresh order")?; - match order.state().status { - // Need to accept the challenge - OrderStatus::Pending => { - if challenges_ready { - debug!("challenges are ready, waiting for order to be ready"); - sleep(Duration::from_secs(2)).await; - continue; - } - debug!("order is pending, waiting for authorization"); - self.authorize(&mut order, challenges) - .await - .context("failed to authorize")?; - if challenges.is_empty() { - bail!("no challenges found"); - } - self.check_dns(challenges) - .await - .context("failed to check dns")?; - for challenge in &*challenges { - debug!("setting challenge ready for {}", challenge.url); - order - .set_challenge_ready(&challenge.url) - .await - .context("failed to set challenge ready")?; - } - challenges_ready = true; - continue; - } - // To upload CSR - OrderStatus::Ready => { - debug!("order is ready, uploading CSR"); - let csr = make_csr(key, domains)?; - order - .finalize(csr.as_ref()) - .await - .context("failed to finalize order")?; - continue; - } - // Need to wait for the challenge to be accepted - OrderStatus::Processing => { - debug!("order is processing, waiting for the CSR to be accepted"); - sleep(Duration::from_secs(2)).await; - continue; - } - // Certificate is ready - OrderStatus::Valid => { - debug!("order is valid, getting certificate"); - return extract_certificate(order).await; - } - // Something went wrong - OrderStatus::Invalid => bail!("order is invalid"), - } - } - } - - fn new_cert_dir(&self, backup_dir: &Path) -> Result { - let timestamp = time::OffsetDateTime::now_utc() - .format(&time::format_description::well_known::Iso8601::DEFAULT) - .context("failed to format timestamp")?; - let backup_path = backup_dir.join(timestamp); - fs::create_dir_all(&backup_path)?; - Ok(backup_path) - } -} - -fn make_csr(key: &str, names: &[String]) -> Result> { - let mut params = - CertificateParams::new(names).context("failed to create certificate params")?; - params.distinguished_name = DistinguishedName::new(); - let key = KeyPair::from_pem(key).context("failed to parse private key")?; - let csr = params - .serialize_request(&key) - .context("failed to serialize certificate request")?; - Ok(csr.der().as_ref().to_vec()) -} - -async fn extract_certificate(mut order: Order) -> Result { - let mut tries = 0; - let cert_chain_pem = loop { - tries += 1; - if tries > 5 { - bail!("failed to get certificate"); - } - match order - .certificate() - .await - .context("failed to get certificate")? - { - Some(cert_chain_pem) => break cert_chain_pem, - None => sleep(Duration::from_secs(1)).await, - } - }; - Ok(cert_chain_pem) -} - -fn need_renew(cert_pem: &str, expires_in: Duration) -> Result { - let pem = read_pem(cert_pem)?; - let cert = pem.parse_x509().context("Invalid x509 certificate")?; - let not_after = cert.validity().not_after.to_datetime(); - let now = time::OffsetDateTime::now_utc(); - debug!("will expire in {:?}", not_after - now); - - Ok(not_after < now + expires_in) -} - -pub(crate) fn read_pem(cert_pem: &str) -> Result { - Pem::iter_from_buffer(cert_pem.as_bytes()) - .next() - .transpose() - .context("Invalid pem")? - .context("no certificate in pem") -} - -fn extract_subject_alt_names(cert_pem: &str) -> Result> { - let pem = read_pem(cert_pem)?; - let cert = pem.parse_x509().context("Invalid x509 certificate")?; - let subject_alt_names = cert - .tbs_certificate - .subject_alternative_name() - .context("failed to parse subject alternative name")? - .context("no subject alternative name found")?; - let mut domains = Vec::new(); - for name in &subject_alt_names.value.general_names { - if let GeneralName::DNSName(dns) = name { - domains.push(dns.to_string()); - } else { - bail!("unsupported general name: {:?}", name); - } - } - Ok(domains) -} - -fn ln_force(src: impl AsRef, dst: impl AsRef) -> Result<()> { - if dst.as_ref().exists() { - fs::remove_file(dst.as_ref())?; - } else if let Some(dst_parent) = dst.as_ref().parent() { - fs::create_dir_all(dst_parent)?; - } - fs::os::unix::fs::symlink(src.as_ref(), dst.as_ref())?; - Ok(()) -} - -#[cfg(test)] -mod tests; diff --git a/certbot/src/acme_client/tests.rs b/certbot/src/acme_client/tests.rs deleted file mode 100644 index be6beffbd0..0000000000 --- a/certbot/src/acme_client/tests.rs +++ /dev/null @@ -1,31 +0,0 @@ -#![cfg(not(test))] - -use super::*; - -async fn new_acme_client() -> Result { - let dns01_client = Dns01Client::new_cloudflare( - std::env::var("CLOUDFLARE_ZONE_ID").expect("CLOUDFLARE_ZONE_ID not set"), - std::env::var("CLOUDFLARE_API_TOKEN").expect("CLOUDFLARE_API_TOKEN not set"), - ); - let credentials = - std::env::var("LETSENCRYPT_CREDENTIAL").expect("LETSENCRYPT_CREDENTIAL not set"); - AcmeClient::load(dns01_client, &credentials).await -} - -#[tokio::test] -async fn test_request_new_certificate() { - tracing_subscriber::fmt::try_init().ok(); - - let test_domain = std::env::var("TEST_DOMAIN").expect("TEST_DOMAIN not set"); - let domains = vec![test_domain.clone(), format!("*.{}", test_domain)]; - let bot = new_acme_client().await.unwrap(); - println!("account credentials: {}", bot.dump_credentials().unwrap()); - let key = KeyPair::generate().unwrap(); - let key_pem = key.serialize_pem(); - let cert = bot - .request_new_certificate(&key_pem, &domains) - .await - .expect("Failed to get cert"); - println!("key:\n{}", key_pem); - println!("cert:\n{}", cert); -} diff --git a/certbot/src/bot.rs b/certbot/src/bot.rs deleted file mode 100644 index b73c5ee937..0000000000 --- a/certbot/src/bot.rs +++ /dev/null @@ -1,201 +0,0 @@ -use std::{ - collections::BTreeSet, - io::ErrorKind, - path::{Path, PathBuf}, - time::Duration, -}; - -use anyhow::{Context, Result}; -use fs_err as fs; -use tokio::time::sleep; -use tracing::{error, info}; - -use crate::acme_client::read_pem; - -use super::{AcmeClient, Dns01Client}; - -#[allow(clippy::duplicated_attributes)] -#[derive(Clone, Debug, bon::Builder)] -#[builder(on(String, into))] -#[builder(on(PathBuf, into))] -pub struct CertBotConfig { - acme_url: String, - auto_set_caa: bool, - credentials_file: PathBuf, - auto_create_account: bool, - cf_zone_id: String, - cf_api_token: String, - cert_file: PathBuf, - key_file: PathBuf, - cert_dir: PathBuf, - cert_subject_alt_names: Vec, - renew_interval: Duration, - renew_timeout: Duration, - renew_expires_in: Duration, -} - -impl CertBotConfig { - pub async fn build_bot(&self) -> Result { - CertBot::build(self.clone()).await - } -} - -pub struct CertBot { - acme_client: AcmeClient, - config: CertBotConfig, -} - -impl CertBot { - /// Build a new `CertBot` from a `CertBotConfig`. - pub async fn build(config: CertBotConfig) -> Result { - let dns01_client = - Dns01Client::new_cloudflare(config.cf_zone_id.clone(), config.cf_api_token.clone()); - let acme_client = match fs::read_to_string(&config.credentials_file) { - Ok(credentials) => AcmeClient::load(dns01_client, &credentials).await?, - Err(e) if e.kind() == ErrorKind::NotFound => { - if !config.auto_create_account { - return Err(e).context("credentials file not found"); - } - info!("creating new ACME account"); - let client = AcmeClient::new_account(&config.acme_url, dns01_client) - .await - .context("failed to create new account")?; - let credentials = client - .dump_credentials() - .context("failed to dump credentials")?; - if let Some(credential_dir) = config.credentials_file.parent() { - fs::create_dir_all(credential_dir) - .context("failed to create credential directory")?; - } - fs::write(&config.credentials_file, credentials) - .context("failed to write credentials")?; - info!("created new ACME account: {}", client.account_id()); - if config.auto_set_caa { - info!("setting CAA records"); - client - .set_caa_records(&config.cert_subject_alt_names) - .await?; - } - client - } - Err(e) => { - return Err(e).context("failed to read credentials file"); - } - }; - Ok(Self { - acme_client, - config, - }) - } - - /// Get the ACME account ID. - pub fn account_id(&self) -> &str { - self.acme_client.account_id() - } - - /// List all issued certificates. - pub fn list_certs(&self) -> Result> { - list_certs(&self.config.cert_dir) - } - - /// List all public keys. - pub fn list_cert_public_keys(&self) -> Result>> { - list_cert_public_keys(&self.config.cert_dir) - } - - /// Run the certbot. - pub async fn run(&self) { - loop { - match tokio::time::timeout(self.config.renew_timeout, self.run_once()).await { - Ok(Ok(_)) => {} - Ok(Err(e)) => { - error!("failed to run certbot: {e:?}"); - } - Err(_) => { - error!("certbot timed out"); - } - } - sleep(self.config.renew_interval).await; - } - } - - /// Run the certbot once. - pub async fn run_once(&self) -> Result<()> { - self.acme_client - .create_cert_if_needed( - &self.config.cert_subject_alt_names, - &self.config.cert_file, - &self.config.key_file, - &self.config.cert_dir, - ) - .await?; - info!("checking if certificate needs to be renewed"); - let renewed = self - .acme_client - .auto_renew( - &self.config.cert_file, - &self.config.key_file, - &self.config.cert_dir, - self.config.renew_expires_in, - ) - .await; - match renewed { - Ok(true) => { - info!( - "renewed certificate for {}", - self.config.cert_file.display() - ); - } - Ok(false) => { - info!( - "certificate {} is up to date", - self.config.cert_file.display() - ); - } - Err(e) => { - return Err(e); - } - } - Ok(()) - } - - /// Set CAA record for the domain. - pub async fn set_caa(&self) -> Result<()> { - self.acme_client - .set_caa_records(&self.config.cert_subject_alt_names) - .await - } -} - -fn read_pubkey(cert_pem: &str) -> Result> { - let cert = read_pem(cert_pem)?; - let public_key = cert.parse_x509().context("failed to parse x509 cert")?; - Ok(public_key.tbs_certificate.public_key().raw.to_vec()) -} - -pub fn list_certs(workdir: impl AsRef) -> Result> { - let mut certs = vec![]; - let cert_dir = Path::new(workdir.as_ref()); - for entry in fs::read_dir(cert_dir)? { - let entry = entry?; - let path = entry.path(); - let cert_path = path.join("cert.pem"); - if path.is_dir() && cert_path.exists() { - certs.push(cert_path); - } - } - Ok(certs) -} - -pub fn list_cert_public_keys(workdir: impl AsRef) -> Result>> { - list_certs(workdir)? - .into_iter() - .map(|cert_path| { - let cert_pem = fs::read_to_string(&cert_path).context("failed to read cert")?; - read_pubkey(&cert_pem).context("failed to parse cert") - }) - .collect::>() -} - -#[cfg(test)] -mod tests; diff --git a/certbot/src/bot/tests.rs b/certbot/src/bot/tests.rs deleted file mode 100644 index 6cd5ed07fd..0000000000 --- a/certbot/src/bot/tests.rs +++ /dev/null @@ -1,35 +0,0 @@ -#![cfg(not(test))] - -use instant_acme::LetsEncrypt; - -use super::*; - -async fn new_certbot() -> Result { - let cf_zone_id = std::env::var("CLOUDFLARE_ZONE_ID").expect("CLOUDFLARE_ZONE_ID not set"); - let cf_api_token = std::env::var("CLOUDFLARE_API_TOKEN").expect("CLOUDFLARE_API_TOKEN not set"); - let domains = vec![std::env::var("TEST_DOMAIN").expect("TEST_DOMAIN not set")]; - let config = CertBotConfig::builder() - .acme_url(LetsEncrypt::Staging.url()) - .auto_create_account(true) - .credentials_file("./test-workdir/credentials.json") - .cf_zone_id(cf_zone_id) - .cf_api_token(cf_api_token) - .cert_dir("./test-workdir/backup") - .cert_file("./test-workdir/live/cert.pem") - .key_file("./test-workdir/live/key.pem") - .cert_subject_alt_names(domains) - .renew_interval(Duration::from_secs(30)) - .renew_timeout(Duration::from_secs(120)) - .renew_expires_in(Duration::from_secs(7772187)) - .auto_set_caa(false) - .build(); - config.build_bot().await -} - -#[tokio::test] -async fn test_certbot() { - tracing_subscriber::fmt::try_init().ok(); - - let bot = new_certbot().await.unwrap(); - bot.run().await; -} diff --git a/certbot/src/dns01_client.rs b/certbot/src/dns01_client.rs deleted file mode 100644 index ae447593d5..0000000000 --- a/certbot/src/dns01_client.rs +++ /dev/null @@ -1,70 +0,0 @@ -use anyhow::Result; -use cloudflare::CloudflareClient; -use enum_dispatch::enum_dispatch; -use serde::{Deserialize, Serialize}; - -mod cloudflare; - -#[derive(Debug, Deserialize, Serialize)] -/// Represents a DNS record -pub(crate) struct Record { - /// Unique identifier for the record - pub id: String, - /// The name of the DNS record (e.g., "_acme-challenge.example.com") - pub name: String, - /// The content of the DNS record (e.g., the TXT value for ACME challenges) - pub content: String, - /// The type of DNS record (e.g., "TXT" for ACME challenges) - pub r#type: String, -} - -#[enum_dispatch] -pub(crate) trait Dns01Api { - /// Creates a TXT DNS record with the given domain and content. - /// - /// Returns the ID of the created record. - async fn add_txt_record(&self, domain: &str, content: &str) -> Result; - - /// Add a CAA record for the given domain. - async fn add_caa_record( - &self, - domain: &str, - flags: u8, - tag: &str, - value: &str, - ) -> Result; - - /// Remove a DNS record. - /// - /// Deletes a DNS record using its unique identifier. - async fn remove_record(&self, record_id: &str) -> Result<()>; - - /// Get all records for a domain. - async fn get_records(&self, domain: &str) -> Result>; - - /// Remove TXT DNS records by domain. - /// - /// Deletes all TXT DNS records matching the given domain. - async fn remove_txt_records(&self, domain: &str) -> Result<()> { - for record in self.get_records(domain).await? { - if record.r#type == "TXT" { - self.remove_record(&record.id).await?; - } - } - Ok(()) - } -} - -/// A DNS-01 client. -#[derive(Debug, Serialize, Deserialize)] -#[enum_dispatch(Dns01Api)] -#[serde(rename_all = "lowercase")] -pub enum Dns01Client { - Cloudflare(CloudflareClient), -} - -impl Dns01Client { - pub fn new_cloudflare(zone_id: String, api_token: String) -> Self { - Self::Cloudflare(CloudflareClient::new(zone_id, api_token)) - } -} diff --git a/certbot/src/dns01_client/cloudflare.rs b/certbot/src/dns01_client/cloudflare.rs deleted file mode 100644 index b574f65141..0000000000 --- a/certbot/src/dns01_client/cloudflare.rs +++ /dev/null @@ -1,256 +0,0 @@ -use anyhow::{Context, Result}; -use reqwest::Client; -use serde::{Deserialize, Serialize}; -use serde_json::json; - -use crate::dns01_client::Record; - -use super::Dns01Api; - -const CLOUDFLARE_API_URL: &str = "https://api.cloudflare.com/client/v4"; - -#[derive(Debug, Serialize, Deserialize)] -pub struct CloudflareClient { - zone_id: String, - api_token: String, -} - -impl CloudflareClient { - pub fn new(zone_id: String, api_token: String) -> Self { - Self { zone_id, api_token } - } -} - -impl Dns01Api for CloudflareClient { - async fn add_txt_record(&self, domain: &str, content: &str) -> Result { - let client = Client::new(); - let url = format!("{}/zones/{}/dns_records", CLOUDFLARE_API_URL, self.zone_id); - let response = client - .post(&url) - .header("Authorization", format!("Bearer {}", self.api_token)) - .header("Content-Type", "application/json") - .json(&json!({ - "type": "TXT", - "name": domain, - "content": content, - "ttl": 120 - })) - .send() - .await?; - - if !response.status().is_success() { - anyhow::bail!( - "failed to create acme challenge: {}", - response.text().await? - ); - } - - #[derive(Deserialize)] - struct Response { - result: ApiResult, - } - - #[derive(Deserialize)] - struct ApiResult { - id: String, - } - - let response: Response = response.json().await.context("failed to parse response")?; - - Ok(response.result.id) - } - - async fn remove_record(&self, record_id: &str) -> Result<()> { - let client = Client::new(); - let url = format!( - "{}/zones/{}/dns_records/{}", - CLOUDFLARE_API_URL, self.zone_id, record_id - ); - - let response = client - .delete(&url) - .header("Authorization", format!("Bearer {}", self.api_token)) - .send() - .await?; - - if !response.status().is_success() { - anyhow::bail!( - "failed to remove acme challenge: {}", - response.text().await? - ); - } - - Ok(()) - } - - async fn add_caa_record( - &self, - domain: &str, - flags: u8, - tag: &str, - value: &str, - ) -> Result { - let client = Client::new(); - let url = format!("{}/zones/{}/dns_records", CLOUDFLARE_API_URL, self.zone_id); - let response = client - .post(&url) - .header("Authorization", format!("Bearer {}", self.api_token)) - .header("Content-Type", "application/json") - .json(&json!({ - "type": "CAA", - "name": domain, - "ttl": 120, - "data": { - "flags": flags, - "tag": tag, - "value": value - } - })) - .send() - .await?; - if !response.status().is_success() { - anyhow::bail!( - "failed to create acme challenge: {}", - response.text().await? - ); - } - - #[derive(Deserialize)] - struct Response { - result: ApiResult, - } - - #[derive(Deserialize)] - struct ApiResult { - id: String, - } - - let response: Response = response.json().await.context("failed to parse response")?; - - Ok(response.result.id) - } - - async fn get_records(&self, domain: &str) -> Result> { - let client = Client::new(); - let url = format!("{}/zones/{}/dns_records", CLOUDFLARE_API_URL, self.zone_id); - - let response = client - .get(&url) - .header("Authorization", format!("Bearer {}", self.api_token)) - .send() - .await?; - - if !response.status().is_success() { - anyhow::bail!("failed to get dns records: {}", response.text().await?); - } - - #[derive(Deserialize, Debug)] - struct CloudflareResponse { - result: Vec, - } - - let response: CloudflareResponse = - response.json().await.context("failed to parse response")?; - - let records = response - .result - .into_iter() - .filter(|record| record.name == domain) - .collect(); - Ok(records) - } -} - -#[cfg(test)] -mod tests { - #![cfg(not(test))] - - use super::*; - - impl CloudflareClient { - #[cfg(test)] - async fn get_txt_records(&self, domain: &str) -> Result> { - Ok(self - .get_records(domain) - .await? - .into_iter() - .filter(|r| r.r#type == "TXT") - .collect()) - } - - #[cfg(test)] - async fn get_caa_records(&self, domain: &str) -> Result> { - Ok(self - .get_records(domain) - .await? - .into_iter() - .filter(|r| r.r#type == "CAA") - .collect()) - } - } - - fn create_client() -> CloudflareClient { - CloudflareClient::new( - std::env::var("CLOUDFLARE_ZONE_ID").expect("CLOUDFLARE_ZONE_ID not set"), - std::env::var("CLOUDFLARE_API_TOKEN").expect("CLOUDFLARE_API_TOKEN not set"), - ) - } - - fn random_subdomain() -> String { - format!( - "_acme-challenge.{}.{}", - rand::random::(), - std::env::var("TEST_DOMAIN").expect("TEST_DOMAIN not set"), - ) - } - - #[tokio::test] - async fn can_add_txt_record() { - let client = create_client(); - let subdomain = random_subdomain(); - println!("subdomain: {}", subdomain); - let record_id = client - .add_txt_record(&subdomain, "1234567890") - .await - .unwrap(); - let record = client.get_txt_records(&subdomain).await.unwrap(); - assert_eq!(record[0].id, record_id); - assert_eq!(record[0].content, "1234567890"); - client.remove_record(&record_id).await.unwrap(); - let record = client.get_txt_records(&subdomain).await.unwrap(); - assert!(record.is_empty()); - } - - #[tokio::test] - async fn can_remove_txt_record() { - let client = create_client(); - let subdomain = random_subdomain(); - println!("subdomain: {}", subdomain); - let record_id = client - .add_txt_record(&subdomain, "1234567890") - .await - .unwrap(); - let record = client.get_txt_records(&subdomain).await.unwrap(); - assert_eq!(record[0].id, record_id); - assert_eq!(record[0].content, "1234567890"); - client.remove_txt_records(&subdomain).await.unwrap(); - let record = client.get_txt_records(&subdomain).await.unwrap(); - assert!(record.is_empty()); - } - - #[tokio::test] - async fn can_add_caa_record() { - let client = create_client(); - let subdomain = random_subdomain(); - let record_id = client - .add_caa_record(&subdomain, 0, "issue", "letsencrypt.org;") - .await - .unwrap(); - let record = client.get_caa_records(&subdomain).await.unwrap(); - assert_eq!(record[0].id, record_id); - assert_eq!(record[0].content, "0 issue \"letsencrypt.org;\""); - client.remove_record(&record_id).await.unwrap(); - let record = client.get_caa_records(&subdomain).await.unwrap(); - assert!(record.is_empty()); - } -} diff --git a/certbot/src/lib.rs b/certbot/src/lib.rs deleted file mode 100644 index 1fde2a6a7b..0000000000 --- a/certbot/src/lib.rs +++ /dev/null @@ -1,23 +0,0 @@ -//! A CertBot client for requesting certificates from Let's Encrypt. -//! -//! This library provides a simple interface for requesting and managing SSL/TLS certificates -//! using the ACME protocol with Let's Encrypt as the Certificate Authority. -//! -//! # Features -//! -//! - Automatic certificate issuance and renewal -//! - DNS-01 challenge support (currently implemented for Cloudflare) -//! - Easy integration with existing Rust applications -//! -//! For more detailed information on the available methods and their usage, please refer -//! to the documentation of individual structs and functions. - -pub use acme_client::AcmeClient; -pub use bot::{CertBot, CertBotConfig}; -pub use dns01_client::Dns01Client; -pub use workdir::WorkDir; - -mod acme_client; -mod bot; -mod dns01_client; -mod workdir; diff --git a/certbot/src/workdir.rs b/certbot/src/workdir.rs deleted file mode 100644 index 47f20e2735..0000000000 --- a/certbot/src/workdir.rs +++ /dev/null @@ -1,59 +0,0 @@ -use anyhow::Result; -use fs_err as fs; -use std::{ - collections::BTreeSet, - path::{Path, PathBuf}, -}; - -use crate::acme_client::Credentials; - -#[derive(Debug, Clone)] -pub struct WorkDir { - workdir: PathBuf, -} - -impl WorkDir { - pub fn new(workdir: impl AsRef) -> Self { - Self { - workdir: workdir.as_ref().to_path_buf(), - } - } - - pub fn workdir(&self) -> &PathBuf { - &self.workdir - } - - pub fn account_credentials_path(&self) -> PathBuf { - self.workdir.join("credentials.json") - } - - pub fn backup_dir(&self) -> PathBuf { - self.workdir.join("backup") - } - - pub fn live_dir(&self) -> PathBuf { - self.workdir.join("live") - } - - pub fn cert_path(&self) -> PathBuf { - self.live_dir().join("cert.pem") - } - - pub fn key_path(&self) -> PathBuf { - self.live_dir().join("key.pem") - } - - pub fn list_certs(&self) -> Result> { - crate::bot::list_certs(self.backup_dir()) - } - - pub fn acme_account_uri(&self) -> Result { - let encoded_credentials = fs::read_to_string(self.account_credentials_path())?; - let credentials: Credentials = serde_json::from_str(&encoded_credentials)?; - Ok(credentials.account_id) - } - - pub fn list_cert_public_keys(&self) -> Result>> { - crate::bot::list_cert_public_keys(self.backup_dir()) - } -} diff --git a/certgen/Cargo.toml b/certgen/Cargo.toml deleted file mode 100644 index 24f93ce8d8..0000000000 --- a/certgen/Cargo.toml +++ /dev/null @@ -1,12 +0,0 @@ -[package] -name = "certgen" -version.workspace = true -authors.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -anyhow.workspace = true -clap.workspace = true -fs-err.workspace = true -ra-tls.workspace = true diff --git a/certgen/src/main.rs b/certgen/src/main.rs deleted file mode 100644 index 192b57b32f..0000000000 --- a/certgen/src/main.rs +++ /dev/null @@ -1,169 +0,0 @@ -use clap::Parser; -use fs_err as fs; -use ra_tls::{ - cert::{CaCert, CertRequest}, - rcgen::{KeyPair, PKCS_ECDSA_P256_SHA256}, -}; - -#[derive(Parser)] -#[command(author, version, about)] -struct Args { - #[command(subcommand)] - command: Commands, -} - -#[derive(clap::Subcommand)] -enum Commands { - /// Generate certificates for the KMS system - Generate { - /// Domain name for the generated certificates - #[arg(short, long)] - domain: String, - - /// Output directory for the generated certificates - #[arg(short, long, default_value = "certs")] - output_dir: String, - }, - /// Sign a certificate using an existing CA - Sign { - /// Domain name for the generated certificate - #[arg(short, long)] - domain: String, - - /// CA key file - #[arg(short, long)] - ca_key: String, - - /// CA cert file - #[arg(short, long)] - ca_cert: String, - - /// Output cert file - #[arg(short, long)] - cert: String, - - /// Output key file - #[arg(short, long)] - key: String, - }, -} - -fn main() -> anyhow::Result<()> { - let args = Args::parse(); - - match args.command { - Commands::Generate { domain, output_dir } => { - generate_and_store_certificates(&domain, &output_dir)?; - } - Commands::Sign { - domain, - ca_key, - ca_cert, - cert, - key, - } => { - sign_certificate(&domain, &ca_key, &ca_cert, &cert, &key)?; - } - } - Ok(()) -} - -fn generate_and_store_certificates(domain: &str, output_dir: &str) -> anyhow::Result<()> { - let tmp_ca_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - let ca_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - let kms_rpc_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - let tproxy_rpc_key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - - let tmp_ca_cert = CertRequest::builder() - .org_name("Phala Network") - .subject("Phala KMS Client Temp CA") - .ca_level(1) - .key(&tmp_ca_key) - .build() - .self_signed()?; - - // Create self-signed KMS cert - let ca_cert = CertRequest::builder() - .org_name("Phala Network") - .subject("Phala KMS CA") - .ca_level(3) - .key(&ca_key) - .build() - .self_signed()?; - - let kms_domain = format!("kms.{domain}"); - // Sign WWW server cert with KMS cert - let kms_rpc_cert = CertRequest::builder() - .subject(&kms_domain) - .alt_names(&[kms_domain.clone()]) - .key(&kms_rpc_key) - .build() - .signed_by(&ca_cert, &ca_key)?; - - let tproxy_domain = format!("tproxy.{domain}"); - let tproxy_rpc_cert = CertRequest::builder() - .subject(&tproxy_domain) - .alt_names(&[tproxy_domain.clone()]) - .key(&tproxy_rpc_key) - .build() - .signed_by(&ca_cert, &ca_key)?; - - store_cert( - output_dir, - "tmp-ca", - &tmp_ca_cert.pem(), - &tmp_ca_key.serialize_pem(), - )?; - store_cert( - output_dir, - "root-ca", - &ca_cert.pem(), - &ca_key.serialize_pem(), - )?; - store_cert( - output_dir, - "kms-rpc", - &kms_rpc_cert.pem(), - &kms_rpc_key.serialize_pem(), - )?; - store_cert( - output_dir, - "tproxy-rpc", - &tproxy_rpc_cert.pem(), - &tproxy_rpc_key.serialize_pem(), - )?; - - Ok(()) -} - -fn store_cert(path: &str, name: &str, cert: &str, key: &str) -> anyhow::Result<()> { - let cert_path = format!("{}/{}.cert", path, name); - let key_path = format!("{}/{}.key", path, name); - fs::write(cert_path, cert)?; - fs::write(key_path, key)?; - Ok(()) -} - -fn sign_certificate( - domain: &str, - ca_key_path: &str, - ca_cert_path: &str, - cert_path: &str, - key_path: &str, -) -> anyhow::Result<()> { - let ca_key = fs::read_to_string(ca_key_path)?; - let ca_cert = fs::read_to_string(ca_cert_path)?; - let ca = CaCert::new(ca_cert, ca_key)?; - let key = KeyPair::generate_for(&PKCS_ECDSA_P256_SHA256)?; - - let cert = CertRequest::builder() - .subject(domain) - .alt_names(&[domain.to_string()]) - .key(&key) - .build() - .signed_by(&ca.cert, &ca.key)?; - - fs::write(cert_path, cert.pem())?; - fs::write(key_path, key.serialize_pem())?; - Ok(()) -} diff --git a/cliff.toml b/cliff.toml new file mode 100644 index 0000000000..167ef9f5bb --- /dev/null +++ b/cliff.toml @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: © 2025 Phala Network +# +# SPDX-License-Identifier: Apache-2.0 + +# git-cliff ~ configuration file +# https://git-cliff.org/docs/configuration + +[changelog] +# A Tera template to be rendered as the changelog's header. +# See https://keats.github.io/tera/docs/#introduction +header = """ +# Changelog\n +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n +""" +# A Tera template to be rendered for each release in the changelog. +# See https://keats.github.io/tera/docs/#introduction +body = """ +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} + +{% if version -%} + ## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }} +{% else -%} + ## [Unreleased] +{% endif -%} + +{% for group, commits in commits | group_by(attribute="group") %} + ### {{ group | upper_first }} + {%- for commit in commits %} + - {{ commit.message | split(pat="\n") | first | upper_first | trim }}\ + {% if commit.remote.username %} by @{{ commit.remote.username }}{%- endif -%} + {% if commit.remote.pr_number %} in \ + [#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) \ + {%- endif -%} + {% endfor %} +{% endfor %} + +{%- if github.contributors | filter(attribute="is_first_time", value=true) | length != 0 %} + ## New Contributors +{%- endif -%} + +{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %} + * @{{ contributor.username }} made their first contribution + {%- if contributor.pr_number %} in \ + [#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \ + {%- endif %} +{%- endfor %}\n +""" +# A Tera template to be rendered as the changelog's footer. +# See https://keats.github.io/tera/docs/#introduction +footer = """ +{%- macro remote_url() -%} + https://github.com/{{ remote.github.owner }}/{{ remote.github.repo }} +{%- endmacro -%} + +{% for release in releases -%} + {% if release.version -%} + {% if release.previous.version -%} + [{{ release.version | trim_start_matches(pat="v") }}]: \ + {{ self::remote_url() }}/compare/{{ release.previous.version }}..{{ release.version }} + {% endif -%} + {% else -%} + [unreleased]: {{ self::remote_url() }}/compare/{{ release.previous.version }}..HEAD + {% endif -%} +{% endfor %} + +""" +# Remove leading and trailing whitespaces from the changelog's body. +trim = true + +[git] +# Parse commits according to the conventional commits specification. +# See https://www.conventionalcommits.org +conventional_commits = true +# Exclude commits that do not match the conventional commits specification. +filter_unconventional = false +# An array of regex based parsers to modify commit messages prior to further processing. +commit_preprocessors = [ + # Remove issue numbers. + { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "" }, +] +# An array of regex based parsers for extracting data from the commit message. +# Assigns commits to groups. +# Optionally sets the commit's scope and can decide to exclude commits from further processing. +commit_parsers = [ + { message = "^[a|A]dd", group = "Added" }, + { message = "^[s|S]upport", group = "Added" }, + { message = "^[r|R]emove", group = "Removed" }, + { message = "^.*: add", group = "Added" }, + { message = "^.*: support", group = "Added" }, + { message = "^.*: remove", group = "Removed" }, + { message = "^.*: delete", group = "Removed" }, + { message = "^test", group = "Fixed" }, + { message = "^fix", group = "Fixed" }, + { message = "^.*: fix", group = "Fixed" }, + { message = "^.*", group = "Changed" }, +] +# Exclude commits that are not matched by any commit parser. +filter_commits = false +# Order releases topologically instead of chronologically. +topo_order = false +# Order of commits in each group/release within the changelog. +# Allowed values: newest, oldest +sort_commits = "newest" diff --git a/ct_monitor/Cargo.toml b/ct_monitor/Cargo.toml deleted file mode 100644 index 1eda4eaa22..0000000000 --- a/ct_monitor/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "ct_monitor" -version.workspace = true -authors.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -anyhow.workspace = true -clap = { workspace = true, features = ["derive"] } -hex_fmt.workspace = true -regex.workspace = true -reqwest = { workspace = true, default-features = false, features = ["json", "rustls-tls", "charset", "hickory-dns"] } -serde = { workspace = true, features = ["derive"] } -serde_json.workspace = true -tokio = { workspace = true, features = ["full"] } -tracing.workspace = true -tracing-subscriber.workspace = true -x509-parser.workspace = true - -tproxy-rpc.workspace = true -ra-rpc = { workspace = true, default-features = false, features = ["client"] } diff --git a/ct_monitor/src/main.rs b/ct_monitor/src/main.rs deleted file mode 100644 index 2762c92cce..0000000000 --- a/ct_monitor/src/main.rs +++ /dev/null @@ -1,168 +0,0 @@ -use anyhow::{bail, Context, Result}; -use clap::Parser; -use ra_rpc::client::RaClient; -use regex::Regex; -use serde::{Deserialize, Serialize}; -use std::collections::BTreeSet; -use std::time::Duration; -use tproxy_rpc::tproxy_client::TproxyClient; -use tracing::{debug, error, info}; -use x509_parser::prelude::*; - -const BASE_URL: &str = "https://crt.sh"; - -struct Monitor { - tproxy_uri: String, - domain: String, - known_keys: BTreeSet>, - last_checked: Option, -} - -#[derive(Debug, Serialize, Deserialize)] -struct CTLog { - id: u64, - issuer_ca_id: u64, - issuer_name: String, - common_name: String, - name_value: String, - not_before: String, - not_after: String, - serial_number: String, - result_count: u64, - entry_timestamp: String, -} - -impl Monitor { - fn new(tproxy_uri: String, domain: String) -> Result { - validate_domain(&domain)?; - Ok(Self { - tproxy_uri, - domain, - known_keys: BTreeSet::new(), - last_checked: None, - }) - } - - async fn refresh_known_keys(&mut self) -> Result<()> { - info!("fetching known public keys from {}", self.tproxy_uri); - let todo = "Use RA-TLS"; - let tls_no_check = true; - let rpc = TproxyClient::new(RaClient::new(self.tproxy_uri.clone(), tls_no_check)); - let info = rpc.acme_info().await?; - self.known_keys = info.hist_keys.into_iter().collect(); - info!("got {} known public keys", self.known_keys.len()); - for key in self.known_keys.iter() { - debug!(" {}", hex_fmt::HexFmt(key)); - } - Ok(()) - } - - async fn get_logs(&self, count: u32) -> Result> { - let url = format!( - "{}/?q={}&output=json&limit={}", - BASE_URL, self.domain, count - ); - let response = reqwest::get(&url).await?; - Ok(response.json().await?) - } - - async fn check_one_log(&self, log: &CTLog) -> Result<()> { - let cert_url = format!("{}/?d={}", BASE_URL, log.id); - let cert_data = reqwest::get(&cert_url).await?.text().await?; - - let pem = Pem::iter_from_buffer(cert_data.as_bytes()) - .next() - .transpose() - .context("failed to parse pem")? - .context("empty pem")?; - let cert = pem.parse_x509().context("invalid x509 certificate")?; - - let pubkey = cert.public_key().raw; - if !self.known_keys.contains(pubkey) { - error!("❌ error in {:?}", log); - bail!( - "certificate has issued to unknown pubkey: {:?}", - hex_fmt::HexFmt(pubkey) - ); - } - info!("✅ checked log id={}", log.id); - Ok(()) - } - - async fn check_new_logs(&mut self) -> Result<()> { - let logs = self.get_logs(10000).await?; - debug!("got {} logs", logs.len()); - let mut found_last_checked = false; - - for log in logs.iter() { - let log_id = log.id; - - if let Some(last_checked) = self.last_checked { - if log_id == last_checked { - found_last_checked = true; - break; - } - } - debug!("🔍 checking log id={}", log_id); - self.check_one_log(log).await?; - } - - if !found_last_checked && self.last_checked.is_some() { - bail!("last checked log not found, something went wrong"); - } - - if !logs.is_empty() { - let last_log = &logs[0]; - debug!("last checked: {}", last_log.id); - self.last_checked = Some(last_log.id); - } - - Ok(()) - } - - async fn run(&mut self) { - info!("monitoring {}...", self.domain); - loop { - if let Err(err) = self.refresh_known_keys().await { - error!("error refreshing known keys: {}", err); - } - if let Err(err) = self.check_new_logs().await { - error!("error: {}", err); - } - tokio::time::sleep(Duration::from_secs(60)).await; - } - } -} - -fn validate_domain(domain: &str) -> Result<()> { - let domain_regex = - Regex::new(r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$").unwrap(); - if !domain_regex.is_match(domain) { - bail!("invalid domain name"); - } - Ok(()) -} - -#[derive(Parser, Debug)] -#[command(author, version, about, long_about = None)] -struct Args { - /// TProxy URI - #[arg(short, long)] - tproxy_uri: String, - /// Domain name to monitor - #[arg(short, long)] - domain: String, -} - -#[tokio::main] -async fn main() -> anyhow::Result<()> { - { - use tracing_subscriber::{fmt, EnvFilter}; - let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")); - fmt().with_env_filter(filter).init(); - } - let args = Args::parse(); - let mut monitor = Monitor::new(args.tproxy_uri, args.domain)?; - monitor.run().await; - Ok(()) -} diff --git a/docs/amd-sev-snp.md b/docs/amd-sev-snp.md new file mode 100644 index 0000000000..569fb5d8a0 --- /dev/null +++ b/docs/amd-sev-snp.md @@ -0,0 +1,265 @@ +# AMD SEV-SNP Support + +This document describes how dstack uses AMD SEV-SNP on self-hosted bare-metal +systems. SEV-SNP instances in public clouds are not supported yet: dstack +recomputes the launch measurement itself, which needs control of the launch, +and AWS signs its reports with a VLEK, which the verifier rejects. + +For platform firmware, kernel, QEMU, and OVMF preparation, start with +[Hardware Enablement](./hardware-enablement.md). This document covers the +dstack-specific image, installation, attestation, and key-release requirements. + +## Supported image line + +dstack OS 0.6.0 and later use one `dstack-` guest image for both Intel +TDX and AMD SEV-SNP. The unified Yocto machine includes both platform kernel +feature sets and detects the active TEE at runtime. Do not change the Yocto +`MACHINE` to a platform-specific value. + +Guest OS releases are split at the monorepo boundary: + +- versions below 0.6.0 are archived in + [`Dstack-TEE/meta-dstack`](https://github.com/Dstack-TEE/meta-dstack/releases) + under tags such as `v0.5.11`; +- versions 0.6.0 and later are in + [`Dstack-TEE/dstack`](https://github.com/Dstack-TEE/dstack/releases?q=guest-os-v) + under tags such as `guest-os-v0.6.0`. + +The 0.5.x images are legacy TDX images, not the current unified SEV-SNP image +line. Use a 0.6.6-or-later image for SEV-SNP. The image must include +`digest.txt`, `sha256sum.txt`, and the SNP measurement material. + +## Host requirements + +The host must provide: + +- an SEV-SNP-capable AMD processor and current platform firmware; +- SEV-SNP and the Reverse Map Table (RMP) enabled by the host kernel; +- `/dev/sev`; +- a QEMU and OVMF build with SEV-SNP support. + +After following the host platform's enablement procedure, check: + +```bash +test -e /dev/sev +sudo dmesg | grep -e SEV-SNP -e RMP +cat /sys/module/kvm_amd/parameters/sev_snp +``` + +The last command should print `Y`. `dstackup` checks `/dev/sev`, but that +preflight does not replace firmware, kernel, QEMU, or OVMF validation. + +## Install dstack on an SNP host + +Use a release containing the `sev-snp` key provider in the guest OS and VMM. The +KMS container and client attestation verifiers must recognize the new provider +metadata. Set `VERSION` to the OS release version and `KMS_IMAGE` to the KMS +container reference, then install: + +```bash +sudo dstackup image pull --version "$VERSION" +sudo dstackup install --platform amd-sev-snp \ + --image "dstack-$VERSION" --kms-image "$KMS_IMAGE" +sudo dstackup status +``` + +Confirm that installation reports `booted` for the KMS CVM. `dstackup` selects +the `sev-snp` provider for the KMS CVM on AMD hosts. The default +`--platform auto` also detects SEV-SNP from the host CPU flags. Explicit +selection checks for the required SNP device before installation. Review the +[KMS key-release policy](#kms-key-release-policy) before serving applications. + +## Run KMS with persistent local keys + +The `sev-snp` provider lets a KMS CVM recover its encrypted disk and stored KMS +roots after restart on the same AMD hardware. For a manually managed KMS CVM, +set this field in its app-compose document: + +```json +{"key_provider": "sev-snp"} +``` + +The deployment CLI also accepts `dstack deploy --key-provider sev-snp`. Application +CVMs continue using `key_provider: kms` and the existing KMS API. + +The guest derives a seed through `SNP_GET_DERIVED_KEY` using legacy VCEK at +VMPL0. The seed binds to launch measurement, guest policy, HOST_DATA, launch +identity, and a pinned TCB. The guest requires debugging disabled and encrypted +storage, and verifies the configuration binding before deriving the seed. + +Before initializing a new disk, the guest persists public derivation parameters +in `.instance_info` through the host API. Preserve this file, the encrypted +disk, and the original launch configuration together. Missing parameters for +an existing disk, unknown versions, or derivation/unlock failures stop startup. + +Recovery requires the original hardware and bound launch inputs. For OS or +compose changes, or hardware replacement, preserve KMS roots through the +existing onboarding/replication flow. Firmware updates must support the stored +derivation TCB and satisfy attestation policy. + +The entire KMS CVM, including its OS, is trusted. Protect KMS root and sealing +keys by keeping the KMS OS and workload under operator control. Application +key release continues to follow the existing KMS authorization policy. + +## Attestation and image identity + +The guest collects an SNP attestation report through Linux configfs-tsm when +available, with `/dev/sev-guest` extended-report collection as the fallback. +See [Native TEE Interfaces](./native-tee-interfaces.md) before exposing either +kernel interface directly to an application container. + +Verification is fail-closed and includes: + +1. the AMD ARK/ASK/VCEK certificate chain and report signature; +2. the requested `REPORT_DATA` challenge binding and SNP policy fields; +3. the launch `MEASUREMENT` recomputed from the VMM's firmware, kernel, + initramfs, command line, and launch inputs; +4. the MrConfigV3 `HOST_DATA` application-identity binding; +5. the unified OS image identity, `sha256(sha256sum.txt)`, which must match + `digest.txt` and the SNP measurement document. + +GPU workloads get the same boot-time guarantee as on TDX. Before key +provisioning, the guest attests every attached NVIDIA GPU, applies the app's +`requirements.gpu_policy`, and stops boot if either fails. The SNP report proves +this gate ran under that policy: the launch `MEASUREMENT` covers the OS that +runs it, and `HOST_DATA` binds the MrConfigV3 `compose_hash` that fixes the +policy. GPU launches also carry the policy digest, +`SHA-256(JCS(requirements.gpu_policy))`, as `MrConfigV3.gpu_policy_hash`. + +SEV-SNP has no quote-bound runtime register, so the per-boot `gpu-attestation` +event and the boot-time GPU evidence returned by `/v1/Attest` are not bound to +the report. A verifier that needs a GPU present, or a specific GPU count, must +find that requirement in the measured policy rather than in the event. See +[GPU Threat Model and Lifetime](./security/security-model.md#gpu-threat-model-and-lifetime). + +The verifier supports the AMD Milan, Genoa, and Turin KDS product families. +Bergamo and Siena are handled through AMD's canonical Genoa KDS product path. + +The verifier also fetches the product family's CRL from KDS +(`//crl`). It requires the CRL to be signed by the pinned ARK +and current, and rejects a revoked ASK. This applies whether the evidence +carries its certificates or the verifier fetches them, so a KDS mirror must +serve the CRL too. The verifier does not yet check the validity periods of the +ASK and VCEK certificates +([#1140](https://github.com/Dstack-TEE/dstack/issues/1140)). + +AMD publishes no TCB status for SNP, so a report is judged against a list of +minimum TCBs, one per CPU. An entry names the CPU by CPUID Fn0000_0001 EAX, as +AMD's security bulletins print it, and gives the highest SVNs those bulletins +require of it; family 1Ah (Turin) entries also set `fmc`. This one is Milan +after AMD-SB-3020 and AMD-SB-3027: + +```json +[{"cpuid":"00a00f11","bootloader":0,"tee":0,"snp":27,"microcode":222}] +``` + +A product family is too coarse a key: Milan (`00a00f11`) and Milan-X +(`00a00f12`) differ only in stepping and carry different microcode SVNs, as do +Genoa (`00a10f11`), Genoa-X (`00a10f12`) and Bergamo/Siena (`00aa0f02`). A +bulletin that lists only a microcode patch level implies the SVN: it is the +level's low byte, as the bulletins that state both show. + +`BootInfo.tcb_status` is `UpToDate` when the reported, committed and launch +TCBs all meet the entry for the report's CPU, and `OutOfDate` when one does +not. The reported TCB is the one the VCEK certifies, and the committed TCB +bounds a firmware rollback. SEV-SNP reports no advisory IDs. `DstackKms` +accepts only `UpToDate` from a KMS instance, as does `DstackApp` with +`requireTcbUpToDate`. + +The KMS reads the list from its auth API when it authorizes an SEV-SNP +attestation, reusing it for a second. Its verdict on its own attestation is +reused for an hour, like the rest of its boot info. Publish the list where the +auth API reads it: + +- With on-chain governance, publish it in `DstackKms` with + `setSevSnpTcbRequirements` (see [On-chain governance](./onchain-governance.md)). +- With `dstack-auth`, list the entries under `sevSnpTcbRequirements` (see + [dstack-auth operations](./dstack-auth-operations.md)). + +A KMS can cover CPUs governance does not list: `sev_snp_tcb_requirements_file` +under `[core.attestation]` names a file with the same JSON, read at startup. +The published list takes precedence: the file decides only for a CPU the +published list has no entry for, and cannot raise or lower a published minimum. +Governance does not see the file, so a KMS that carries one vouches by itself +for the CPUs governance leaves out, its own included. Write the file in the +KMS's compose file, like `kms.toml`, so that it is part of the measurement +governance allows. + +The KMS refuses a request it cannot judge, with the reason, instead of calling +the TCB out of date: when the auth API does not serve the list, when the list +does not parse, when neither list has an entry for the report's CPU, and when +the report predates the CPUID fields (version 2). The dev backend publishes +none, which leaves the KMS's own list. + +`dstack-verifier` does not read the auth API: give it the same JSON in the file +`attestation.sev_snp_tcb_requirements_file` names, which a compose file can +carry inline (see the [verifier README](../dstack/verifier/README.md)). It +reads the file at startup, and reports an empty status without one and for a +CPU without an entry. + +No report field shows firmware that was downgraded and upgraded again +while the guest ran, as long as the committed TCB stayed at the minimum. + +## KMS key-release policy + +SEV-SNP key and certificate release has two independent gates: + +1. the external KMS authorization policy must accept the verified `BootInfo`; +2. the local KMS operator must explicitly enable SNP release. + +The local gate is disabled by default: + +```toml +[core] +sev_snp_key_release = false +``` + +After the host, image, attestation, and external authorization policy have been +validated, enable it deliberately in the KMS configuration: + +```toml +[core] +sev_snp_key_release = true +``` + +This gate covers application keys, KMS key transfer, application certificate +signing, and self-authorized temporary CA material. Enabling it does not bypass +the external authorization decision. Keep `enforce_self_authorization = true` +for production TEE deployments. + +## AMD KDS collateral + +The verifier obtains the ASK and VCEK from the built-in AMD KDS URL when the +attestation evidence does not already contain them, and always fetches the +product family's CRL from it. An operator can set an AMD-KDS-compatible mirror +or cache, which must also serve `/crl`: + +```toml +[core] +amd_kds_base_url = "https://mirror.example.com/vcek/v1" +``` + +Leave the value empty to use the built-in default. A custom endpoint is part of +the verification trust and availability boundary: use a controlled mirror, +preserve TLS validation, and do not make verification succeed without valid +AMD signatures. + +## Troubleshooting + +- **`/dev/sev` is missing:** finish host firmware/kernel enablement before + running `dstackup install`. +- **The guest resets before Linux starts:** verify that the selected QEMU, + OVMF, and unified dstack OS image all support SNP. Do not debug KMS policy + until the guest boots reliably. +- **Image identity files are missing:** use a 0.6.6-or-later unified image. + `dstackup install` rejects an SNP image without `digest.txt`. +- **KDS requests fail:** check host time, DNS, outbound HTTPS, and KDS or mirror + availability. Do not disable certificate or signature verification. +- **Attestation succeeds but key release fails:** check both the external auth + response and `core.sev_snp_key_release`; either gate can deny the request. +- **TCB is `OutOfDate`:** the TCB is below the minimum published for its CPU. + Update the platform firmware before changing the auth policy. +- **`no minimum TCB is listed for CPUID ...`:** publish an entry for that CPU. + The error names the `cpuid` the entry needs. +- **`failed to read the SEV-SNP TCB requirements from the auth API`:** the auth + API predates the route, or the contract predates `sevSnpTcbRequirements`. diff --git a/docs/app-health-checks.md b/docs/app-health-checks.md new file mode 100644 index 0000000000..a3f9241c51 --- /dev/null +++ b/docs/app-health-checks.md @@ -0,0 +1,229 @@ +# Application health checks + +The gateway keeps an instance out of its app's load-balancing rotation while the +application is not able to serve. This page describes how an app opts into that +and where the verdict comes from. + +## Why this exists + +A CVM registers with the gateway from `dstack-util setup`, during boot. +`app-compose.service` is ordered *after* `dstack-prepare.service`, so at the +moment of registration the application's containers do not exist yet — the image +may still be pulling. Without a health signal the only thing standing between a +freshly booted instance and a real request is the WireGuard handshake, which +says the tunnel is up and nothing about whether anything is listening behind it. + +## Opting in + +Health gating is off unless the app asks for it, in `requirements`: + +```json +{ + "manifest_version": "3", + "name": "my-app", + "runner": "docker-compose", + "requirements": { + "health_check": true + } +} +``` + +That flag reaches the gateway at registration. An app that does not set it is +never polled and is routed to exactly as it was before this feature existed. + +It lives under `requirements` rather than at the top level for a reason: +`requirements` is rejected by guest images older than `manifest_version` 3, and +unknown fields *inside* it are a hard error. So a deployment that asks for +health gating does not silently land on an image that would ignore it. + +That protection is conditional, and the condition is yours: write +`"manifest_version": "3"` — **the string form**, as above. `AppCompose` itself +is not `deny_unknown_fields`, so an app-compose left at `"manifest_version": 2` +with a `requirements` block is *rejected* by a current guest and *silently +accepted, minus the requirements*, by an older one. The string form is what an +older guest chokes on. + +## Where the verdict comes from + +The guest agent recomputes a verdict every 5 seconds and caches it; the gateway +polls `/prpc/v1/Health`, which only reads that cache. The two cadences are +independent on purpose — a fleet of gateway nodes polling the same instance must +not multiply into that many container-runtime queries inside the CVM, and the +RPC is served on the CVM's publicly reachable listener. + +An app that never set `health_check` has no verdict to read: `/prpc/v1/Health` +answers `healthy: true` to whoever asks, whatever its containers are doing. No +gateway asks, so this only matters to a third party calling the RPC directly — +and there, `true` means "this app opted out of health gating", not "the agent +checked and the app is serving". + +There are two sources, and the app picks one. + +### Default: container healthchecks + +With no `health_status_file`, the agent judges the app's own Compose project: + +```yaml +services: + web: + image: my-app:1.0 + healthcheck: + test: ["CMD-SHELL", "curl -fsS localhost:8080/healthz || exit 1"] + interval: 10s + timeout: 3s + retries: 3 +``` + +Only containers that declare a `healthcheck` are judged. A container without one +is not evidence either way — the app has not said how to test it — so it is +skipped rather than counted as passing. `starting` counts as *not* healthy: that +state is precisely the boot window this exists to keep traffic out of. + +If containers are running but **not one of them declares a healthcheck**, the +instance reports unhealthy rather than healthy. You asked for traffic to be +gated on an answer that nothing can produce, and reporting a pass would leave +you with a feature that is switched on and doing nothing, visible only as the +absence of an effect. Note that this is judged from what the runtime did, not +from your compose file — a `HEALTHCHECK` in a Dockerfile counts, a `healthcheck` +merged in from a YAML anchor counts, and `healthcheck: {disable: true}` does +not, whatever the file appears to say. + +A container that declares a healthcheck and is **not running** is not healthy +either, whatever verdict the runtime last recorded for it. Docker re-marks a +stopped container `unhealthy`; nerdctl leaves the last result in place, so a +container that passed one check and then crashed still reports `healthy` with +`Running: false`. + +Finding **no containers at all** is not healthy either. A runtime that answers +while having nothing to show means Compose has not got as far as creating +anything. + +Only the app's own Compose project is judged, matched on the +`com.docker.compose.project` label. Container state lives on the persistent data +disk and outlives reboots and upgrades, so without that filter one exited +container left behind by an earlier deployment under a different project name +would hold the instance out of rotation permanently. + +The `nerdctl-compose` runner needs **nerdctl >= 2.3.1** for Compose +`healthcheck:` to be honoured; earlier versions parse the field and discard it. +Container presence is still detected on older versions, so the boot-window gate +works regardless. + +### `health_status_file`: the app answers for itself + +For the `bash` runner there are no containers to inspect, and an app may anyway +want to give one whole-application answer rather than have every container +judged separately. Name a file and the agent reads it: + +```json +{ + "requirements": { + "health_check": true, + "health_status_file": "/dstack/health" + } +} +``` + +The file is two lines: + +```text +healthy +1771234567 +``` + +| Line | Meaning | +|---|---| +| 1 | `healthy` or `unhealthy`, case-insensitive | +| 2 | Unix timestamp, in seconds, at which the app wrote the file | + +The timestamp is not decoration. A file older than **60 seconds** counts as +unhealthy, which is what turns a wedged app — still running, no longer updating +anything — into a verdict rather than a stale `healthy` that never expires. +Refresh it at least twice per that window; writing it once at startup is a way +to take yourself out of rotation a minute later. + +Anything else is not healthy: a missing file, a malformed one, an unparseable +timestamp, or a state word the agent does not recognise. Writing it atomically +(write a temporary file in the same directory, then rename) avoids being judged +on a half-written one. + +It must be a **regular file**. A FIFO is refused outright rather than reported +as unhealthy-with-a-reason: opening one with no writer would park a thread of +the agent's blocking pool on every refresh, and those threads are not +reclaimable. + +Symlinks *are* followed, including a symlinked parent directory. The path is +measured into the compose hash but what sits at that path at runtime is not, so +this is a read the app can redirect — which buys it nothing, because it already +writes the file and can therefore already lie about its own health. The read is +bounded and the contents are never quoted back. + +That last point is deliberate: a verdict names the rule that failed — "line 1 is +neither healthy nor unhealthy" — because the report is served to anonymous +callers and the bytes at that path may not be the bytes the app wrote. + +The agent reads the file from the guest rootfs, not from inside any container, +so a container that writes it needs the path bind-mounted in. **Mount the +directory, not the file.** A single-file bind mount pins an inode: a rename +inside the container replaces the container's own directory entry and never +touches the file the agent is reading, so the agent sees the original contents +forever, the timestamp ages past the limit, and the instance goes permanently +unhealthy. With the directory mounted, either write-then-rename or a plain +in-place write works. + +Before the first refresh completes, the app reports **not** healthy. +Registration happens long before the application is up, so "not determined yet" +must not read as a pass. + +## How the gateway uses it + +- Health only gates **app-id** routing. Addressing an instance directly by + instance id is never gated, so an unhealthy instance stays reachable for + investigation. +- **If no instance of an app reports healthy, the gateway routes to all of them + anyway.** Health is inference and can be wrong — a misconfigured probe, an + agent that died, a whole fleet failing for a reason unrelated to the app. + Blackholing an app on that basis is worse than sending traffic to instances + that might be fine. Note the consequence: for a **single-instance** app, or a + fleet that boots together, this rule routes traffic while every instance is + still `unknown`. Health gating shifts traffic away from a bad instance; it + does not hold an app offline until one is good. +- A poll that cannot reach the agent is not immediately a verdict. It takes + `failure_threshold` consecutive failures to demote an instance, so one dropped + packet does not eject it. An agent that *answers* "unhealthy" is believed on + the spot. +- Health is a *per-node observation*. Each gateway node polls for itself and + does not share the result, the same way each node reads its own WireGuard + handshakes. The verdict is not persisted: a gateway restart puts every + instance back at `unknown`, and since that is the whole app at once, the + fail-open above routes to all of them until the first round of polls answers + a few seconds later. What *is* stored is the CVM's declaration -- the + `health_check` field of its `inst/` record -- so a restarted node knows which + instances to poll before any of them re-register. +- Instances whose WireGuard handshake has gone stale are not polled. They are + already excluded from routing, and polling them would spend the round's budget + on CVMs that are gone. + +Operators can also take an instance out of rotation by hand with +`Admin.SetInstanceReady`, independently of health. That one is an instruction +rather than an inference, so it does **not** fail open: gating every instance of +an app means the app refuses new connections. + +Polling is configured on the gateway: + +```toml +[core.proxy.health_check] +enabled = true +interval = "5s" +timeout = "2s" +concurrency = 16 +failure_threshold = 2 +``` + +`enabled = false` restores the behaviour from before health polling existed: +every instance stays eligible regardless of what it reports. Note what that +looks like from the outside: instances that opted in sit at `unknown` forever, +because nothing will ever poll them, and they are *all in rotation*. The gateway +dashboard labels that case `unknown (gating off)` and reports the switch itself +under **This Node → Health Gating**, so the state is not left to be inferred +from a column that means something different when polling is on. diff --git a/docs/app-key-epochs.md b/docs/app-key-epochs.md new file mode 100644 index 0000000000..5cf3b052b0 --- /dev/null +++ b/docs/app-key-epochs.md @@ -0,0 +1,208 @@ +# Application key epochs + +Application owners can rotate their app's derived keys without rotating KMS root +keys or other apps. This extends SealedEnv (#1528); the PR dependency order is +#1519 → #1517 → #1520 → #1521 → #1528 → application epochs. + +## Authorization and rotation + +`authorizeApp` returns `currentAppEpoch` together with the current root +epoch and its chain hash. `requestedRootEpoch` and `requestedAppEpoch` are +independent `OptionalUint256` values: omitted selects current, explicit zero selects +historical epoch zero. Future epochs are denied through `rejectionReason`. +`authorizeKms` remains separate and uses app epoch zero. + +`DstackApp.currentAppEpoch` starts at zero. Its owner calls +`advanceAppEpoch(expectedCurrentEpoch)` to increment it. The expected value +prevents a stale or retried transaction from advancing twice. Epochs cannot be +rolled back and are limited to uint32. Prepare the next row before advancing, as +with a pending root epoch: approve its materials with `*AtEpoch(N + 1, ...)`, +then call `advanceAppEpoch(N)`, so guests that restart after the advance are +authorized at once. `AdvanceAppEpoch` in `Manage.s.sol` exposes +this operation; `GetAppEpoch` in `Query.s.sol` reads it. Upgrade the app policy +implementation before advancing, and upgrade the KMS/auth backend and guests +before using nonzero epochs. Once the app epoch is nonzero, the legacy +`isAppAllowed` of both `DstackApp` and `DstackKms` refuses, since its callers +derive epoch-zero keys, so the KMS contract calling the app policy must support +epochs before the app epoch advances. The ERC-165 `IAppEpochAuth` capability combines +`currentAppEpoch()` and `authorizeApp(AuthorizationRequest)` in one interface; the +policy returns the same `AuthorizationResult` struct as `DstackKms`. The request +also carries `teeVariant`, the platform name the KMS reports, which +`allowAnyTeeVariant` and `allowedTeeVariants` in `DstackApp` and `DstackKms` +restrict to the platforms listed in `TeeVariantPolicy.sol`; listing a new +platform takes a contract upgrade. Like `allowAnyDevice`, the policy covers every +epoch: which platforms may hold an app's keys is a trust decision, not a property +of a key generation. Legacy policies +without this capability remain at zero; failures of an advertised getter propagate. + +The Ethereum auth backends query the policy through the KMS contract. The simple +backend reads `apps[appId].currentAppEpoch` (default zero); operators must preserve +its monotonicity. Public encryption-key lookup uses `GET /app/:appId` to read this +value. With `APP_AUTH_URL` unset, auth-eth reads it at the `latest` block, so a +new app gets its key at once and an advanced epoch never hands out the retired +key. When `APP_AUTH_URL` is set, that service answers `GET /app/:appId` and owns +the epoch's freshness, and key release takes the app epoch from the delegate's +`currentAppEpoch` — the KMS only range-checks a requested epoch against it — +not from a value read at the policy block. The monotonicity requirement moves +with it: auth-eth only range-checks the delegate's epoch, so a delegate that +goes back an epoch, through a restore or a bug, makes environment public-key +lookups and default boots use a retired epoch's keys; delegate operators must +preserve its monotonicity. On the chain path, key release still reads the +policy block, so an +environment sealed to a just-advanced epoch boots only once the advance reaches +that block. Legacy boot authorization and +legacy environment public-key issuance are rejected once the app epoch is nonzero, +preventing old clients from silently continuing with epoch-zero keys. + +## Epoch-scoped allowlists + +Material approvals are an exact `epoch × material` matrix, not a maximum epoch. +Authorization checks only the selected row, with O(1) add, removal and lookup: + +- `DstackKms`: OS images, KMS aggregated measurements and KMS device IDs are + indexed by **root epoch**. OS image limits also apply to app key requests. +- `DstackApp`: compose hashes and device IDs are indexed by **app epoch**. Each + required material must be allowed in the selected row. `allowAnyDevice` is a + single switch over every app epoch: which hosts may run the app is not a + property of a key generation, and a per-epoch switch could leave an older + epoch open to any host after the current one is restricted. + +There is no implicit access in either direction. Rotating keys starts an empty +row; approving a new row neither copies old approvals nor grants historical keys. +Root and app selectors remain independent. Omitted selectors select the current +epochs. For an image handover, explicitly approve the new image in the old row so +it can migrate old keys, approve it in the new row, and remove the old image from +the old row after the handover. The old image never needs access to the new row. + +A request may select any epoch up to the current one and is decided on that +epoch's row, so a value is revoked only once every row allowing it is cleared. +Neither contract has epoch-less material setters: +`*AtEpochs(fromEpoch, toEpoch, material)` changes every row in the range, and in +`DstackApp` `*AtEpoch(epoch, material)` one row (in `DstackKms`, pass the epoch +twice). One transaction revokes a value from all rows, with +`remove*AtEpochs(0, latest, …)` in `DstackKms` and +`remove*AtEpochs(0, currentAppEpoch, …)` in `DstackApp`. `DstackKms` writes +registered root epochs (before any is registered, only epoch zero); `DstackApp` +writes app epochs up to the next one. +`DstackApp` reports these setters as the ERC-165 interface +`IAppEpochManagement` and no longer reports `IAppAuthBasicManagement` +(`0x8fd37527`), whose epoch-less setters it removed. The scripts in +`Manage.s.sol` take `ROOT_EPOCH` or `APP_EPOCH` for one row, or +`FROM_ROOT_EPOCH`/`TO_ROOT_EPOCH` and `FROM_APP_EPOCH`/`TO_APP_EPOCH` for a range, +and fail without them. + +App policies deployed before app epochs (v0.5.x, v0.6.0) keep working with an +upgraded `DstackKms` and KMS: they report no `IAppEpochAuth`, so `authorizeApp` +asks their `isAppAllowed` and only for app epoch zero, and `currentAppEpoch` +reports zero for them. Their owners keep the epoch-less setters until they +upgrade, which `Manage.s.sol` detects and uses with no epoch or `APP_EPOCH=0`. +Upgrading keeps their allowlists as app epoch zero. See +[onchain-governance.md](./onchain-governance.md#apps-deployed-before-app-epochs). + +Disk and environment migration after a root rotation fetches the keys of the +recorded epoch, so a new image migrating old data must be allowed in that old +row too. Without it the guest stops with an error naming the root and app epoch +it could not get keys for. + +The `*AtEpoch` getters read the selected row, including legacy epoch zero. +`EpochPolicyChanged` events include the row and the resulting permission. Legacy +bool getters and events describe **epoch zero only**; changing a nonzero row does +not change its legacy bool or emit a misleading legacy material event. The +exception is `allowAnyDevice` and its `AllowAnyDeviceSet` event, which cover every +app epoch. +Root policy rows from epoch 1 belong to the epoch's registration, so a row can +be written only once the epoch is registered (register, prepare the row, then +activate). A popped epoch's rows do not carry over: the next registration of the +number starts with empty rows, even with the same keys, which must be prepared +again before activation. Epoch 0 keeps the legacy mappings. + +### KMS keyring handover + +Keyring handover is deliberately different from app key access: approval in the +**highest exported root epoch** authorizes the entire keyring, including all older +roots. The KMS passes that epoch explicitly to `authorizeKms`, so approval in the +current row cannot accidentally authorize a newer pending keyring. A registered +pending root may be authorized for KMS handover before activation; app key requests +still cannot select it. KMS self-authorization without a selector continues to +check the active root epoch. The source checks `kms_import_keys` for the recipient, and the recipient +checks `kms_export_keys` for the source, both at the highest transferred epoch. +This permits staged key distribution without changing which epoch the KMS serves. + +### Upgrading existing proxies + +The original bool mappings and `allowAnyDevice` retain their storage locations and +are used directly as row zero. New storage consumes storage-gap slots in each +contract (seven in `DstackKms`, four in `DstackApp`); no entries are copied and no reinitializer is required. Existing +owners, pending owners, policy flags, root registries and app epoch counters are +preserved. Even if the pre-upgrade counter is nonzero, old global material +approvals grant only row zero after upgrading: explicitly populate the intended +nonzero rows. `allowAnyDevice` keeps covering every app epoch. + +Upgrade the KMS policy before app policies, then approve the intended rows before +restarting guests or activating a new root. `DstackApp` advertises the optional +ERC-165 `IAppEpochAuth` capability. `DstackKms.authorizeApp` first applies the +checks it owns (operation scope, registered root epoch, requested root epoch not +beyond the current one, app registration, OS image at the selected root epoch, +deployed contract), then forwards the request unchanged to the policy's +`authorizeApp`. The policy validates the operation and the requested app epoch and +fills `authorized`, `rejectionReason` and `currentAppEpoch`; the KMS then sets +`gatewayAppId` and the current and latest root epoch fields. The decision and +its app epoch therefore come from one policy call. Its interface ID is the XOR of +both method selectors; policies advertising only either former single-method +interface must upgrade to the combined interface. Policies without that capability can only +authorize app epoch zero; failures of an advertised method propagate instead of +falling back. +Direct legacy app checks use the current app epoch; legacy KMS app authorization +still rejects nonzero app epochs. + +These material matrices are implemented by the Solidity policies. Config-file auth +backends such as dstack-auth retain their own policy model; dstack-auth applies the +same epoch limits, accepting a registered pending root epoch for KMS handover and +only active epochs for key-issuing operations. + +## Derivation and lifetime + +Every key is identified by `(root_epoch, app_epoch)`. App epoch zero keeps existing derived keys and app-key signatures. Nonzero app epochs append +`"app-epoch-v1:" || app_epoch[4, big-endian]` to the existing derivation context +for disk, environment, SealedEnv, app CA and secp256k1 keys. + +The root signature for a nonzero app secp256k1 key signs Keccak256 of +`"dstack-kms-issued-v2:" || app_id[20] || app_epoch[4, big-endian] || public_key[33]`. +Relying parties must verify this format against the trusted root key for the +returned root epoch. Epoch zero keeps the original `dstack-kms-issued` format. + +Restart CVMs after advancing the policy. A running CVM continues to use its boot +key pair; omitted guest-agent GetKey selectors mean that CVM's boot epochs, not a +fresh chain lookup. Explicit historical requests select each dimension +independently and cache by the complete pair. Historical requests must be approved +in the selected root/app rows. Revoking one row does not revoke other rows or +keys already delivered. Supplied `trusted_ca` always pins the KMS connection, +regardless of epoch selection; historical responses cannot replace that pin. + +The guest migrates disk headers and environment ciphertext if either dimension +changes and rejects future epochs in either dimension. Disk migration also +requires `requirements.unsafe_allow_disk_migration` in the app compose, which is +strongly discouraged; see +[the emergency rotation protocol](kms-emergency-key-rotation-protocol.md#5-os-slot-migration-and-luks-header-metadata). LUKS tokens record both +epochs (missing app epoch means zero). Rekeying replaces the keyslot wrapping key; +it does not rotate the volume encryption key or erase host snapshots. Once a disk +header carries an epoch token, older guest images reject that header as malformed; +reverting the VM image therefore requires migrating the disk with a compatible +image or restoring a compatible header backup. App rotation isolates future app +keys from an exposed old derived key, but cannot recover from compromise of the +KMS root or revoke already disclosed secrets. + +## SDK selection + +Both selectors are optional; specify zero explicitly to recover an old key. +For example, Python `client.get_key("storage", "secp256k1", root_epoch=3, +app_epoch=0)` selects exactly that pair. JavaScript uses +`client.getKey("storage", "secp256k1", 3, 0)`. Rust uses +`client.get_key(GetKeyConfig::builder().domain("storage").algorithm("secp256k1").root_epoch(3).app_epoch(0).build())`. +Go provides `GetKeyAtEpochs` with pointer selectors. Responses report both epochs. + +Sealing helpers (`seal_env`, `SealEnv`, `sealEnv`) and the SealedEnv public-key +verifiers take both epochs, with no default: they work offline and cannot know +the current epochs, so pass the ones `GetSealedEnvPubKey` returned with the key. See [SealedEnv](sealed-env.md) for the wire and signature +formats. The VMM UI and CLI use the epochs returned with the encryption key. SealedEnv +uses a single version-1 format that always includes both epochs. diff --git a/docs/assets/app-board.png b/docs/assets/app-board.png new file mode 100644 index 0000000000..00d82892c1 Binary files /dev/null and b/docs/assets/app-board.png differ diff --git a/docs/assets/app-deploy.png b/docs/assets/app-deploy.png new file mode 100644 index 0000000000..7830d0b9eb Binary files /dev/null and b/docs/assets/app-deploy.png differ diff --git a/docs/assets/app-dns-a.png b/docs/assets/app-dns-a.png new file mode 100644 index 0000000000..13c8020c0d Binary files /dev/null and b/docs/assets/app-dns-a.png differ diff --git a/docs/assets/app-dns-txt.png b/docs/assets/app-dns-txt.png new file mode 100644 index 0000000000..068bc28ac1 Binary files /dev/null and b/docs/assets/app-dns-txt.png differ diff --git a/docs/assets/arch.png b/docs/assets/arch.png index 0670396c1b..a8cd28d720 100644 Binary files a/docs/assets/arch.png and b/docs/assets/arch.png differ diff --git a/docs/assets/dstack-logo-kit/01 Horizontal/01 Dstack _Horizontal_primary.png b/docs/assets/dstack-logo-kit/01 Horizontal/01 Dstack _Horizontal_primary.png new file mode 100644 index 0000000000..ee6e5fba58 Binary files /dev/null and b/docs/assets/dstack-logo-kit/01 Horizontal/01 Dstack _Horizontal_primary.png differ diff --git a/docs/assets/dstack-logo-kit/01 Horizontal/01 Dstack _Horizontal_primary.svg b/docs/assets/dstack-logo-kit/01 Horizontal/01 Dstack _Horizontal_primary.svg new file mode 100644 index 0000000000..4365f9ae67 --- /dev/null +++ b/docs/assets/dstack-logo-kit/01 Horizontal/01 Dstack _Horizontal_primary.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/dstack-logo-kit/01 Horizontal/02 Dstack _Horizontal_dark.png b/docs/assets/dstack-logo-kit/01 Horizontal/02 Dstack _Horizontal_dark.png new file mode 100644 index 0000000000..60afe999f4 Binary files /dev/null and b/docs/assets/dstack-logo-kit/01 Horizontal/02 Dstack _Horizontal_dark.png differ diff --git a/docs/assets/dstack-logo-kit/01 Horizontal/02 Dstack _Horizontal_dark.svg b/docs/assets/dstack-logo-kit/01 Horizontal/02 Dstack _Horizontal_dark.svg new file mode 100644 index 0000000000..72bb6d423a --- /dev/null +++ b/docs/assets/dstack-logo-kit/01 Horizontal/02 Dstack _Horizontal_dark.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/dstack-logo-kit/02 Vertical/01 Dstack_Vertical_primary.png b/docs/assets/dstack-logo-kit/02 Vertical/01 Dstack_Vertical_primary.png new file mode 100644 index 0000000000..1f764f0c44 Binary files /dev/null and b/docs/assets/dstack-logo-kit/02 Vertical/01 Dstack_Vertical_primary.png differ diff --git a/docs/assets/dstack-logo-kit/02 Vertical/01 Dstack_Vertical_primary.svg b/docs/assets/dstack-logo-kit/02 Vertical/01 Dstack_Vertical_primary.svg new file mode 100644 index 0000000000..8643a55300 --- /dev/null +++ b/docs/assets/dstack-logo-kit/02 Vertical/01 Dstack_Vertical_primary.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/dstack-logo-kit/02 Vertical/02 Dstack_Vertical_dark.png b/docs/assets/dstack-logo-kit/02 Vertical/02 Dstack_Vertical_dark.png new file mode 100644 index 0000000000..e0746960ea Binary files /dev/null and b/docs/assets/dstack-logo-kit/02 Vertical/02 Dstack_Vertical_dark.png differ diff --git a/docs/assets/dstack-logo-kit/02 Vertical/02 Dstack_Vertical_dark.svg b/docs/assets/dstack-logo-kit/02 Vertical/02 Dstack_Vertical_dark.svg new file mode 100644 index 0000000000..2599d4bcc5 --- /dev/null +++ b/docs/assets/dstack-logo-kit/02 Vertical/02 Dstack_Vertical_dark.svg @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/dstack-logo-kit/03 icon/01 Dstack icon_primary.png b/docs/assets/dstack-logo-kit/03 icon/01 Dstack icon_primary.png new file mode 100644 index 0000000000..4d43cb0a42 Binary files /dev/null and b/docs/assets/dstack-logo-kit/03 icon/01 Dstack icon_primary.png differ diff --git a/docs/assets/dstack-logo-kit/03 icon/01 Dstack icon_primary.svg b/docs/assets/dstack-logo-kit/03 icon/01 Dstack icon_primary.svg new file mode 100644 index 0000000000..7b11d94e2f --- /dev/null +++ b/docs/assets/dstack-logo-kit/03 icon/01 Dstack icon_primary.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/dstack-logo-kit/03 icon/02 Dstack icon_dark.png b/docs/assets/dstack-logo-kit/03 icon/02 Dstack icon_dark.png new file mode 100644 index 0000000000..10df666a67 Binary files /dev/null and b/docs/assets/dstack-logo-kit/03 icon/02 Dstack icon_dark.png differ diff --git a/docs/assets/dstack-logo-kit/03 icon/02 Dstack icon_dark.svg b/docs/assets/dstack-logo-kit/03 icon/02 Dstack icon_dark.svg new file mode 100644 index 0000000000..3ce920ea1e --- /dev/null +++ b/docs/assets/dstack-logo-kit/03 icon/02 Dstack icon_dark.svg @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/docs/assets/tproxy-accountid.png b/docs/assets/gateway-accountid.png similarity index 100% rename from docs/assets/tproxy-accountid.png rename to docs/assets/gateway-accountid.png diff --git a/docs/assets/tproxy.png b/docs/assets/gateway.png similarity index 100% rename from docs/assets/tproxy.png rename to docs/assets/gateway.png diff --git a/docs/assets/tappd.png b/docs/assets/guest-agent.png similarity index 100% rename from docs/assets/tappd.png rename to docs/assets/guest-agent.png diff --git a/docs/assets/kms-auth-set-info.png b/docs/assets/kms-auth-set-info.png new file mode 100644 index 0000000000..e63ac08701 Binary files /dev/null and b/docs/assets/kms-auth-set-info.png differ diff --git a/docs/assets/kms-bootstrap-result.png b/docs/assets/kms-bootstrap-result.png new file mode 100644 index 0000000000..abb06bea1e Binary files /dev/null and b/docs/assets/kms-bootstrap-result.png differ diff --git a/docs/assets/kms-bootstrap.png b/docs/assets/kms-bootstrap.png new file mode 100644 index 0000000000..c584645496 Binary files /dev/null and b/docs/assets/kms-bootstrap.png differ diff --git a/docs/assets/prelaunch-script.png b/docs/assets/prelaunch-script.png new file mode 100644 index 0000000000..a6d97f270d Binary files /dev/null and b/docs/assets/prelaunch-script.png differ diff --git a/docs/assets/tapp-dns-a.png b/docs/assets/tapp-dns-a.png deleted file mode 100644 index ba9b8c5beb..0000000000 Binary files a/docs/assets/tapp-dns-a.png and /dev/null differ diff --git a/docs/assets/tapp-dns-txt.png b/docs/assets/tapp-dns-txt.png deleted file mode 100644 index efd86b1b34..0000000000 Binary files a/docs/assets/tapp-dns-txt.png and /dev/null differ diff --git a/docs/assets/td-shim-vs-tdvf.png b/docs/assets/td-shim-vs-tdvf.png new file mode 100644 index 0000000000..0bd89525b8 Binary files /dev/null and b/docs/assets/td-shim-vs-tdvf.png differ diff --git a/docs/assets/token-env.png b/docs/assets/token-env.png new file mode 100644 index 0000000000..4848aeabeb Binary files /dev/null and b/docs/assets/token-env.png differ diff --git a/docs/assets/tproxy-add-wildcard-domain.jpg b/docs/assets/tproxy-add-wildcard-domain.jpg new file mode 100644 index 0000000000..44d8b8cfc9 Binary files /dev/null and b/docs/assets/tproxy-add-wildcard-domain.jpg differ diff --git a/docs/assets/teepod.png b/docs/assets/vmm.png similarity index 100% rename from docs/assets/teepod.png rename to docs/assets/vmm.png diff --git a/docs/attestation-gcp.md b/docs/attestation-gcp.md new file mode 100644 index 0000000000..408535cfed --- /dev/null +++ b/docs/attestation-gcp.md @@ -0,0 +1,56 @@ +# Dstack GCP Attestation Flow (GCP TDX + TPM) + +This document describes how dstack produces and verifies attestation on GCP using +TDX plus a TPM quote. It follows the implementation in `dstack-attest`. + +## Components +- TDX quote generator: `tdx-attest::get_quote` +- TDX event log reader: `cc-eventlog::tdx::read_event_log` +- TPM quote generator: `tpm-attest::TpmContext::create_quote` +- Verifier: `dstack-attest` + `dcap-qvl` + `tpm-qvl` + +## Attestation Creation (guest side) +1. **Collect report_data** (64 bytes), optionally bound to RA TLS pubkey. +2. **Generate TDX quote** via `tdx-attest::get_quote(report_data)`. +3. **Read TDX event log** via `cc-eventlog::tdx::read_event_log()`. +4. **Compute TPM qualifying data** as `sha256(tdx_quote)`. +5. **Create TPM quote** with qualifying data and dstack PCR policy: + `tpm_attest::TpmContext::create_quote(qualifying_data, policy)`. +6. **Bundle** into `DstackGcpTdxQuote { tdx_quote, tpm_quote }`. +7. **Include config** from `/dstack/.host-shared/.sys-config.json`. + +## Attestation Verification (verifier side) +Verification runs in `Attestation::verify_with_time` and splits into TDX + TPM. + +### TDX verification +1. **Fetch TDX collateral** and verify quote: + `dcap_qvl::collateral::get_collateral_and_verify(quote, pccs_url)`. +2. **Validate TCB**: + - Debug mode must be off. + - `mr_signer_seam` must be all-zero. +3. **Replay runtime events** to compute RTMR3 and compare with quote RTMR3. +4. **Check report_data** in TD report equals the attestation `report_data`. + +### TPM verification +1. **Fetch TPM collateral** and verify quote: + `tpm_qvl::get_collateral_and_verify(tpm_quote)`. +2. **Replay runtime events** to compute runtime PCR and compare with quoted PCR. +3. **Check qualifying data** equals `sha256(tdx_quote)`. +4. **Bind the OS image identity**: + `vm_config.os_image_hash` is the unified image digest + `sha256(sha256sum.txt)`. The verifier requires `vm_config.gcp_measurement`, + checks that `sha256sum.txt` commits to `measurement.gcp.cbor`, then compares + the UKI Authenticode hash inside that CBOR file with the GCP TPM PCR2 UKI + event. + +### Optional RA TLS binding +If the verifier provides a RA TLS pubkey, it enforces: +`report_data == QuoteContentType::RaTlsCert.to_report_data(pubkey)`. + +## Output +The verifier returns `DstackVerifiedReport::DstackGcpTdx` containing: +- `tdx_report` (verified TDX report and collateral info) +- `tpm_report` (verified TPM quote and PCRs) + +## Relevant Code +- `dstack-attest/src/attestation.rs` diff --git a/docs/attestation-nitro-enclave.md b/docs/attestation-nitro-enclave.md new file mode 100644 index 0000000000..7e0df262b1 --- /dev/null +++ b/docs/attestation-nitro-enclave.md @@ -0,0 +1,91 @@ +# Dstack Nitro Enclave Attestation Flow (NSM) + +> **AWS Nitro Support:** Attestation verification is fully implemented. For AWS deployment options, [book a call](https://calendly.com/aspect-ux/30min) with our team. + +This document describes how dstack produces and verifies attestation on AWS +Nitro Enclaves using the NSM attestation document. It follows the +implementation in `dstack-attest` and `nsm-qvl`. + +## Components +- NSM attestation generator: `nsm-attest::get_attestation` +- Verifier: `dstack-attest` + `nsm-qvl` + +## Attestation Creation (enclave side) +1. **Collect report_data** (64 bytes), optionally bound to RA TLS pubkey. +2. **Request NSM attestation** with user_data = report_data: + `nsm_attest::get_attestation(report_data)`. +3. **Bundle** into `DstackNitroQuote { nsm_quote }`. +4. **Include config** derived from PCRs: + `os_image_hash = sha256(PCR0 || PCR1 || PCR2)` (all zeros if PCRs are zero). + +The NSM attestation document (COSE_Sign1 payload) includes: +- `module_id`, `digest`, `timestamp` +- `pcrs` map +- signing `certificate` and `cabundle` +- optional `user_data`, `nonce`, `public_key` + +## Attestation Verification (verifier side) +Verification runs in `Attestation::verify_with_time`: + +### COSE and document checks (nsm-qvl) +1. **Parse COSE_Sign1** and require `alg = ES384 (-35)`. +2. **Validate COSE critical headers** (`crit`) if present. +3. **Parse attestation document** from payload and enforce: + - `digest == "SHA384"` + - PCR lengths are 48 bytes + - freshness window against `now` + +### Certificate chain and signature +4. **Verify cert chain** to `AWS_NITRO_ENCLAVES_ROOT_G1`. +5. **Verify COSE signature** using the leaf certificate P-384 key. +6. **Key usage sanity** on leaf cert (if present): + - must allow `digitalSignature` + - must not allow `keyCertSign` or `cRLSign` + +### Optional CRL verification +`nsm-qvl` exposes async CRL verification via: +`verify_attestation_with_crl(..., enable_crl, ...)`. +This is **disabled by default** in `dstack-attest` because CRL fetch from +S3 may return 403. The caller can enable CRL explicitly. + +### Dstack-specific checks +7. **Match user_data** to `report_data`. +8. **Decode PCRs** and return verified report. + +## Output +The verifier returns `DstackVerifiedReport::DstackNitroEnclave` containing: +- `module_id` +- `pcrs` (PCR0/1/2) +- `user_data` (report_data) +- `timestamp` + +## KMS key release + +Key release to a Nitro Enclave is gated locally by `nitro_enclave_key_release` +in `kms.toml`, which defaults to `false`: + +```toml +[core] +nitro_enclave_key_release = true +``` + +This gate sits *after* full attestation verification and after the external auth +policy decision, so both must also pass. It mirrors `sev_snp_key_release` and +`aws_nitro_tpm_key_release`: platforms whose confidentiality guarantee does not +come from a CPU the way Intel TDX's does are opt-in, so that enabling one never +implies another. + +Two properties of this platform are worth knowing before enabling it: + +- The AWS hypervisor is in the TCB. The NSM document is signed by an AWS root, + and PCR0/1/2 measure the enclave image, but there is no hardware memory + encryption isolating the enclave from the platform operator. +- dstack extends no runtime measurement register on this variant, so `app_id` + and `instance_id` in the attestation come from an event list that nothing + replays against a quoted register. `os_image_hash` and `compose_hash`, which + are derived from the signed PCRs, are unaffected. + +## Relevant Code +- `dstack-attest/src/attestation.rs` +- `nsm-qvl/src/verify.rs` +- `kms/src/main_service.rs` (`ensure_key_release_allowed`) diff --git a/docs/attestation-tdx.md b/docs/attestation-tdx.md new file mode 100644 index 0000000000..de1be25783 --- /dev/null +++ b/docs/attestation-tdx.md @@ -0,0 +1,92 @@ +# Intel TDX Attestation Guide for dstack Applications + +This document outlines the process of verifying the authenticity and integrity of data produced by dstack Applications running within Intel TDX environments. + +## 1. Review code safety + +- Review the Application code to ensure its logic is correct. +- Review the App Compose file to confirm it uses the specified source code or its compiled outputs. +- Review the runtime environment codebase, including virtual firmware, linux kernel, initrd, and rootfs. Verify the correctness of each component. + +## 2. Validate data origin authenticity +### 2.1 Understanding tdx quote measurements + +Applications generate a tdx quote using dstack's API given the data they want to prove. + +The quote signature can be verified using dcap-qvl to confirm its generation by a legitimate TDX CVM and environment trustworthiness. +Following signature verification, examine MRTD and RTMRs to confirm the CVM is executing the verified code. + +The MR register values indicate the following: + +- MRTD: Contains the virtual firmware measurement, taken by TDX-module in SEAM mode. Virtual firmware (OVMF in dstack's case) is the first code executed post-CVM startup, serving as the App code's trust anchor. Intel signs and guarantees TDX-module integrity. + +- RTMR: Measurements recorded by code executing within the CVM. In dstack OS, these measurements are defined as: + + - RTMR0: OVMF records CVM's virtual hardware setup, including CPU count, memory size, and device configuration. While dstack uses fixed devices, CPU and memory specifications can vary. RTMR0 can be computed from these specifications. + - RTMR1: OVMF records the Linux kernel measurement. + - RTMR2: Linux kernel records kernel cmdline (including rootfs hash) and initrd measurements. + - RTMR3: initrd records dstack App details, including compose hash, GPU policy and attestation events, instance id, app id, and key provider. + +MRTD, RTMR0, RTMR1, and RTMR2 can be pre-calculated from the built image (given CPU+RAM specifications). Compare these with the verified quote's MRs to confirm correct base image code execution. + +RTMR3 differs as it contains runtime information like compose hash and instance id. Verify this by replaying the event log - if the calculated RTMR3 matches the quote's RTMR3, the event log information is valid. Then verify the compose hash, key provider, and other event log details match expectations. + +After `compose-hash`, each configured init script produces an ordered +`init-script-hash` event whose payload is the SHA-256 digest of the exact UTF-8 +script bytes. The event order matches the script array order. These events let +an infrastructure provider contribute initialization code approved by +multiple parties and let each party verify its code independently without +reconstructing the complete compose document. + +For a GPU launch, any `init-script-hash` events are followed by +`gpu-policy-hash`. After successful NVIDIA attestation and policy evaluation, +`gpu-attestation` follows `boot-mr-done` and precedes `key-provider`. The `gpu-policy-hash` payload is +`SHA-256(JCS(requirements.gpu_policy))`, using `{}` when the field is omitted. +The `gpu-attestation` payload is JSON containing the verified device count, +CC/DevTools state, aggregate signed-claim `dbgstat` and `secboot`, and +`evidence_sha256`. + +The guest-agent returns the complete `nvattest` record captured during boot from `/v1/Attest`, when the request sets `include_boottime_gpu_evidence`, so a verifier can fetch the quote and the GPU evidence in one round trip. `AttestResponse.boottime_gpu_evidence` is a list of `GpuEvidenceBundle` (`{vendor, format, evidence}`); the boot record is the bundle whose `vendor` is `nvidia` and whose `format` is `nvidia-nvattest-boottime-json-v1`, and its `evidence` is hex-encoded bytes that decode to the exact UTF-8 `nvattest` output. It is not trustworthy by itself. (`/v1/AttestGpu` runs a *fresh* attestation against a caller nonce and returns bundles tagged `nvidia-nvattest-collect-evidence-json-v1`, a deliberately distinct format that a boot-record verifier does not appraise; its result is not bound to the TD and must not be used as remote evidence; only the boot-time record below is.) After verifying the TDX quote and replaying the event log to RTMR3, hash the *decoded* bundle bytes — `SHA-256(hex_decode(bundle.evidence))`, never the JSON string as returned nor a re-serialized form — and require the result to equal the `gpu-attestation` event's `evidence_sha256`. See [GPU Security for AI Workloads](./security/security-model.md#gpu-security-for-ai-workloads) for the event schema, ordering, Rego example, and platform differences. + +### 2.2. Determining expected MRs +MRTD, RTMR0, RTMR1, and RTMR2 correspond to the image. dstack OS builds all related software from source. +Build the exact image revision you intend to verify. See +[Build the dstack guest OS](./building-guest-os.md) for prerequisites and the +reproducible build workflow. At a high level: + +```bash +git clone https://github.com/Dstack-TEE/dstack.git +cd dstack +git checkout +make os-image +``` + +The resulting `os/mkosi/repro-build/build/out/prod/dstack-.tar.gz` +contains: + +- ovmf.fd: virtual firmware +- bzImage: kernel image +- initramfs.cpio.gz: initrd +- rootfs.img.parted.verity: partitioned dm-verity root filesystem +- metadata.json: image metadata, including kernel boot cmdline + +Calculate image MRs using [dstack-mr](../dstack/dstack-mr/): +```bash +VERSION=0.6.0 # replace with the image version being verified +cargo run --manifest-path dstack/Cargo.toml --bin dstack-mr measure \ + -c 4 -m 4G "dstack-$VERSION/metadata.json" +``` + +Once these verification steps are completed successfully, the report_data contained in the verified quote can be considered authentic and trustworthy. + +## Conclusion + +To verify dstack App data trustworthiness: + +- Review source code for correctness and safety. +- Build image from source. +- Calculate MRTD, RTMR0, RTMR1, and RTMR2 values using [dstack-mr](https://github.com/Dstack-TEE/dstack/tree/next/dstack/dstack-mr). +- Verify quote measurements: + - Confirm MRTD, RTMR0, RTMR1, and RTMR2 match pre-calculated values. + - Verify RTMR3 matches the event log replay result. + - Confirm event log details (compose hash, instance id, app id, rootfs hash, key provider) match expectations. diff --git a/docs/aws-attested-instance-security-evaluation.md b/docs/aws-attested-instance-security-evaluation.md new file mode 100644 index 0000000000..42703390b4 --- /dev/null +++ b/docs/aws-attested-instance-security-evaluation.md @@ -0,0 +1,74 @@ +# AWS EC2 Instance Attestation Security Evaluation + +This document evaluates dstack attestation on AWS EC2 with NitroTPM +(Attestable AMIs) under the account-admin-untrusted threat model. It states +the security properties dstack requires from a platform and how the AWS +NitroTPM path satisfies them in the current implementation. For the +operational relying-party workflow (verifier deployment, allowlists, key +release), see `docs/aws-ec2-production-verifier-runbook.md`. + +The threat model is: + +- Trusted root: AWS Nitro system and NitroTPM attestation signing + infrastructure. +- Verified, not blindly trusted: dstack OS images, dstack KMS instances, + dstack verifier code, and governance policy. The relying party accepts these + only after checking reproducible build outputs, attested measurements, event + logs, and policy state. A published AMI ID or a running KMS endpoint is not + sufficient evidence by itself. +- Untrusted: the workload AWS account administrator/operator. They may launch, + stop, replace, snapshot, reconfigure, and network-interpose EC2 resources in + their account. AWS KMS keys controlled by that account are also untrusted for + secret authority because the account administrator may be able to change key + policy, create grants, or route secret-bearing calls through policies they + control. +- Out of scope: availability. The operator can always deny service. + +## Platform Security Property Spec + +The following properties are the readiness gates for any platform claiming the +same security level as dstack under this threat model, and how the AWS +NitroTPM path meets them today. + +| ID | Required property | dstack mechanism | AWS NitroTPM status | +| --- | --- | --- | --- | +| P1 | Verifiable platform root of trust | TDX/SNP/Nitro quote verification against vendor root; debug rejected; TCB surfaced | NitroTPM Attestation Documents are verified against the AWS Nitro Attestation PKI, including document timestamp sanity. AWS exposes no TDX/SNP-style TCB advisory field, so a verified attestation is normalized to `tcbStatus = "UpToDate"` and passes the standard authorization gate unchanged. | +| P2 | Reproducible or independently computable base image measurement | meta-dstack rebuild plus `dstack-mr` computes `MRTD`/`RTMR0-2` | The unified `os/build.sh` flow emits the AWS image archive with `sha256sum.txt`, `digest.txt`, and `measurement.aws.cbor`; its output directory also contains the reference-PCR side-car `aws-pcrs.json`. `os_image_hash = sha256(sha256sum.txt)` is the same identity used on all platforms; the verifier recomputes it from the downloaded image directory (`dstack/verifier/src/verification.rs`). The hardening audit script `os/yocto/tools/aws/audit-aws-ec2-image-hardening.sh` checks the image for operator mutation channels. | +| P3 | Boot command line and root filesystem integrity are measured | `RTMR1/2`, rootfs hash, dm-verity, measured initrd/cmdline | The UKI commits kernel, initrd, and embedded cmdline into `PCR4`; the rootfs is dm-verity-protected. `VmConfig.aws_measurement` is required and must bind `boot_pcr_digest = sha256(PCR4||PCR7||PCR12)` to the attested PCRs, so `PCR12` (external cmdline) is always part of the bound digest — a missing-PCR12 bypass is not expressible. Enforced in guest quote generation (`dstack/dstack-attest/src/attestation.rs`), `verify_os_image_hash_for_aws_nitro_tpm` (`dstack/verifier/src/verification.rs`), and the KMS pipeline via the same verifier check. | +| P4 | Runtime application identity is cryptographically bound | RTMR3 `compose-hash`, `app-id`, `instance-id`, `key-provider`; event log replay | SHA384 `PCR14` event-log replay is the authoritative binding (RTMR3 analogue; non-resettable). Launch events: `system-preparing`, `app-id`, `compose-hash`, zero or more ordered `init-script-hash` events, `instance-id`, `boot-mr-done`, `key-provider`, `storage-fs`, `storage-encrypted`, `system-ready` (`dstack/dstack-util/src/system_setup.rs`). GPU launches also include `gpu-policy-hash` before `instance-id`, and `gpu-attestation` after `boot-mr-done` and before `key-provider`. `dstack-attest`, `dstack-verifier`, and KMS reject missing/mismatched PCR14 and bad replay. Optionally, the guest extends the raw `MrConfig` V2 `config_id` into `PCR8` once (`PCR8 = sha384(0^48 || config_id)`) so a lightweight third-party verifier can check compose hash + key provider without event-log replay; dstack's own verifier and KMS do not check PCR8. | +| P5 | Challenge/liveness and caller key binding | `report_data` challenge or RA-TLS public key hash in quote | RA-TLS binds `report_data` to the TLS certificate public key. KMS key release is bound to the live RA-TLS handshake; external `/verify` callers supply and check their own `report_data` challenge. The low-level NitroTPM document verifier also rejects stale or far-future document timestamps. | +| P6 | Secret release only to attested code | dstack KMS verifies attestation, checks auth policy, derives per-app keys | dstack KMS verifies the NitroTPM attestation, runs the same `verify_os_image_hash_for_aws_nitro_tpm` binding check as the verifier, builds `BootInfo` from verified boot PCRs plus PCR14 launch events, and checks auth policy before deriving app keys (`dstack/kms/src/main_service.rs`). AWS NitroTPM key release is gated behind the opt-in `aws_nitro_tpm_key_release` flag (default false in `kms.toml`). | +| P7 | Key-release policy is not controlled by the untrusted account admin | KMS runs inside TEE; policy from auth API/contracts; KMS identity measured | Satisfied with dstack KMS or another verifiable secret authority outside the untrusted AWS account admin's control. A NitroTPM-backed dstack KMS keeps root material out of account-admin snapshots and clones. The policy backend (on-chain `DstackKms`/`DstackApp` or an equivalent service; dstack-auth is for development, testing and evaluation only) must be outside the workload account admin's control. Same-account AWS KMS fails this property if the admin can change key policy, create grants, or call secret-bearing operations through a policy they control. | +| P8 | Operator cannot inject boot-time or runtime inputs that affect secrets without detection | Host-shared files are measured or independently authenticated; KMS URLs not trusted, KMS key identity measured | App TPM access is enforced by measurement, not by a container sandbox: `init_script`, `pre_launch_script`, and the docker-compose are measured into the app-compose hash, hence into the governed app identity, and replayed into non-resettable `PCR14`, so an operator cannot alter app inputs without changing the measured identity and being denied key release. Production dstack-os AWS images exclude SSH, cloud-init, SSM, EC2 Instance Connect, and serial login (checked by `audit-aws-ec2-image-hardening.sh`). IMDS/operator-provided config must not be a secret-affecting input unless measured or authenticated. | +| P9 | Persistent state confidentiality from account admin | dstack disk key derived after attestation; encrypted env vars decrypted only inside CVM | The local TPM key provider seals the disk seed under a SHA384 PCR policy over `[4, 7, 8, 12, 14]` (`AWS_NITRO_PCRS` in `dstack/tpm-attest/src/lib.rs`), so the sealed seed survives same-instance stop/start but does not transfer with cloned EBS volumes to another instance. EBS snapshots and volumes remain account-admin visible at the AWS control plane, so persisted confidential state must stay encrypted inside the instance and AMIs must contain no secrets. | +| P10 | Network and TLS endpoint identity is attestation-bound | RA-TLS / Zero Trust HTTPS / gateway attestation; TLS keys generated in TEE | The Rust RA-TLS verifier exposes `verify_der`/`verify_pem`, which extract the certificate's embedded attestation, verify it with the platform verifier (including AWS NitroTPM), and require `report_data = QuoteContentType::RaTlsCert(SubjectPublicKeyInfo)`. `dstack-verifier --verify-cert` provides an operator/relying-party certificate evidence path that also binds `os_image_hash`. AWS attestation alone does not protect DNS, load balancers, or admin-controlled proxies; clients must require this RA-TLS check, signed responses, or an attested gateway. | +| P11 | Upgrade governance is explicit and non-bypassable | DstackApp/DstackKms whitelists compose hashes, OS images, KMS aggregate MRs | dstack-auth and the unchanged on-chain `DstackKms`/`DstackApp` contracts pin OS image hash, app compose hash, device ID, and KMS identity. KMS auth pins the early `mrAggregated` (the `boot-mr-done` launch-event snapshot). AWS reuses the standard gate via `tcbStatus = "UpToDate"` normalization (dstack-auth enforces it once `allowedTcbStatuses: ["UpToDate"]` is set) with no AWS-specific on-chain field, plus the opt-in `aws_nitro_tpm_key_release` KMS flag. Secure Boot PCR7 certificate policies need explicit rotation/revocation handling so old AMIs do not remain authorized. | +| P12 | Verifier is independent and complete | `dstack-verifier`, DCAP/QVL, RTMR replay, KMS/app/governance checks | `dstack-verifier` verifies the NitroTPM document against the AWS Nitro PKI, enforces the required `aws_measurement`/`boot_pcr_digest` binding against the unified `os_image_hash`, replays the PCR14 launch-event chain, and emits the canonical auth-policy object as `details.boot_info` for the same policy logic used by `/bootAuth/app` and `/bootAuth/kms`. The relying-party deployment workflow is `docs/aws-ec2-production-verifier-runbook.md`; each deployment must instantiate it with real OS-image, PCR, and compose-hash allowlists. | + +## Sources + +- AWS EC2 instance attestation: + https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/nitrotpm-attestation.html +- AWS Attestable AMIs: + https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/attestable-ami.html +- AWS custom AMI PCR computation: + https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-pcr-compute.html +- AWS NitroTPM Attestation Document: + https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/attestation-get-doc.html +- AWS NitroTPM Attestation Document validation: + https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/nitrotpm-attestation-document-validate.html +- AWS NitroTPM Attestation Document contents: + https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/nitrotpm-attestation-document-content.html +- AWS KMS attested calls: + https://docs.aws.amazon.com/kms/latest/developerguide/attested-calls.html +- AWS NitroTPM samples: + https://github.com/aws/nitrotpm-attestation-samples +- AWS advisory on PCR12: + https://github.com/aws/nitrotpm-attestation-samples/security/advisories/GHSA-xrv8-2pf5-f3q7 +- dstack security model: `docs/security/security-model.md` +- dstack TDX attestation guide: `docs/attestation-tdx.md` +- dstack KMS protocol: `dstack/kms/README.md` +- dstack Nitro Enclave flow: `docs/attestation-nitro-enclave.md` +- dstack GCP TDX + TPM flow: `docs/attestation-gcp.md` +- AWS EC2 production verifier runbook: + `docs/aws-ec2-production-verifier-runbook.md` diff --git a/docs/aws-ec2-production-verifier-runbook.md b/docs/aws-ec2-production-verifier-runbook.md new file mode 100644 index 0000000000..de64f1481f --- /dev/null +++ b/docs/aws-ec2-production-verifier-runbook.md @@ -0,0 +1,325 @@ +# AWS EC2 Production Verifier Runbook + +This runbook describes the verifier-side workflow for AWS EC2 NitroTPM dstack +deployments under the account-admin-untrusted threat model. + +The relying party must not trust an AMI ID, DNS name, load balancer, AWS KMS +key, or dstack KMS endpoint by itself. It should accept a workload only after +checking the release evidence, NitroTPM challenge binding, policy `BootInfo`, +and endpoint identity. + +## Inputs + +- The release image package for the exact release candidate, produced by the + guest-OS build (`make os-image`; see `docs/building-guest-os.md`) as the + `--uki.tar.gz` archive. It contains `disk.raw`, `sha256sum.txt`, `digest.txt`, and + `measurement.{gcp,aws}.cbor`. The build output also contains an + `aws-pcrs.json` side-car, but that file is not part of the archive. +- The dstack monorepo sources pinned at the exact release revision, for the + reproducible rebuild. +- A dstack verifier built from this repository. +- The production auth policy backend: auth-eth contracts or an equivalent + verifier-controlled service. `dstack-auth` is for development, testing and + evaluation only. +- For public services, the endpoint's RA-TLS certificate. + +## 1. Verify Release Evidence + +The release evidence is the image package itself: every measured file is +listed in `sha256sum.txt`, and the unified image identity is +`os_image_hash = sha256(sha256sum.txt)` (also recorded as `digest.txt`). +There is no separately generated release manifest; the same build produces +both the image and its evidence. + +Rebuild from clean, pinned sources and require a byte-identical result: + +```bash +git status --porcelain # must be empty at the pinned release revision +make os-image # reproducible mkosi backend; emits os/mkosi/repro-build/build/out/prod/--uki.tar.gz +``` + +Compare the rebuilt package against the published one. `sha256sum.txt` lists +the full build inputs, not only the files in the UKI archive, so do not run +`sha256sum -c` inside the extracted UKI package: + +```bash +mkdir published rebuilt +tar -xzf published---uki.tar.gz -C published --strip-components=1 +tar -xzf rebuilt---uki.tar.gz -C rebuilt --strip-components=1 + +cmp published/sha256sum.txt rebuilt/sha256sum.txt +cmp published/measurement.aws.cbor rebuilt/measurement.aws.cbor +cmp published/disk.raw rebuilt/disk.raw + +expected=$(sha256sum published/sha256sum.txt | awk '{print $1}') +test "$expected" = "$(cat published/digest.txt)" +``` + +The mkosi backend pins its inputs to an immutable Debian snapshot, SHA-256 +checked archives, and fixed Git revisions (`os/mkosi/versions.env`); for full +supply-chain independence, mirror those inputs by content hash. + +Run the hardening audit against the release kernel config and rootfs; it must +exit zero with `failures=0`: + +```bash +os/yocto/tools/aws/audit-aws-ec2-image-hardening.sh \ + --kernel-config \ + --rootfs-manifest \ + --rootfs-squashfs +``` + +## 2. Register the AMI and deploy with `dstack-cloud` + +Apply the EC2 and EBS Direct IAM policy in the AWS prerequisites of +[`quickstart.md`](quickstart.md). `iam:PassRole` is needed only when +`aws_config.iam_instance_profile` is configured. + +After the release artifact hashes and AWS PCR references match the published +release evidence, deploy with **`dstack-cloud`** (`platform: aws`). The CLI +uploads the local UKI `disk.raw` directly to an EBS snapshot and registers an +Attestable AMI (UEFI + NitroTPM v2.0) when `aws_config.ami_id` is empty, builds +the shared config disk with +`aws_measurement` from `measurement.aws.cbor`, writes a minimal GPT data-disk +template whose partition is labeled `dstack-data`, and launches the instance. + +```bash +# one-time: install CLI +export PATH="$PATH:$(pwd)/dstack/scripts/bin" + +# project for AWS +dstack-cloud new my-aws-app --platform aws --region us-west-2 +cd my-aws-app +# configure subnet/security groups; no S3 bucket or vmimport role is required +# pull or place the UKI package (must include measurement.aws.cbor) under image_search_paths + +dstack-cloud pull dstack-0.6.0 # UKI package must include assemble-time measurement.aws.cbor +dstack-cloud prepare # embeds fixed os_image_hash + aws_measurement (no PCR recompute) +dstack-cloud deploy # create EBS snapshots directly, register AMI, run-instances + +dstack-cloud status +dstack-cloud logs --follow +``` + +Record the resulting AMI id, shared/data snapshots, and instance id from +`state.json` / `dstack-cloud status` in the release review package. + +Recompute AWS reference PCRs and the UKI AuthentiCode hash from the release +UKI with version-pinned host tools (do not rely on an unpinned container +toolchain for reference measurements): + +```bash +cargo install --git https://github.com/aws/NitroTPM-Tools \ + --rev d76d6eeebd4169b00a3c3af9858852d48f40e748 \ + --locked nitro-tpm-pcr-compute # aws/NitroTPM-Tools v1.1.2 +# The UKI is EFI/BOOT/BOOTX64.EFI in the 256 MiB EFI partition at 1 MiB. +dd if=published/disk.raw of=efi.img bs=1M skip=1 count=256 status=none +mcopy -i efi.img ::EFI/BOOT/BOOTX64.EFI dstack-uki.efi +nitro-tpm-pcr-compute --image dstack-uki.efi +pesign -h -P -i dstack-uki.efi # UKI AuthentiCode SHA256 +``` + +The PCRs must match the build-output `aws-pcrs.json` side-car when it is +published with the release, and their digest +`sha256(PCR4 || PCR7 || PCR12)` must equal the `boot_pcr_digest` committed in +`measurement.aws.cbor`. For the generic hardened UKI this is the boot PCR set +plus the UKI hash: + +```text +dstack_os_image_hash: +PCR4: +PCR7: +PCR12: 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 +UKI AuthentiCode SHA256: +``` + +For a dynamic app package, the **UKI/AMI stays generic**. App/config identity +is not embedded in the UKI cmdline; the guest computes the `MrConfig` **V2** +config id from its measured app identity (compose hash, app id, key-provider +kind, deploy-time key-provider pin from `app-compose.json`) and extends the +raw config id into **PCR8** at guest setup. Record the expected config id in +the deployment-specific release package: + +```text +dstack_os_image_hash: # prefer sha256(sha256sum.txt) + aws_measurement +PCR4/PCR7/PCR12: +PCR8: sha384(0^48 || ) +PCR14: +expected MrConfig V2 config id: +``` + +## 3. Verify the Attestation + +Challenge binding uses **report_data → NitroTPM user_data** (same role as +TDX/GCP): the relying party embeds its own challenge in `report_data` and +checks it against `details.report_data` in the verifier result. + +Example verifier request shape: + +```json +{ + "attestation": "hex-encoded-dstack-attestation" +} +``` + +Run: + +```bash +cargo run --bin dstack-verifier -- --verify request.json +``` + +Require: + +```bash +# from the release package: os_image_hash = sha256(sha256sum.txt) +expected_os_image_hash=$(sha256sum published/sha256sum.txt | awk '{print $1}') +# exact 64-byte challenge used when collecting this attestation, as hex +expected_report_data="<128-hex-characters>" + +jq -e \ + --arg expected_os_image_hash "$expected_os_image_hash" \ + --arg expected_report_data "$expected_report_data" ' + .is_valid == true and + .details.quote_verified == true and + .details.report_data == $expected_report_data and + .details.boot_info.teeVariant == "dstack-aws-nitro-tpm" and + .details.boot_info.tcbStatus == "UpToDate" and + .details.boot_info.osImageHash == $expected_os_image_hash +' request.json.verification.json +``` + +NitroTPM has no TDX/SNP-style TCB surface, so the verifier and KMS normalize a +verified NitroTPM attestation to `tcbStatus = "UpToDate"`. This lets AWS reuse +the standard authorization contract and auth policy unchanged, with no +AWS-specific on-chain fields. + +The relying party should then check `details.boot_info` against its auth policy. + +## 4. Configure Auth Policy + +For AWS NitroTPM, the policy must require: + +- accepted `tcbStatus` (`UpToDate`, matching the normalized value); +- accepted `osImageHash` (unified `sha256(sha256sum.txt)`; `aws_measurement` + is required and must bind the attested boot PCRs); +- accepted app `composeHash` and `appId`; +- accepted KMS identity via **early `mrAggregated`** (boot-mr-done), same as + bare TDX; +- verified PCR14 event-log replay (single event lane; no PCR23 runtime split) — + this is the authoritative app-identity binding (`composeHash`, `appId`, + `instance-id`, `key-provider`); +- a `report_data` challenge for external verifier flows that need liveness. + +When evaluating with `dstack-auth`, note that the TCB status and advisories are +checked only when the allowlist sets them, so set both explicitly: + +```json +{ + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [], + "osImages": ["0x"], + "kms": { + "mrAggregated": ["0x"], + "devices": [], + "allowAnyDevice": true + }, + "apps": { + "0x": { + "composeHashes": ["0x"], + "devices": [], + "allowAnyDevice": true + } + } +} +``` + +dstack-auth authorizes the canonical `BootInfo` the KMS derives after verifying +the NitroTPM evidence; it does not verify raw NitroTPM evidence itself. See +[dstack-auth operations](./dstack-auth-operations.md) for the remaining fields. + +For GPU workloads, PCR14 also contains `gpu-policy-hash` immediately after +`compose-hash`. Its 32-byte payload must equal +`SHA-256(JCS(requirements.gpu_policy))`, using `{}` when the policy is omitted. +Because the verifier replays the event chain against the signed NitroTPM +Attestation Document, this validates `gpu_policy_hash` on AWS. A successful GPU +launch also adds `gpu-attestation`; after PCR14 replay, its `evidence_sha256` +can be compared with `SHA-256(hex_decode(bundle.evidence))`, where `bundle` is +the `AttestResponse.boottime_gpu_evidence` entry whose `format` is +`nvidia-nvattest-boottime-json-v1`, returned by `/v1/Attest` when the request +sets `include_boottime_gpu_evidence`. Hash the decoded bytes exactly as +returned, not a re-serialized form. + +The guest also extends a `MrConfig` V2 **config commitment** into **PCR8** +(`PCR8 = sha384(0^48 || config_id)`). This is **optional** and exists only to +let a lightweight third-party verifier confirm `composeHash` + key-provider +*without* implementing PCR14 event-log replay: recompute +`expected_aws_config_pcr(MrConfig::V2 { compose_hash, app_id, key_provider, +key_provider_id })` and compare it to PCR8. dstack's own verifier and KMS do +**not** check PCR8 — they rely on PCR14 replay — so it is not part of the +required policy above. + +The `teeVariant` field is carried in the verified boot info for +observability; a relying party may additionally assert +`teeVariant == "dstack-aws-nitro-tpm"` against the verifier output, but the +authorization contract itself keys on the standard fields above. + +Same-account AWS KMS is not a trusted secret authority in this threat model if +the untrusted account admin can alter key policy, grants, or secret-bearing +operations. Use dstack KMS or another verifier-controlled KMS. + +## 5. Verify Endpoint Identity + +AWS EC2 attestation does not authenticate DNS, load balancers, or +admin-controlled proxies. Public clients must verify an attestation-bound +endpoint. + +For RA-TLS endpoints, capture the server certificate: + +```bash +openssl s_client -connect HOST:PORT -servername HOST -showcerts /dev/null | + awk '/BEGIN CERTIFICATE/{p=1} p{print} /END CERTIFICATE/{exit}' \ + > endpoint-cert.pem +``` + +Verify it: + +```bash +cargo run --bin dstack-verifier -- --verify-cert endpoint-cert.pem +``` + +Require the generated `endpoint-cert.pem.ratls-verification.json` to contain: + +```bash +jq -e ' + .is_valid == true and + .details.tee_variant == "dstack-aws-nitro-tpm" and + .details.app_info.os_image_hash_verified == true +' endpoint-cert.pem.ratls-verification.json +``` + +On AWS NitroTPM the `os_image_hash` binding is self-contained, so +`os_image_hash_verified` is `true` here; only then should you trust +`.details.app_info.os_image_hash`. Then apply the same allowlist policy to the +verified app identity (including `os_image_hash`). If the +deployment uses signed responses or an attested gateway instead of direct +RA-TLS, the response-signing key or gateway certificate must be bound to +verified NitroTPM evidence with equivalent policy checks. + +## 6. Release Decision + +An AWS EC2 NitroTPM deployment can be promoted only when: + +1. a reproducible rebuild from the clean, pinned release sources yields a + byte-identical `sha256sum.txt` (and therefore the same `os_image_hash`); +2. build input content is mirrored or otherwise available by content hash; +3. independently recomputed AWS PCRs and the UKI AuthentiCode hash match the + published build-output `aws-pcrs.json` side-car (when provided) and the + `boot_pcr_digest` in `measurement.aws.cbor`; +4. the hardening audit has zero failures and zero warnings, or every warning has + a documented release exception; +5. the registered AMI has a live EC2 smoke record for the exact AMI ID and + root snapshot in the release review package; +6. `/verify` returns a valid AWS `BootInfo`; +7. auth policy accepts only the intended OS, app, and KMS state; +8. endpoint identity is RA-TLS, signed-response, or attested-gateway bound. diff --git a/docs/bridge-networking.md b/docs/bridge-networking.md new file mode 100644 index 0000000000..7007d4c86f --- /dev/null +++ b/docs/bridge-networking.md @@ -0,0 +1,324 @@ +# Bridge Networking for VMM + +By default, dstack-vmm uses **user** networking (QEMU's built-in SLIRP stack, no host setup required). Bridge networking is an alternative that provides better performance for high-connection workloads by using kernel-level bridging with TAP devices. + +## When to use bridge networking + +- High connection concurrency (user-mode networking becomes CPU-bound at ~25K+ concurrent connections) +- Workloads that need full L2 network access +- Environments where VMs need to be directly reachable on the LAN + +## Configuration + +### VMM global config (`vmm.toml`) + +```toml +[cvm.networking] +mode = "bridge" +bridge = "virbr0" +``` + +### Per-VM override + +Individual VMs can override the global networking mode via: +- **CLI**: `vmm-cli.py deploy --net bridge`, `--net user`, or `--net macvtap` +- **Web UI**: Networking dropdown in the deploy dialog +- **API**: `networking: { mode: "bridge" }` in `VmConfiguration` + +The bridge interface name comes from the global config unless the node lists it in `cvm.allowed_bridges`. VMs may also override the vhost and queue settings — see [network-data-plane.md](network-data-plane.md). + +## Host setup + +### Option A: Using libvirt default network + +libvirt's default network provides a bridge (`virbr0`) with DHCP (dnsmasq) and NAT out of the box. + +```bash +# Install libvirt (if not already present) +sudo apt install -y libvirt-daemon-system + +# Ensure default network is active +sudo virsh net-start default 2>/dev/null +sudo virsh net-autostart default +``` + +Verify: +```bash +ip addr show virbr0 +# Should show 192.168.122.1/24 + +virsh net-dhcp-leases default +# Lists DHCP leases for connected VMs +``` + +### Option B: Manual bridge without libvirt + +Create a bridge with systemd-networkd and run a standalone DHCP server. + +**1. Create the bridge:** + +```bash +# /etc/systemd/network/10-dstack-br.netdev +[NetDev] +Name=dstack-br0 +Kind=bridge + +# /etc/systemd/network/11-dstack-br.network +[Match] +Name=dstack-br0 + +[Network] +Address=10.0.100.1/24 +ConfigureWithoutCarrier=yes +IPMasquerade=both +``` + +```bash +sudo systemctl restart systemd-networkd +``` + +**2. Enable IP forwarding:** + +```bash +echo "net.ipv4.ip_forward=1" | sudo tee /etc/sysctl.d/99-dstack-bridge.conf +sudo sysctl -p /etc/sysctl.d/99-dstack-bridge.conf +``` + +**3. Run a DHCP server (dnsmasq):** + +```bash +sudo apt install -y dnsmasq +``` + +Create dnsmasq config: + +```ini +# /etc/dnsmasq.d/dstack-br0.conf +interface=dstack-br0 +bind-interfaces +dhcp-range=10.0.100.10,10.0.100.254,255.255.255.0,12h +dhcp-option=option:router,10.0.100.1 +dhcp-option=option:dns-server,8.8.8.8,1.1.1.1 +``` + +```bash +sudo systemctl restart dnsmasq +``` + +**4. Firewall rules (nftables):** + +When the host firewall has a restrictive INPUT policy (e.g. `drop`), the bridge's DHCP and DNS traffic will be silently blocked. libvirt handles this automatically for virbr0, but a standalone bridge needs explicit rules. + +```bash +BRIDGE=dstack-br0 +SUBNET=10.0.100.0/24 + +# Allow DHCP and DNS from VMs (INPUT/OUTPUT) +sudo nft add rule ip filter INPUT iifname "$BRIDGE" udp dport 67 counter accept +sudo nft add rule ip filter INPUT iifname "$BRIDGE" udp dport 53 counter accept +sudo nft add rule ip filter INPUT iifname "$BRIDGE" tcp dport 53 counter accept +sudo nft add rule ip filter OUTPUT oifname "$BRIDGE" udp dport 68 counter accept +sudo nft add rule ip filter OUTPUT oifname "$BRIDGE" udp dport 53 counter accept + +# Allow forwarding for VM traffic +sudo nft add rule ip filter FORWARD ip saddr "$SUBNET" iifname "$BRIDGE" counter accept +sudo nft add rule ip filter FORWARD ip daddr "$SUBNET" oifname "$BRIDGE" ct state related,established counter accept +sudo nft add rule ip filter FORWARD iifname "$BRIDGE" oifname "$BRIDGE" counter accept + +# NAT masquerade for outbound traffic +sudo nft add rule ip nat POSTROUTING ip saddr "$SUBNET" ip daddr 224.0.0.0/24 counter return +sudo nft add rule ip nat POSTROUTING ip saddr "$SUBNET" ip daddr 255.255.255.255 counter return +sudo nft add rule ip nat POSTROUTING ip saddr "$SUBNET" ip daddr != "$SUBNET" counter masquerade +``` + +If the host uses libvirt, nftables rules may be in custom chains (`LIBVIRT_INP`, `LIBVIRT_FWO`, etc.) instead of the default `INPUT`/`FORWARD` chains. Adjust the chain names accordingly. + +To make these rules persistent across reboots, save them with `nft list ruleset > /etc/nftables.conf` or add them to a systemd service. + +**5. Update vmm.toml:** + +```toml +[cvm.networking] +mode = "bridge" +bridge = "dstack-br0" +``` + +### netd is required + +Bridge networking needs `netd`, the privileged helper that owns every host +interface a bridge or macvtap NIC uses. It is the same binary: + +```bash +sudo dstack-vmm --config vmm.toml netd +``` + +Nothing else on the node needs `CAP_NET_ADMIN`: the VMM itself still runs +unprivileged, and `netd` holds the privilege behind a Unix socket whose +filesystem permissions authorize callers. + +This used to be conditional — `netd` built the TAP when libvirt filtering was on +or when the NIC wanted more than one queue pair, and otherwise QEMU's setuid +`qemu-bridge-helper` did. Two owners meant two answers to the same questions: +which netdev QEMU gets, whether vhost is really on, and what a bridge NIC's TAP +is built with. So a bridge NIC's host interface has one owner now, on every +node. + +`qemu-bridge-helper` is no longer used, and `/etc/qemu/bridge.conf` no longer +needs an `allow` line for the bridge. + +## How it works + +- `netd` creates a persistent TAP, attaches it to the bridge, binds the nwfilter if the node filters, and the VMM passes `-netdev tap,id=net0,ifname=,...` +- Guest MAC address is derived from SHA256 of the VM ID, with an optional configurable prefix (stable across restarts for DHCP IP consistency) +- The host DHCP server (dnsmasq) assigns an IP to the VM +- The TAP outlives QEMU and is deleted when the VMM tears the VM's networking down, so a VM that crashes does not leave its filter rules attached to a name the next VM could take +- Every interface `netd` creates records which VM of which VMM instance it belongs to, in the kernel's interface alias — see [Who owns an interface](#who-owns-an-interface) +- The VMM process needs neither root nor `CAP_NET_ADMIN`; `netd` holds that privilege in a separate service + +### MAC address prefix + +You can configure a fixed MAC address prefix (0–3 bytes) in vmm.toml: + +```toml +[cvm.networking] +mode = "bridge" +bridge = "dstack-br0" +mac_prefix = "52:54:00" +``` + +The remaining bytes are derived from the VM ID hash. The prefix applies to all networking modes, not just bridge. The locally-administered bit is always set on the first byte. + +## Operational notes + +### Do not restart the bridge while VMs are running + +`virsh net-destroy`/`net-start` (or removing/recreating the bridge) will detach all TAP interfaces from the bridge, breaking VM networking. If this happens, affected VMs must be restarted. + +### Firewall considerations + +- libvirt automatically injects nftables rules for INPUT (DHCP/DNS), FORWARD, and NAT masquerade into its own chains (`LIBVIRT_INP`, `LIBVIRT_FWO`, `LIBVIRT_FWI`, `LIBVIRT_PRT`) +- A standalone bridge requires **all** of these rules to be added manually (see Option B step 4 above). The most common failure mode is a restrictive INPUT policy silently dropping DHCP requests from VMs — if VMs on a custom bridge don't get an IP, check `sudo nft list chain ip filter INPUT` first +- Docker's nftables chains (`DOCKER-FORWARD`) run before libvirt's but do not block virbr0 traffic +- Use `setup-bridge.sh check --bridge ` to diagnose missing rules + +### Which NIC a port mapping uses + +A port mapping says which NIC its traffic enters through: + +```bash +vmm-cli.py deploy ... --port udp:0.0.0.0:7483:51820@0 --port tcp:127.0.0.1:7484:8001@0 +``` + +Leave `@` off and the VMM picks the first user-mode NIC — where QEMU's +`hostfwd=` entries have always gone. If the VM has no user-mode NIC, the mapping +has no publishing backend and the launch log names it as stranded. A single-NIC +user-mode VM never needs the suffix. + +With several NICs the choice used to be made silently, and not always the way an +operator would have. A bridge NIC for external traffic beside a user-mode NIC for +management — the topology multi-NIC was added for — put every published port on +the *management* NIC: the traffic reached the guest, but over slirp, bypassing +whatever the bridge NIC's nwfilter was there to enforce and hiding the client's +address behind the slirp gateway. A second user-mode NIC could never publish +anything at all, because only the first was ever selected. + +A mapping resolves to at most one NIC. The only backend that can carry it is +QEMU user networking through `hostfwd=`; `netd` builds bridge interfaces but +does not publish host ports. + +### Which ports a bridge NIC can publish + +QEMU publishes a port with `hostfwd=` on a user-mode NIC, and that is the only +mechanism this host has. **The `netd` in this repository builds interfaces; it +does not forward host ports**, so a bridge NIC cannot carry a port mapping. + +`--port …@` therefore only ever names a user-mode NIC. Pinning to a bridge, +macvtap or custom NIC is refused at deployment, where the caller is there to be +told. An unpinned mapping goes to the first user-mode NIC; a VM that has none is +not refused — it may have been deployed before this — but every mapping it +strands is named in the launch log. + +## Who owns an interface + +`netd` names an interface `dt<12 hex>`, a digest of (VMM instance, VM, NIC +index). That answers "where is this VM's interface" but not "whose is this +interface" — and the second question is the one a leaked interface poses. So +`netd` also records the identity on the interface itself: + +```console +$ ip -d link show dtc41d9e0b7a52 | grep alias + alias dstack1:0:path-3f9a1c8e7d2b4a60:0a1b2c3d4e5f6071 +``` + +The kernel holds that for exactly the interface's lifetime, so unlike a file on +disk it cannot be written late, lost, or left behind. It is a hint, never an +authority: a record is believed only when re-deriving the interface name from +it reproduces the name it is written on, so a forged, truncated or ambiguous +record reads the same as no record at all. + +Teardown does not need it — a sweep derives the names it deletes. What needs it +is an operator, and a host running several VMM instances, where it is the only +thing that tells one instance's interfaces from another's. + +```bash +# What netd holds on this host +sudo dstack-vmm netd list + +# Everything one VM holds, for a VM whose VMM will never ask again +sudo dstack-vmm netd remove-vm --instance path-3f9a1c8e7d2b4a60 --vm 0a1b2c3d4e5f6071 +``` + +### When a release does not land + +The VMM writes `.netd-pending` into the VM's directory before it asks `netd` +to build anything, and deletes it only after `netd` has swept every interface +that VM could hold. The marker is the only record the VMM keeps of what `netd` +may hold, so it survives failed launches and changes to a topology that no +longer uses `netd`. A VM without it has nothing to release, and its stop, +removal and launch never contact `netd` for one. + +A sweep derives each of the 256 names the VM's identity could produce, so it +needs no record of which NICs existed: it also reaches an interface a crash left +behind, or one whose NIC the manifest has since dropped. It is idempotent, and +every path that releases a VM retries it until it lands: + +- a launch sweeps before it prepares; +- a stop that could not reach `netd` leaves the marker, and the VMM checks + stopped VMs with a marker every minute and sweeps them; +- a removal keeps the VM's directory, and the VM marked as being removed, and + retries the sweep with backoff until `netd` answers. The directory is deleted + after that, with `.removing` last, so a removal interrupted by a crash is + resumed by the next VMM start. + +On an unfiltered node, an unavailable `libvirtd` does not make an otherwise +successful TAP sweep fail. Filtered nodes still require confirmation that their +nwfilter bindings have been released; deleting the TAP alone is not sufficient. + +What no VMM will retry is an interface whose VM directory an operator deleted +by hand, or one recorded under an instance ID no VMM uses any more. `netd list` +shows both, with the instance and VM they are recorded under: + +```bash +sudo dstack-vmm netd list +sudo dstack-vmm netd remove-vm --instance --vm +sudo dstack-vmm netd remove-interface dtc41d9e0b7a52 +``` + +Changing `cvm.instance_id` — or `run_path`, which it is derived from — strands +interfaces the same way. Running VMs keep working until they stop, and +`netd list` still shows the old instance ID, which is what `remove-vm` needs. + +### Mixing networking modes + +Bridge and user-mode VMs can coexist. Set the global default in `vmm.toml` and override per-VM as needed: + +```bash +# Global default is bridge, but deploy this VM with user networking +vmm-cli.py deploy --name my-vm --image dstack-0.5.6 --compose app.yaml --net user +``` + +### vhost-net and multiqueue + +Bridge NICs can run on the host kernel's vhost-net data plane and expose several virtio-net queue pairs. Both are off by default and enabled per node or per VM — see [network-data-plane.md](network-data-plane.md) for the knobs, the enablement checklist, the mode support matrix, and how to pick a queue count. + +vhost-net works in a TDX guest: the virtio rings and buffers live in shared, unencrypted memory so that a host-side backend can reach them, which is the same mechanism `vhost-vsock-pci` has always relied on. diff --git a/docs/building-guest-os.md b/docs/building-guest-os.md new file mode 100644 index 0000000000..0388596c1c --- /dev/null +++ b/docs/building-guest-os.md @@ -0,0 +1,264 @@ +# Build the dstack guest OS + +This guide builds the bootable dstack guest-OS release artifacts from source. +It is for OS developers, release maintainers, and operators who want a custom +image. You do **not** need to build an image for normal self-hosted onboarding: +`dstackup install` downloads and verifies a published guest-OS release by +default. + +> [!IMPORTANT] +> **mkosi is the default and recommended OS backend.** The Yocto backend under +> `os/yocto/` is **deprecated**. It remains only so existing Yocto images can +> still be rebuilt. Do not use it for new images, new features, or release +> work. See [Deprecated: Yocto backend](#deprecated-yocto-backend). +> +> The mkosi build still reads some patches, units, and scripts from +> `os/yocto/`, so that directory must not be deleted yet; see +> [`../os/README.md`](../os/README.md). + +## What the build produces + +The default `prod` build produces: + +- a bare-metal/CVM bundle for Intel TDX and, when the SEV firmware artifact is + available, AMD SEV-SNP; +- a UKI disk-image bundle for the GCP confidential-VM boot path; +- dm-verity rootfs data, launch-measurement material, checksums, and the unified + `digest.txt` OS identity. + +The mkosi backend lives in `os/mkosi/`. Backend-independent rootfs payload, +artifact contract, measurement, and release packaging live outside the backend; +see [`../os/README.md`](../os/README.md). Backend internals, the +reproducibility model, and the component cache are described in +[`../os/mkosi/README.md`](../os/mkosi/README.md). + +## Prerequisites + +Use an x86-64 Linux host with: + +- Git; +- Docker Engine, usable by the current user, that can run `--privileged` + containers (mkosi needs loop devices, device-mapper, and mounts); +- outbound HTTPS access for the pinned Debian snapshot, upstream source + archives, and Rust crates; +- tens of gigabytes of free disk space on a regular filesystem (not overlayfs) + for the build directory. + +No Rust, Go, C, or C++ toolchain is needed on the host; every compiler is pinned +and runs inside mkosi's build overlay. + +TEE hardware is not required to build the image. It is required only when you +boot and attest the resulting image on the corresponding platform. + +Check the basics before starting: + +```bash +docker version +git --version +df -h . +``` + +## Quick build + +From a fresh checkout: + +```bash +git clone https://github.com/Dstack-TEE/dstack.git +cd dstack +make os-image +``` + +`make os-image` runs one complete, cold production image build in a container +that pins mkosi and the host tools it drives. It needs no submodules and is +equivalent to: + +```bash +./os/mkosi/repro-build/repro-build.sh +``` + +The build refuses to run from a dirty worktree, because the recorded source +revision would not describe the compiled sources. Commit or stash changes +first. (Native `os/mkosi/build.sh` builds also accept `DSTACK_ALLOW_DIRTY=1`, +which records the revision as `-modified`; the containerized build does not +forward it.) + +A cold production build takes roughly 30–45 minutes on a 16-job host, +depending mostly on network speed. + +## Outputs + +Release artifacts are written under: + +```text +os/mkosi/repro-build/build/out/prod/ +├── dstack-/ +├── dstack-.tar.gz +├── dstack--uki.tar.gz +└── dstack--kernel-devel.tar.gz +``` + +To use a different build directory, run +`./os/mkosi/repro-build/repro-build.sh -o DIR`. When the build finishes it +prints the `os_image_hash` and the SHA-256 of both archives. + +The bare-metal archive includes the kernel, initramfs, OVMF firmware, +partitioned dm-verity rootfs, platform measurement CBOR files, +`sha256sum.txt`, `digest.txt`, and `metadata.json`. The UKI archive +includes the bootable `disk.raw` plus its identity and measurement files. The +kernel-devel archive holds the build trees for out-of-tree modules (see below). + +Inspect and verify an archive with: + +```bash +mkdir -p /tmp/dstack-image +tar -xzf os/mkosi/repro-build/build/out/prod/dstack-.tar.gz \ + -C /tmp/dstack-image +cd /tmp/dstack-image/dstack- +sha256sum -c sha256sum.txt +test "$(sha256sum sha256sum.txt | awk '{print $1}')" = "$(cat digest.txt)" +``` + +## Build both production and development flavors + +Production is the default. To build both variants once: + +```bash +FLAVORS="prod dev" ./os/mkosi/repro-build/repro-build.sh +``` + +The development archive is written to `out/dev/dstack-dev-.tar.gz` +and records `"is_dev": true` in `metadata.json`. + +## Kernel headers for out-of-tree modules + +The guest rootfs ships the kernel's build tree at +`/usr/src/linux-headers-`, linked from +`/lib/modules//build`, so tools that compile against the running +kernel (for example eBPF tooling) find it at the usual Debian location when it +is bind-mounted into a container. Beside it, `/usr/src/nvidia-` holds +the interface headers and `Module.symvers` of the NVIDIA open modules the image +loads, in the open-gpu-kernel-modules layout, for modules that call into +`nvidia.ko`. Both trees are also published for building out-of-tree modules +outside the CVM: + +- `dstack--kernel-devel.tar.gz`, the exported trees, and +- `ghcr.io/dstack-tee/dstack-kernel-builder:`, the same trees plus a + compiler from the pinned Debian snapshot the kernel was built with, with + `KDIR` and `NVIDIA_HEADERS` set. + +```dockerfile +FROM ghcr.io/dstack-tee/dstack-kernel-builder: AS kmod +COPY mymod/ /src +RUN make -C $KDIR M=/src modules + +FROM alpine +COPY --from=kmod /src/mymod.ko /opt/ +``` + +A module that calls into `nvidia.ko` also takes its include directories from +`$NVIDIA_HEADERS` and passes +`KBUILD_EXTRA_SYMBOLS=$NVIDIA_HEADERS/kernel-open/Module.symvers`, without which +modpost rejects its references to the driver's symbols. + +To build the image locally from a release archive, run +`os/image/kernel-builder/build.sh `. + +The in-image trees are part of the dm-verity rootfs and therefore of +`os_image_hash`; the two release artifacts are not in `sha256sum.txt`. A module loaded by an application (which needs +`CAP_SYS_MODULE`) is covered by the container image digest and therefore the +compose hash, but it is not measured separately and dstack does not enforce +module signatures. + +## Check reproducibility + +For a release candidate: + +```bash +make os-repro-check +``` + +This performs two cold production builds in different build paths and with +different job counts, then compares both release archives byte for byte. It +takes roughly twice the resources of a single build. The first leg's artifacts +remain under `os/mkosi/repro-build/build/a/`. + +## Incremental backend development + +The containerized build is the recommended release path. On a host with the +pinned mkosi version (see `MKOSI_VERSION` in `os/mkosi/versions.env`) and the +packages reported by `mkosi --directory os/mkosi dependencies`, and with root +privileges (or a working user namespace), the backend can be driven directly: + +```bash +./os/mkosi/build.sh lint # static contract, seconds +./os/mkosi/build.sh image "$PWD/os/mkosi/build" # cached iteration build +./os/mkosi/build.sh --no-cache image "$PWD/os/mkosi/build" # cold build +./os/build.sh --flavors "prod dev" --build-dir "$PWD/os/mkosi/build" +``` + +A native `image` build reuses a component-output cache by default and skips the +release tarballs; `disk.raw`, the measurements, and `metadata.json` are still +produced. Pass `--archive` to get the tarballs from a cached build, or +`--no-cache` for a release-equivalent cold build. See +[`../os/mkosi/README.md`](../os/mkosi/README.md) for cache details. + +The generic entrypoint `os/build.sh` dispatches to `os//build.sh` and +defaults to `mkosi`. + +## Troubleshooting + +### Docker permission is denied + +Ensure `docker version` works as the same non-root user that owns the +checkout. The build container runs privileged and hands ownership of the build +directory back to the calling user when it exits. + +### The workspace is on overlayfs + +mkosi assembles its build root as an overlayfs, which cannot be stacked on +another overlayfs. Choose a build directory on a regular filesystem with +`./os/mkosi/repro-build/repro-build.sh -o DIR`. + +### A fetch fails + +Confirm outbound network and DNS access, then rerun the same command. Package +downloads come from an immutable Debian snapshot, so a retry fetches identical +content. + +### The disk fills up + +The disposable build directories are: + +```text +os/mkosi/repro-build/build/ +os/mkosi/build/ +~/.cache/dstack/mkosi-dev/ # native component cache +``` + +They are ignored by Git (or live outside the checkout) and can be removed when +no build is running. Copy the release archives elsewhere first if you need +them. + +## Deprecated: Yocto backend + +> [!WARNING] +> The Yocto backend is deprecated and will be removed. Do not use it for new +> images or releases, and do not add features to it. Every build entrypoint +> prints a deprecation warning. Files under `os/yocto/` that the mkosi build +> still reads remain live inputs of the default image until they are moved. + +The Yocto backend is kept only so existing Yocto-built images can still be +rebuilt and verified. Its entrypoints have moved to explicitly named targets: + +| Deprecated command | Replacement | +|--------------------|-------------| +| `make os-image-yocto` | `make os-image` | +| `make os-repro-check-yocto` | `make os-repro-check` | +| `make os-yocto` / `./os/build.sh --backend yocto` | `make os` / `./os/build.sh` | +| `make os-deps` | not needed; mkosi uses no submodules | + +`make os-image-yocto` initializes the eight Yocto dependency submodules and runs +`os/yocto/repro-build/repro-build.sh -n` in its pinned Ubuntu builder container. +Archives are written to `os/yocto/repro-build/dist/`; use +`RELEASE_FLAVORS="prod dev"` to build both flavors. See +[`../os/yocto/README.md`](../os/yocto/README.md) for the remaining details. diff --git a/docs/certbot-dns-persist-01.md b/docs/certbot-dns-persist-01.md new file mode 100644 index 0000000000..c3b2643130 --- /dev/null +++ b/docs/certbot-dns-persist-01.md @@ -0,0 +1,240 @@ +# Certificate issuance without a DNS credential (`dns-persist-01`) + +`dns-01` asks certbot to write a fresh `_acme-challenge` TXT record for every +order, so whatever runs certbot holds a DNS API token with write access to the +zone, forever. In dstack that token lives inside the gateway CVM. Attestation +covers what the CVM is running, but a token is a token: anything that gets hold +of it can rewrite the zone, including records that have nothing to do with +certificates. + +`dns-persist-01` moves the proof out of the issuance loop. The zone owner +publishes one record naming the CA and the ACME account allowed to issue: + +```dns +_validation-persist.example.com. IN TXT "letsencrypt.org; accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/1234567890" +``` + +The account key proves who is asking, the record proves the zone owner agreed, +and neither changes between orders. certbot reads DNS and never writes it, so +the CVM holds no DNS credential and the zone can be hosted anywhere — no +Cloudflare account, no API token, no provider integration. + +> **Experimental.** `dns-persist-01` is specified in +> [draft-ietf-acme-dns-persist-01][draft], which is still changing: an open +> working-group issue may add a client-key-derived value to the record, and +> Let's Encrypt has said it will not deploy the challenge to production until +> that is resolved. It is live on Let's Encrypt **staging** and in +> [Pebble][pebble]. Treat the record format as unstable, and expect to +> republish when the draft settles. + +[draft]: https://datatracker.ietf.org/doc/html/draft-ietf-acme-dns-persist-01 +[pebble]: https://github.com/letsencrypt/pebble + +## What the record means + +| Part | Effect | +| --- | --- | +| `letsencrypt.org` | Issuer Domain Name. A CA ignores records naming a different issuer, so one label can hold records for several CAs. | +| `accounturi=` | The ACME account authorized to issue. Compared byte for byte — no case folding, no URI normalization. | +| `policy=wildcard` | Extends the record to `*.example.com`. Without it the CA authorizes `example.com` alone and refuses wildcard orders. | +| `persistUntil=` | Optional UNIX timestamp after which the CA stops accepting the record. | + +A wildcard order authorizes from its base name — `*.example.com` is validated +against `_validation-persist.example.com`, not +`_validation-persist.*.example.com` — so one record covers a name and its +wildcard. + +Two things about the syntax bite in practice, because a CA rejects the whole +record rather than ignoring the offending part: **no trailing semicolon**, and +**no whitespace inside a value**. certbot renders records that satisfy both; +copy them verbatim rather than retyping. + +The scope stops at the names above. Let's Encrypt does not walk up the tree, so +a record on `example.com` does not authorize `sub.example.com` — give each base +name its own record. + +## Standalone certbot + +`certbot` never writes DNS in this mode, so setup is: create the account, read +the records off it, publish them, then issue. + +```toml +# certbot.toml +workdir = "/var/lib/certbot" +acme_url = "https://acme-staging-v02.api.letsencrypt.org/directory" +challenge = "dns-persist-01" +issuer_domain_name = "letsencrypt.org" +# auto_set_caa promises certbot keeps CAA in sync, which it cannot do without +# write access. Leave it off and publish the CAA records below by hand. +auto_set_caa = false +domains = ["example.com", "*.example.com"] +renew_interval = 3600 +renew_days_before = 10 +renew_timeout = 120 +# Capped at half of renew_timeout, so this one waits 60s, not 300s. The whole +# order -- the wait, the authorizations, finalize, and fetching the certificate +# -- has to fit inside renew_timeout, and a wait that outlasts it takes the +# timeout with it, losing the warning naming the record that was missing. +# Raising this alone changes nothing; raise renew_timeout with it. +max_dns_wait = 300 +``` + +`cf_api_token` is unused and can be left out; certbot warns if one is set. + +```console +$ certbot init -c certbot.toml +INFO certbot::bot: creating new ACME account +INFO certbot::bot: created new ACME account: https://acme-staging-v02.api.letsencrypt.org/acme/acct/1234567890 + +$ certbot dns-records -c certbot.toml +_validation-persist.example.com. IN TXT "letsencrypt.org; accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/1234567890; policy=wildcard" +example.com. IN CAA 0 issue "letsencrypt.org;validationmethods=dns-persist-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/1234567890" +example.com. IN CAA 0 issuewild "letsencrypt.org;validationmethods=dns-persist-01;accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/1234567890" +``` + +Publish all three, wait for them to propagate, then issue: + +```console +$ certbot renew --once -c certbot.toml +INFO certbot::acme_client: requesting new certificates for example.com, *.example.com +INFO certbot::bot: created new certificate +``` + +Renewals need nothing further. The record stays, and `certbot renew` reuses it +for every order. + +The CAA records are optional but recommended — they stop any other account, at +Let's Encrypt or elsewhere, from being issued for your name. Note the +`validationmethods=dns-persist-01` in them: a CAA record left pinned to +`dns-01` refuses every `dns-persist-01` order, so switching methods means +updating CAA and the validation record together. + +### When issuance fails + +certbot checks its own resolver before starting an order, and says exactly what +it expected to find: + +``` +WARN certbot::acme_client: no TXT record at _validation-persist.example.com matches the expected value: letsencrypt.org; accounturi=https://acme-staging-v02.api.letsencrypt.org/acme/acct/1234567890; policy=wildcard +Error: order is invalid: API error: Checking DNS-PERSIST-01 challenge TXT record with issuer-domain-name "letsencrypt.org": accounturi mismatch: expected "https://acme-staging-v02.api.letsencrypt.org/acme/acct/1234567890", got "https://acme-staging-v02.api.letsencrypt.org/acme/acct/9876543210" (urn:ietf:params:acme:error:unauthorized) +``` + +The check is advisory and never blocks an order: certbot's resolver is not the +CA's, and its expectation can be stricter than what the CA would accept. A +warning with a successful issuance underneath it is a resolver difference, not +a problem. A record that genuinely does not match costs the whole DNS budget +before the order is sent, because the check waits it out first -- that is +`max_dns_wait`, or half of `renew_timeout` when that is smaller, which for the +configuration above is 60s. certbot logs the budget it settled on at `debug`. + +If the CA rejects the order, compare the published record against +`certbot dns-records` character by character. The usual causes are a stale +`accounturi` after the account was recreated, a missing `policy=wildcard` on a +wildcard order, and an issuer domain name that does not match the CA. + +## dstack-gateway + +A ZT domain picks its method with the `challenge` field, which defaults to +`dns-01` — existing domains are unaffected: + +```json +{ "domain": "app.example.com", "port": 443, "challenge": "dns-persist-01" } +``` + +Such a domain needs no `dns_cred_id`, and the gateway CVM never receives a DNS +credential for it. `GetZtDomain` and `ListZtDomains` return the records to +publish in `required_dns_records`, and the gateway logs them whenever it cannot +write DNS itself: + +``` +WARN cert[app.example.com]: publish this record by hand: _validation-persist.app.example.com. IN TXT "letsencrypt.org; accounturi=...; policy=wildcard" +``` + +The gateway issues for `*.{domain}` only, so each domain needs one validation +record with `policy=wildcard`. + +### Setup order + +The records name the ACME account, so the account comes first: + +1. `SetCertbotConfig` — `acme_url`, and `issuer_domain_name` if the CA is not + Let's Encrypt. +2. `RotateAcmeCredentials` — registers the account and returns its `account_uri`. + It needs no ZT domain: registration proves nothing about a domain. Every call + registers a *new* account, so call it once here; running it again later is a + rotation, with the consequences described below. +3. `AddZtDomain` with `challenge: "dns-persist-01"`. No `dns_cred_id`: the + domain needs none, and the gateway CVM never receives one for it. +4. Read the records — the dashboard shows them when the domain is added and + again under its **Records** button, and `GetZtDomain`, `ListZtDomains` and + the gateway log all carry them — then publish the `_validation-persist` TXT + record, plus the CAA records if you want issuance pinned to this account. +5. `RenewZtDomainCert`. Renewals from here need nothing further. + +Adding another dns-persist-01 domain later starts at step 3: the account already +exists, so the new domain's records are available as soon as it is. A domain's +challenge is chosen when it is added — in the dashboard's ZT-Domain form as well +as over the API — and carried forward by every edit. `UpdateZtDomain` replaces +the whole record, so `challenge` is optional there and omitting it means "leave +it as it is": a caller that predates the field — a cached dashboard bundle, a +script, an older SDK — cannot downgrade a `dns-persist-01` domain to `dns-01` by +editing something else, which its hand-published CAA would then refuse. Send the +field explicitly to switch a domain over. + +### Naming the CA + +For a non-production ACME server, set `issuer_domain_name` in the global certbot +config — `Admin.SetCertbotConfig`, or the field of that name in the dashboard's +Certbot Configuration — to whatever that server puts in `issuer-domain-names`, +`pebble.letsencrypt.org` for Pebble. Empty means `letsencrypt.org`. + +It also names the CA in the CAA records certbot writes for `dns-01` domains, so +one setting covers both challenges rather than pinning CAA to Let's Encrypt +while orders go somewhere else. `acme_url` is one setting for the whole +deployment; this follows it. + +The value is checked when it is set. It ends up verbatim inside an RFC 8659 +`issue-value`, and publishing CAA deletes the records it replaces before writing +the new ones, so a name carrying a space or a `;` would leave the zone holding a +malformed `issue` property with nothing valid behind it — CAA that forbids every +issuer. Anything that is not a DNS name is refused by `SetCertbotConfig`, and by +`certbot` at startup. + +Publishing CAA installs a temporary `;` guard, deletes the records it replaces, +writes the new ones and drops the guard. A run interrupted part-way leaves the +guard behind, which denies every issuer until a later run finishes the job — so +each run now sweeps stale guards before installing its own, and a rerun is +enough to recover. + +### How long the check waits + +The self-check before each order waits for the record to become visible, but +never longer than half of `renew_timeout`, the budget for the whole renewal. +Past that the outer timeout fires first and the renewal ends as `certificate +request timed out` with no mention of the record it could not find — the +opposite of what the check is for. Both values defaulted to 300s in the gateway +(and the CLI wrapped a 300s wait in a 120s budget), so this was the default +behaviour rather than an edge case. + +Two operations behave differently on these domains: + +- **`SetCaa`** skips them. There is nothing to reconcile without write access; + the records are logged instead, and the summary reports how many were left to + the operator. +- **`RotateAcmeCredentials`** is not self-service. Rotation moves the cluster + to a new ACME account, and every `_validation-persist` record still names the + old one, so orders for those domains fail until the operator republishes. The + response returns the new records in `required_dns_records` and the gateway + logs them; publish before the next renewal comes due. + + A rotation that registers the account but cannot re-pin every `dns-01` + domain's CAA still succeeds — the account exists and the cluster is on it — + and names those domains in `repin_failed_domains`. Finish with `SetCaa` + rather than another rotation, which would register yet another account + against a rate-limited quota. The dashboard reports both lists in one dialog + after a rotation, with a **Run SetCaa** button for the second. + +## Related + +- [dstack-gateway](dstack-gateway.md) — gateway architecture and TLS termination +- [deployment.md](deployment.md#4-zero-trust-https-optional) — the `dns-01` setup this replaces diff --git a/docs/confidential-ai.md b/docs/confidential-ai.md new file mode 100644 index 0000000000..56fd3c1130 --- /dev/null +++ b/docs/confidential-ai.md @@ -0,0 +1,262 @@ +# Confidential AI + +Run AI workloads where the infrastructure operator can't see your data. dstack uses Intel TDX and NVIDIA Confidential Computing to encrypt everything in memory—your prompts, model weights, and intermediate computations stay private. + +## What You Can Build + +- **Private inference** - Users verify their prompts never leave encrypted memory +- **Training on sensitive data** - Fine-tune models without exposing training data to operators +- **Trustworthy agents** - Prove your agent code can't exfiltrate user data + +The key difference from self-hosting: users don't have to trust you. They can cryptographically verify what code runs and that the hardware is genuine. + +## What Makes It Confidential + +Four protections keep data confidential: + +**TLS terminates inside the VM.** Your HTTPS connection ends inside the Confidential VM, not at some load balancer outside. The operator never sees plaintext traffic. + +**CPU memory is encrypted.** Intel TDX encrypts all RAM with hardware keys. The hypervisor can't read it, the host OS can't read it, even physical access to the DIMM won't help. + +**GPU memory is encrypted.** On H100/H200/Blackwell with NVIDIA CC mode, GPU memory is encrypted too. Model weights and activations stay protected during inference and training. + +**Disk is encrypted.** Anything written to storage uses keys derived from the TEE. The storage backend only sees ciphertext. + +Attestation lets you verify which application handles that data. You can use CPU attestation to check that the deployed application configuration matches the one you reviewed. See [how attestation works](#how-attestation-works). + +## How Attestation Works + +The application runs in a confidential VM and uses the NVIDIA driver inside that VM to send work to the GPUs. CPU attestation lets you check the VM's software, including that driver, and the application configuration. GPU attestation describes the hardware and its confidential-computing state at the time of the check. + +```mermaid +graph LR + CPU["Confidential VM
Application and NVIDIA driver"] -->|submits work| GPU["Confidential GPUs"] + CPUProof["CPU attestation"] -.->|covers software and configuration| CPU + GPUProof["Boot-time GPU attestation"] -.->|covers hardware and protection state| GPU + GPUProof -.->|recorded in launch log| CPUProof +``` + +In a multi-GPU VM, the boot-time check covers every attached GPU. Together, the CPU and GPU evidence let you verify which software submits the work and the GPU protections in place at launch. The check does not prove that the same GPUs stay attached for the VM's lifetime. + +For the guarantees and their limits, see [GPU Security for AI Workloads](./security/security-model.md#gpu-security-for-ai-workloads). + +### Verifying the Whole Deployment + +A service can show "CPU verified" and "GPU verified" while sending your prompts to an unchecked GPU. For example, the CPU quote could come from a genuine confidential VM and the GPU report from a separate test machine. Even if both reports answer the same fresh challenge (nonce), each still describes its own environment. + +With the default policy, the dstack OS makes GPUs available to the workload only after every attached GPU passes the boot-time check. A failed check stops startup before the workload can receive prompts. On Intel TDX, the result is recorded in the VM's launch log, which the signed CPU quote covers. See [Verification](#verification) for how to check it. + +Your data also needs a protected path to the application you reviewed. If an untrusted proxy terminates TLS outside the VM, it can read your prompts before forwarding them to the confidential workload. Verify where TLS terminates and review how the application handles your data. See [Verification](#verification) and [Phala Cloud domain attestation](https://docs.phala.com/phala-cloud/networking/domain-attestation). + +## Private Inference + +Deploy vLLM behind a signing proxy. Users can verify responses came from your TEE, not a compromised server. + +```yaml +services: + vllm: + image: vllm/vllm-openai:latest + command: --model Qwen/Qwen2.5-7B-Instruct --host 0.0.0.0 + deploy: + resources: + reservations: + devices: + - driver: nvidia + capabilities: [gpu] + + proxy: + image: phalanetwork/vllm-proxy:latest + ports: + - "8000:8000" + volumes: + - /var/run/dstack.sock:/var/run/dstack.sock + environment: + - VLLM_BASE_URL=http://vllm:8000 + - MODEL_NAME=Qwen/Qwen2.5-7B-Instruct + - TOKEN=${TOKEN} +``` + +The data flow looks like this: + +```mermaid +graph LR + User -->|TLS| Proxy + subgraph TEE[Confidential VM] + Proxy[vllm-proxy] + Proxy -->|HTTP| vLLM + vLLM --> GPU[GPU Memory] + Proxy -.->|signs with| Key[TEE-derived key] + end + Proxy -->|Response + Signature| User +``` + +The proxy terminates TLS, forwards to vLLM, and signs responses with a key derived from the TEE's identity. That signature proves the response came from this specific environment. + +Deploy it: + +```bash +phala deploy -n my-llm -c docker-compose.yaml \ + --instance-type h200.small \ + -e TOKEN=your-secret +``` + +Verify a response signature: + +```python +import requests + +sig = requests.get( + f"https://your-endpoint/v1/signature/{chat_id}", + headers={"Authorization": "Bearer your-token"} +).json() + +# sig contains signing_address, response_hash, signature +``` + +Try it live at [chat.redpill.ai](https://chat.redpill.ai). Full example: [dstack-examples/ai/inference](https://github.com/Dstack-TEE/dstack-examples/tree/main/ai/inference). + +## Confidential Training + +Fine-tune on sensitive data without exposing it to the operator. The training data and resulting weights stay in encrypted memory. + +```yaml +services: + trainer: + image: unsloth/unsloth:latest + command: python train.py --model meta-llama/Llama-3.2-3B --data /data/dataset.jsonl + volumes: + - /var/run/dstack.sock:/var/run/dstack.sock + - training-data:/data + environment: + - HF_TOKEN=${HF_TOKEN} + - WANDB_API_KEY=${WANDB_API_KEY} + deploy: + resources: + reservations: + devices: + - driver: nvidia + capabilities: [gpu] + +volumes: + training-data: +``` + +With NVIDIA CC on H100/H200, GPU memory is encrypted. Weights, gradients, and activations stay confidential throughout training. + +```mermaid +graph TB + subgraph TEE[Confidential VM] + Data[Training Data] --> Trainer + Trainer --> GPU[Confidential GPU Memory] + GPU --> Weights[Model Weights] + end + External[Data Provider] -->|encrypted upload| Data + Weights -->|encrypted download| External +``` + +Before a data provider shares sensitive data, they should: + +1. Review your docker-compose.yaml—check for unexpected network access or volume mounts +2. Get the attestation quote and verify the compose hash matches +3. Confirm it's running on genuine TDX + NVIDIA CC hardware + +The compose hash is a hash of your docker-compose.yaml. It's included in the attestation quote, so data providers can verify exactly what code will process their data. + +```python +from dstack_sdk import DstackClient + +client = DstackClient() +info = client.info() + +print(f"Compose hash: {info.compose_hash.hex()}") +# Data provider compares this against the docker-compose they reviewed +``` + +Full example: [dstack-examples/ai/training](https://github.com/Dstack-TEE/dstack-examples/tree/main/ai/training). + +## Trustworthy AI Agents + +Agents do complex things with user data—RAG lookups, database queries, LLM calls. Users want guarantees: their data won't be logged, won't be used for training, won't be exfiltrated. + +For true end-to-end privacy, the agent should call a confidential LLM endpoint (like the vllm-proxy from the inference section) instead of a third-party API. This keeps user prompts encrypted the entire way. + +```yaml +services: + agent: + image: your-agent:latest + volumes: + - /var/run/dstack.sock:/var/run/dstack.sock + environment: + # Point to a confidential LLM endpoint, not OpenAI + - LLM_BASE_URL=https://api.redpill.ai/v1 + - LLM_API_KEY=${LLM_API_KEY} + - DATABASE_URL=${DATABASE_URL} + ports: + - "8080:8080" +``` + +The architecture looks like this: + +```mermaid +graph TB + User -->|TLS| Agent + subgraph TEE1[Agent CVM] + Agent[Agent Code] + Agent --> RAG[RAG Pipeline] + Agent --> DB[(Database)] + end + Agent -->|TLS| LLM + subgraph TEE2[LLM CVM] + LLM[vllm-proxy + vLLM] + end + Agent -->|response| User + Operator -.->|cannot access| TEE1 + Operator -.->|cannot access| TEE2 +``` + +Both the agent and the LLM run in separate TEEs. User queries stay encrypted from browser to agent to LLM and back. The operator sees nothing. + +**Data stays private.** RAG retrievals, database queries, LLM calls, and agent state all run in encrypted memory. Using a confidential LLM means prompts never leave the encrypted environment. + +**No hidden behavior.** The compose hash in the attestation proves what code is running. Users can audit the code and verify it matches—no secret logging, no unauthorized data collection. + +**Provable constraints.** Want to prove your agent doesn't send user data to training pipelines? The auditable code + attestation makes that verifiable. + +For agents that need persistent keys (signing, encryption), derive them from the TEE: + +```python +from dstack_sdk import DstackClient + +client = DstackClient() +key = client.get_key('agent/signing-key') +# Same deployment = same key, but key never leaves TEE +``` + +Full example: [dstack-examples/ai/agents](https://github.com/Dstack-TEE/dstack-examples/tree/main/ai/agents). + +## Verification + +You can verify a running deployment before sending it sensitive data. Start by reviewing the application code and configuration. Then verify the CPU attestation and compare the measured application configuration with the one you reviewed. + +On Intel TDX, the signed CPU quote lets you verify the launch record, including the application configuration hash and dstack's boot-time GPU check. Follow the [Intel TDX attestation guide](./attestation-tdx.md). For other platforms, see the [verification overview](./verification.md#platform-specific-verification). + +For a GPU workload, check two more things, because the default policy also accepts a launch with no GPU: + +- The reviewed configuration keeps GPU attestation enabled: `requirements.gpu_policy.attest_gpu` is not `false`. A `rego` rule in the same policy can require the expected GPU count. +- The launch record contains exactly one `gpu-attestation` event, and its `devices` count is above zero and matches your deployment. + +## Performance + +GPU inference runs at 99% of bare-metal speed on H100/H200. The memory encryption happens in hardware, so the overhead is minimal. Larger models actually perform better in TEE—the encryption cost is fixed while compute scales with model size. + +See the [full benchmark report](https://docs.phala.network/dstack/phala-cloud/references/performance-report) for CPU and storage numbers. + +## Getting Started + +1. Try [chat.redpill.ai](https://chat.redpill.ai) to see private inference in action +2. Deploy your own with the [inference example](https://github.com/Dstack-TEE/dstack-examples/tree/main/ai/inference) +3. Read the [Security Model](./security/security-model.md) for the full threat model + +## Production + +redpill.ai and NEAR AI run confidential AI on dstack in production. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000000..06872f0c61 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,718 @@ +# Deploying dstack + +> **This guide is for self-hosted deployments** on your own TDX or AMD SEV-SNP hardware. For cloud deployments, see [Quickstart](./quickstart.md). + +This guide covers the full manual deployment path for self-hosted dstack. Before deploying, prepare the host with [Hardware enablement](./hardware-enablement.md). If you want the shortest path to a first app on one host, start with [Self-hosted quick onboarding](./onboarding.md). + +## Overview + +dstack can be deployed in two ways: + +- **Single-node deployment**: `dstackup` downloads a verified guest image, renders host config, starts the VMM and auth webhook, bootstraps a KMS CVM, and deploys apps through direct port mappings. Use [Self-hosted quick onboarding](./onboarding.md) for the first-app path. +- **Production deployment**: KMS and Gateway run as CVMs with hardware-rooted security. Uses an auth server for authorization and OS image allowlisting. Required for multi-node deployments, Gateway routing, custom domains, or on-chain governance. + +For local development and contribution workflows, see [Contributing](../CONTRIBUTING.md). + +## Prerequisites + +**Hardware:** +- Bare metal TDX or AMD SEV-SNP server. See [Hardware enablement](./hardware-enablement.md). +- At least 16GB RAM, 100GB free disk space +- Public IPv4 address +- Optional: NVIDIA H100 or Blackwell GPU for [Confidential Computing](https://www.nvidia.com/en-us/data-center/solutions/confidential-computing/) workloads + +**Network:** +- Domain with DNS access (for Gateway TLS) + +> **Note:** See [Hardware Requirements](https://docs.phala.network/dstack/hardware-requirements) for server recommendations. + +## Production Deployment + +For production, deploy KMS and Gateway as CVMs with hardware-rooted security. Production deployments require: +- KMS running in a CVM (not on the host) +- Auth server for authorization (webhook mode) +- KMS measurements allowlisted before bootstrap / onboarding / trusted RPCs can succeed + +If you skip the KMS allowlist step, the VM may boot and the onboard UI may still appear, but the KMS will reject bootstrap, onboarding, or later trusted RPCs with authorization errors. + +### Production Checklist + +**Required:** + +1. Set up TDX host with dstack-vmm +2. Deploy KMS as CVM (with auth server, capture its attestation info, and allowlist the KMS `mrAggregated` before bootstrap) +3. Deploy Gateway as CVM +4. [Zero Trust HTTPS](#4-zero-trust-https) - the gateway cannot serve an app over TLS until it holds a certificate for the domain + +**Optional Add-ons:** + +5. [Certificate Transparency monitoring](#5-certificate-transparency-monitoring-optional) +6. [Multi-node deployment](#6-multi-node-deployment-optional) +7. [On-chain governance](./onchain-governance.md) - Smart contract-based authorization + +--- + +### 1. Set Up TDX Host + +Clone and build dstack-vmm: + +```bash +git clone https://github.com/Dstack-TEE/dstack +cd dstack +cargo build --manifest-path dstack/Cargo.toml --release -p dstack-vmm -p supervisor +mkdir -p vmm-data +cp dstack/target/release/dstack-vmm vmm-data/ +cp dstack/target/release/supervisor vmm-data/ +cd vmm-data/ +``` + +Create `vmm.toml`: + +```toml +address = "tcp:0.0.0.0:9080" +reuse = true +image_path = "./images" +run_path = "./run/vm" + +[auth] +enabled = true +# generate with: openssl rand -hex 32 +tokens = [""] + +[cvm] +kms_urls = [] +gateway_urls = [] +cid_start = 30000 +cid_pool_size = 1000 + +[cvm.port_mapping] +enabled = true +address = "127.0.0.1" +range = [ + { protocol = "tcp", from = 1, to = 20000 }, + { protocol = "udp", from = 1, to = 20000 }, +] + +[host_api] +address = "vsock:2" +port = 10000 +``` + +> **VMM API authentication (required for non-localhost binds).** Since [PR #796](https://github.com/Dstack-TEE/dstack/pull/796), the `[auth]` token guards the *entire* VMM surface — creating and stopping CVMs, the web UI, and all pRPC calls — not just `/logs`. Because the example above binds `tcp:0.0.0.0:9080` (reachable off the host), you MUST enable `[auth]`; otherwise the whole control API is exposed unauthenticated. Auth is fail-closed: with `enabled = true` and no usable credential, requests are rejected. +> +> Clients authenticate with `Authorization: Bearer ` (or the `X-Admin-Token: ` header). Instead of inline `tokens`, you can point to an Apache bcrypt htpasswd file with `htpasswd_file = "/etc/dstack/admin.htpasswd"` (create it with `htpasswd -B -c /etc/dstack/admin.htpasswd admin`). Only bcrypt (`-B`) entries are accepted. + +Download guest images from [dstack guest-OS releases](https://github.com/Dstack-TEE/dstack/releases) and extract to `./images/`. + +> For reproducible builds and verification, see the [Security Model](./security/security-model.md). + +Start VMM: + +```bash +./dstack-vmm -c vmm.toml +``` + +--- + +### 2. Deploy KMS as CVM + +Production KMS requires: +- **KMS**: The key management service inside a CVM +- **Auth server**: Webhook server that validates boot requests and returns authorization decisions + +#### Auth Server Options + +> **Note:** the boot-authorization webhook below (dstack-auth / auth-eth) is a *different* mechanism from the KMS admin-API authentication. The webhook allowlists which CVMs may boot and receive keys; the admin API (`[listeners.admin]` in `kms.toml`) guards operator RPCs. See [dstack-kms admin authentication](../dstack/kms/README.md#admin-api-authentication). + +| Server | Use Case | Configuration | +|--------|----------|---------------| +| [dstack-auth](./dstack-auth-operations.md) | Config-file-based whitelisting for development, testing and evaluation only | JSON config file | +| [auth-eth](../dstack/kms/auth-eth/) | On-chain governance via the `DstackKms`/`DstackApp` contracts in the same directory | Ethereum RPC + contract | +| Custom | Your own authorization logic | Implement webhook interface | + +All auth servers implement the same webhook interface: + +- `GET /` - Health check and current root epoch +- `POST /authorizeApp` - Application key and certificate authorization +- `POST /authorizeKms` - KMS self-authorization and key handover + +The legacy `/bootAuth/app` and `/bootAuth/kms` routes remain available for older +clients and KMS bootstrap/onboarding checks. + +#### Using dstack-auth (Config-Based) + +dstack-auth validates requests against a JSON config file. Build it: + +```bash +cd dstack +cargo build --release -p dstack-auth +``` + +Create `auth-config.json` for initial KMS deployment: + +```json +{ + "osImages": ["0x"], + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [], + "kms": { + "mrAggregated": ["0x"], + "allowAnyDevice": true + }, + "apps": {} +} +``` + +> **Important:** an empty `kms.mrAggregated` allowlist denies every KMS. Capture the current KMS measurement with `Onboard.GetAttestationInfo` and add it before bootstrap. + +`allowedTcbStatuses` and `allowedAdvisoryIds` are opt-in: without them the TCB +status and advisories are not checked. Keep them unless you operate and trust +the host yourself; see [TCB and advisory policy](./dstack-auth-operations.md#tcb-and-advisory-policy). + +Bootstrap needs only the fields above. Before the KMS serves keys, set +`kmsContractAddr` to the KMS CVM's app ID and register its root keys as +`rootEpochs` (see [Rotating KMS Root Keys](#rotating-kms-root-keys)); every +other operation is denied until both are set. + +Run dstack-auth on the operator host: + +```bash +./target/release/dstack-auth --config /path/to/auth-config.json --port 3001 +``` + +It binds to `127.0.0.1`, which a KMS CVM on QEMU user-mode networking reaches as +`http://10.0.2.2:3001`. Add `--address 0.0.0.0` if the KMS reaches the host over +a real network. + +For adding Gateway, apps, and other config fields, see [dstack-auth Operations Guide](./dstack-auth-operations.md). + +#### Using auth-eth (On-Chain) + +For decentralized governance via smart contracts, see [On-Chain Governance](./onchain-governance.md). + +auth-eth reads policy at the block `ETH_BLOCK_TAG` names, `finalized` by +default. Only `finalized` protects policy from reorgs. With `latest` (required +for an OP-stack chain read through Helios) or `safe`, a reorg can revert both +activations and revocations: a removed image or compose hash is authorized +again, and a rolled-back root epoch activation makes every KMS restart onto the +previous epoch. `ETH_FINALITY_CONFIRMATIONS=N` hides reorgs shallower than N +blocks but delays every policy change, emergency revocations included, by N +blocks. See [reorgs and the block tag](../dstack/kms/auth-eth/README.md#reorgs-and-the-block-tag). + +Optional `APP_AUTH_URL` leaves KMS policy on `DstackKms` and forwards +`/authorizeApp` and `GET /app/:appId` to another service. The default, leaving +it unset, is unchanged. See [delegated app authorization](../dstack/kms/auth-eth/README.md#delegated-app-authorization). + +#### Getting OS Image Hash + +The OS image hash is in the `digest.txt` file inside the guest image tarball: + +```bash +# Extract hash from release tarball +tar -xzf dstack-0.5.5.tar.gz +cat dstack-0.5.5/digest.txt +# Output: 0b327bcd642788b0517de3ff46d31ebd3847b6c64ea40bacde268bb9f1c8ec83 +``` + +Add `0x` prefix for the dstack-auth config: `0x0b327bcd...` + +#### Deploy KMS CVM + +Choose the deployment script based on your auth server: + +**For dstack-auth (external webhook):** + +dstack-auth runs on your infrastructure, outside the CVM. + +```bash +cd dstack/kms/dstack-app/ +``` + +Edit `.env.simple`: + +```bash +VMM_RPC=http://127.0.0.1:9080 +AUTH_WEBHOOK_URL=http://10.0.2.2:3001 +KMS_RPC_ADDR=0.0.0.0:9201 +GUEST_AGENT_ADDR=127.0.0.1:9205 +OS_IMAGE=dstack-0.5.5 +IMAGE_DOWNLOAD_URL=https://github.com/Dstack-TEE/meta-dstack/releases/download/v0.5.5/dstack-0.5.5.tar.gz +``` + +Then run: + +```bash +./deploy-simple.sh +``` + +**For auth-eth (on-chain governance):** + +> See [On-Chain Governance Guide](./onchain-governance.md) for deploying KMS with smart contract-based authorization. + +**Monitor startup:** + +```bash +tail -f ../../../vmm-data/run/vm//serial.log +``` + +Wait for `[ OK ] Finished App Compose Service.` + +#### Bootstrap KMS + +Open `http://127.0.0.1:9201/` in your browser. + +1. Click **Bootstrap** +2. Enter the domain for your KMS (e.g., `kms.example.com`) +3. Click **Finish setup** + +![KMS Bootstrap](assets/kms-bootstrap.png) + +The KMS will display its public key and TDX quote: + +![KMS Bootstrap Result](assets/kms-bootstrap-result.png) + +--- + +### 3. Deploy Gateway as CVM + +#### Prerequisites + +Before deploying Gateway: +1. Register the Gateway app in your auth server config (add to `apps` section in `auth-config.json`) +2. Note the App ID you assign - you'll need it for the `.env` file + +For on-chain governance, see [On-Chain Governance](./onchain-governance.md#register-gateway-app) for registration steps. + +#### Deploy Gateway CVM + +```bash +cd dstack/gateway/dstack-app/ +./deploy-to-vmm.sh +``` + +Edit `.env` with required variables: + +```bash +# VMM connection (use TCP if VMM is on same host, or remote URL) +VMM_RPC=http://127.0.0.1:9080 + +# Cloudflare (for DNS-01 ACME challenge) +CF_API_TOKEN=your_cloudflare_api_token + +# Domain configuration +SRV_DOMAIN=example.com +PUBLIC_IP=$(curl -s ifconfig.me) + +# Gateway app ID (from registration above) +GATEWAY_APP_ID=32467b43BFa67273FC7dDda0999Ee9A12F2AaA08 + +# Gateway URLs +MY_URL=https://gateway.example.com:9202 +BOOTNODE_URL=https://gateway.example.com:9202 + +# WireGuard (uses same port as RPC) +WG_ADDR=0.0.0.0:9202 + +# Network settings +SUBNET_INDEX=0 +ACME_STAGING=no # Set to 'yes' for testing +OS_IMAGE=dstack-0.5.5 +``` + +**Note on hex formats:** +- Gateway `.env` file: Use raw hex without `0x` prefix (e.g., `GATEWAY_APP_ID=32467b43...`) +- dstack-auth config: Use `0x` prefix (e.g., `"0x32467b43..."`). The server normalizes both formats. + +Run the script again: + +```bash +./deploy-to-vmm.sh +``` + +The script will display the compose file and compose hash, then prompt for confirmation: + +``` +Docker compose file: +... +Compose hash: 0x700a50336df7c07c82457b116e144f526c29f6d8... +Configuration: +... +Continue? [y/N] +``` + +**Before pressing 'y'**, add the compose hash to your auth server whitelist: +- For dstack-auth: Add to `composeHashes` array in `auth-config.json` +- For auth-eth: Use Foundry scripts (see [On-Chain Governance](./onchain-governance.md#register-gateway-app)) + +Then return to the first terminal and press 'y' to deploy. + +#### Update VMM Configuration + +After Gateway is running, update `vmm.toml` with KMS and Gateway URLs: + +```toml +[cvm] +kms_urls = ["https://kms.example.com:9201"] +gateway_urls = ["https://gateway.example.com:9202"] +``` + +`gateway_urls` is a failover list for one gateway cluster. To register a CVM +with independently operated clusters, configure explicit groups instead. Each +cluster gets a separate WireGuard interface and key pair; their WireGuard +address ranges must not overlap. All clusters must run the gateway app identity +authorized by the CVM's KMS-issued app keys. + +Clusters refresh independently. If one cluster is unavailable, its last +working WireGuard configuration remains active while other clusters continue +to register and update normally. + +`gateway_urls` and `gateway_clusters` are mutually exclusive in the VMM +configuration. The VMM refuses to start if both are non-empty. For compatibility +with sys-config files produced elsewhere, the guest prefers `gateway_clusters` +and logs a warning when both forms are present. + +```toml +[cvm] +kms_urls = ["https://kms.example.com:9201"] + +[[cvm.gateway_clusters]] +name = "primary" +urls = [ + "https://gateway-a.example.com:9202", + "https://gateway-b.example.com:9202", +] +[[cvm.gateway_clusters]] +name = "secondary" +urls = ["https://gateway-c.example.com:9202"] +``` + +Restart dstack-vmm to apply changes. + +--- + +### 4. Zero Trust HTTPS + +The gateway issues its own certificates from inside the CVM. `dstack-gateway` +links the `certbot` crate directly: it answers dns-01 challenges with the +Cloudflare credential you give it, and keeps the ACME account key and every +certificate in the CVM's WaveKV store. Neither key is ever written to the host, +which is what makes the monitoring in step 5 worth running — every certificate +the CT logs show for your domain should carry a public key the gateway +published. Nothing on the host issues or holds these certificates; the `certbot` +CLI under `dstack/certbot/cli` is a testing tool for the same crate and has no +part in this path. + +`bootstrap-cluster.sh` configures all of it, reading `CF_API_TOKEN`, +`SRV_DOMAIN` and `ACME_STAGING` from the `.env` you filled in during step 3 and +calling the gateway's admin API: + +```bash +cd dstack/gateway/dstack-app/ +bash bootstrap-cluster.sh +``` + +| RPC | What it sets | +|---|---| +| `SetCertbotConfig` | ACME directory URL and the renewal schedule | +| `CreateDnsCredential` | the Cloudflare token used for dns-01, as the default credential | +| `AddZtDomain` | a domain to keep a wildcard certificate for | + +Run it once per cluster. Additional nodes receive all three through cluster +sync, so do not repeat it per node. + +Every name the gateway terminates TLS on needs its own ZT domain. The script +adds `SRV_DOMAIN`; if app URLs sit one level deeper — `-.gateway.example.com` +— then `gateway.example.com` needs an entry of its own, because a wildcard +certificate for `*.example.com` does not cover subdomains of subdomains. + +Certificates are requested on the next renewal round rather than the moment a +domain is added. Watch for them to arrive: + +```bash +ADMIN_ADDR=127.0.0.1:9203 # GATEWAY_ADMIN_RPC_ADDR in .env +curl -sf -H "Authorization: Bearer $ADMIN_API_TOKEN" \ + "http://$ADMIN_ADDR/prpc/ListZtDomains" | jq '.domains[] | {domain: .config.domain, cert: .cert_status}' +``` + +`has_cert: true` with a `not_after` roughly 90 days out means the domain is +served. `POST /prpc/RenewCert` forces a round immediately instead of waiting +for `renew_interval_secs`. + +Pin issuance to your own ACME account with `POST /prpc/SetCaa`, which writes +CAA records naming Let's Encrypt and the gateway's account URI for every +configured domain. Any other account is then refused by the CA rather than +merely noticed after the fact by step 5. + +Start on Let's Encrypt staging (`ACME_STAGING=yes`), whose certificates are not +browser-trusted but whose rate limits leave room for mistakes. Switching to +production takes two calls: `SetCertbotConfig` with the production directory +URL, then `RotateAcmeCredentials` to register an account there and re-pin every +domain's CAA to it. Renewals refuse to run while the stored account and the +configured ACME URL disagree, so do not skip the rotation. + +For the same flow driven by hand, one curl at a time, see the +[Gateway service setup tutorial](./tutorials/gateway-service-setup.md#step-4-bootstrap-admin-api). +For a multi-node cluster, see [Cluster deployment](../dstack/gateway/docs/cluster-deployment.md). + +--- + +### 5. Certificate Transparency Monitoring (Optional) + +Monitor for unauthorized certificates issued to your domain. + +```bash +cd /path/to/dstack +cargo build --manifest-path dstack/Cargo.toml --release -p ct_monitor +./dstack/target/release/ct_monitor \ + --gateway-uri https:// \ + --domain +``` + +**How it works:** +1. Fetches known public keys from Gateway (`/acme-info` endpoint) +2. Queries crt.sh for certificates issued to your domain +3. Verifies each certificate's public key matches the known keys +4. Logs errors (❌) when certificates are issued to unknown public keys + +The monitor runs in a loop, checking every 60 seconds. Integrate with your alerting system by monitoring stderr for error messages. + +--- + +### 6. Multi-Node Deployment (Optional) + +Scale by adding VMM nodes and KMS replicas for high availability. + +#### Adding VMM Nodes + +On each additional TDX host: +1. Set up dstack-vmm (see step 1) +2. Configure `vmm.toml` with existing KMS/Gateway URLs +3. Start VMM + +```toml +[cvm] +kms_urls = ["https://kms.example.com:9201"] +gateway_urls = ["https://gateway.example.com:9202"] +``` + +#### Adding KMS Replicas (Onboarding) + +Additional KMS instances can onboard from an existing KMS to share the same root keys. This enables: +- High availability (multiple KMS nodes) +- Geographic distribution +- Load balancing + +**How it works:** + +1. New KMS starts in onboard mode (empty `auto_bootstrap_domain`) +2. New KMS generates an RA-TLS client certificate with its attestation: self-issued with an admin token, or signed by the source temporary CA for tokenless legacy onboarding +3. New KMS calls `GetKmsKey` over mTLS: `Admin.GetKmsKey` with the token, or the explicitly enabled public `KMS.GetKmsKey` without one +4. Source KMS verifies the attestation and authorizes handover via `/authorizeKms` +5. If approved, source KMS returns root keys +6. New KMS verifies the source's attestation on that same connection and checks it against its own policy before using the keys +7. Both KMS instances now derive identical keys + +**Configure the source KMS for key handover:** + +Every KMS needs this, or `core.onboard.public_key_handover = true`: without a handover path it refuses to start, before onboarding or bootstrap, naming the missing setting. In a public config such as an app compose, set `auth_token_hash` (the token's SHA-256) instead of `auth_token`, with a high-entropy random token (`openssl rand -hex 32`), since the hash can be brute-forced offline. + +`Admin.GetKmsKey` only works on an admin listener with TLS (`[listeners.default.tls]`, or `[listeners.admin.tls]` to override it): without TLS the listener speaks plain HTTP, so the new KMS can present no RA-TLS certificate and the call fails with `No attestation provided`. The admin listener binds to `127.0.0.1` by default; bind it to an address the new KMS can reach and restrict access to the KMS nodes at the network layer. + +```toml +[listeners.admin] +enabled = true +address = "0.0.0.0" # reachable by the new KMS; firewall it to KMS nodes only +port = 8001 +auth_token = "" + +[listeners.default.tls] +key = "/var/lib/kms/certs/rpc.key" +certs = "/var/lib/kms/certs/rpc.crt" +# No `mutual` section: client certificates are verified by their attestation. +``` + +**Configure new KMS for onboarding:** + +```toml +[core.onboard] +enabled = true +auto_bootstrap_domain = "" # Empty = onboard mode + +[listeners.onboard] +address = "0.0.0.0" +port = 9203 # HTTP port for onboard UI +``` + +**Trigger onboard via API:** + +```bash +curl -X POST http://:9203/prpc/Onboard.Onboard?json \ + -H "Content-Type: application/json" \ + -d '{"source_url": "https://:8001/prpc", "source_token": "", "domain": "kms2.example.com"}' +``` + +**Finish and restart:** + +```bash +curl http://:9203/finish +# Restart KMS - it will now serve as a full KMS with shared keys +``` + +> **Note:** KMS onboarding requires attested KMS instances, and both sides must already be authorized. Add the relevant KMS `mrAggregated` hashes to your auth backend first: +> +> - the destination KMS must allow the source KMS +> - the source KMS must allow the destination KMS +> +> If you skip this, `Onboard.Onboard` or later trusted RPCs will fail with KMS authorization errors. + +> **Admin authentication.** The KMS *admin* RPCs (for example `ClearImageCache`) are served on a dedicated `[listeners.admin]` listener behind the shared HTTP authenticator, just like the VMM and gateway: set `[listeners.admin] enabled = true` with an `auth_token` (or the `DSTACK_KMS_ADMIN_TOKEN` / `ADMIN_API_TOKEN` env vars), and clients send `Authorization: Bearer ` or `X-Admin-Token`. Enabled with neither `auth_token` nor `htpasswd_file` (and `insecure_no_auth = false`) fails closed — the KMS refuses to start. See [dstack-kms admin authentication](../dstack/kms/README.md#admin-api-authentication). +> +> **Source pinning.** Before sending anything secret, the new KMS requires the source's RPC certificate, at the TLS handshake, to be a `kms:rpc` leaf signed by the current root CA its own auth API reports (`rootCaPubkey` in `GET /`), so `source_url` must be `https://`. A source without the registered roots never sees the launch ticket or `source_token`; onboarding fails if the auth API reports no root CA key. Right after a root epoch is activated, a source still serving the RPC certificate of the previous one fails the handshake until it restarts; onboarding attempts do not trigger that restart, so restart the source. Upgrade the auth backend before the KMS: a custom webhook must report `rootCaPubkey`. A KMS with `auth_api.type = "dev"` registers no roots and pins nothing. +> +> **Launch ticket.** When the KMS contract requires one (`setRequireKmsLaunchTicket`), pass this instance's ticket as `launch_ticket` in the onboarding request; the source checks its hash against `kmsLaunchTickets()` before handing over the keys. Remove the ticket from the contract once the instance has joined. See [launch tickets](../dstack/kms/README.md#launch-tickets). +> +> **Key handover.** It is served as `Admin.GetKmsKey` on the `[listeners.admin]` listener, which needs TLS so it can verify the onboarding KMS's RA-TLS certificate. Pass the source admin URL (`https://`) and its token (`source_token`) in the onboarding request; the token is required unless the source enables the public handover. The legacy public `KMS.GetKmsKey` is off by default; set `core.onboard.public_key_handover = true` on the source only when an onboarding KMS cannot use the admin listener, such as a 0.5.x KMS or an onboarding request without `source_token`. + +#### Rotating KMS Root Keys + +KMS root keys are versioned by epoch; epoch 0 is the original roots. Every KMS +keeps all epochs so CVMs can migrate from any of them, and serves the epoch +governance made current. See the [rotation design](./kms-emergency-key-rotation-protocol.md) +for the full procedure; the KMS steps are: + +1. If epochs were never registered, publish the attestation the KMS produced at + bootstrap (served as `bootstrap_info` by `KMS.GetMeta`) and + register the current root public keys as epoch 0: + `DstackKms.registerRootEpoch(caPubkey, k256Pubkey, evidenceUrl)`, via + `script/Manage.s.sol:RegisterRootEpoch`, or a `rootEpochs` entry in the + dstack-auth config. Epoch 0 is current once registered, and must be the + `kmsInfo` keys when those are set. A deployment whose `kmsInfo` holds a + legacy `quote` and `eventlog` instead of an attestation converts them with + `dstack-kms legacy-attestation --quote --eventlog ` and publishes + the result first: from then on `kmsInfo` follows the current epoch's keys and + its quote and event log are cleared. +2. Onboard a fresh KMS with `"rotate": true` (the **Rotate** checkbox in the + onboard UI) from a KMS at the current epoch N-1. It imports epochs 0..N-1, + generates epoch N, and returns the new public keys with an attestation whose + report data is + `keccak256("dstack-kms-genereted-keys-v1:{ca_pubkey_hex};{k256_pubkey_hex};")` + zero-padded to 64 bytes, the same encoding as the original bootstrap (the + spelling is part of the format). It binds both public keys; the epoch number + comes from the on-chain registration order. +3. Before registering, verify the attestation with + [dstack-verifier](../dstack/verifier/README.md) (`POST /verify`): check the + quote, the approved KMS image and measurements, and that its report data + equals the value recomputed from the returned public keys. Then publish it + and register epoch N with its URL. The cluster keeps serving N-1. +4. Onboard the other KMS nodes from the rotated one; they import 0..N and keep + serving N-1. A join checks the source's keyring against the latest registered + epoch as well as the current one, so a source holding an unregistered or + different epoch N is refused. +5. Activate epoch N (`ActivateRootEpoch`, or `currentRootEpoch` for + dstack-auth). Each KMS restarts onto N on its next uncached authorization + check; a KMS that does not hold N waits + until it is onboarded again. + If the nodes holding N are lost before N is activated, drop it with + `PopRootEpoch` (or remove the `rootEpochs` entry) and rotate again; nodes + that imported the dropped N must be onboarded again. On chain, the policy + rows prepared for the dropped N do not apply to the new one; approve them + again before activating it. +6. Boot CVMs on an OS that supports root epochs. At boot they re-key their data + disk from the epoch recorded in its LUKS header to the current one. If an + encrypted environment still uses an older epoch, the CVM re-encrypts it during + boot and the VMM replaces the ciphertext only if it was not changed concurrently. + See [SealedEnv](./sealed-env.md) for the new format, file precedence, and rollback requirements. + +Each `authorizeKms` or `authorizeApp` result carries the current epoch and its chain hash, +and the latest registered epoch (`latestRootEpoch`, `latestRootEpochHash`), which may be +pending activation, including when authorization is denied. KMS verifies these against its keyring; +there is no cached serving epoch. An optional `requestedRootEpoch` selects historical +keys, and omission selects the returned current epoch. Requests for future +epochs are denied. No registered epoch returns a rejection with +`rejectionReason: "Root epoch not registered"` and a zero hash. + +RPC certificates still require a listener restart when their root CA changes; +callers retry after the certificate is refreshed. Register epoch 0 before normal +key release. Bootstrap keeps using scoped KMS authorization so it can generate +the first roots before registration. See the +[authorization protocol](../dstack/kms/README.md#authorization-protocol). + +--- + +## Deploying Apps + +After setup, deploy apps via the VMM dashboard or CLI. + +### Register App + +Before deploying, register your app in your auth server: +- For dstack-auth: See [dstack-auth Operations Guide](./dstack-auth-operations.md#adding-an-app) +- For auth-eth: See [On-Chain Governance](./onchain-governance.md#register-apps-on-chain) + +### Deploy via UI + +Open `http://localhost:9080`: + +![App Deploy](assets/app-deploy.png) + +- Select the OS image +- Enter the App ID (from registration above) +- Upload your `docker-compose.yaml` + +After startup, click **Dashboard** to view: + +![App Board](assets/app-board.png) + +--- + +## Troubleshooting + +### Error: vhost-vsock: unable to set guest cid: Address already in use + +The CID range conflicts with existing VMs. + +1. Find used CIDs: `ps aux | grep 'guest-cid='` +2. Update `vmm.toml`: + ```toml + [cvm] + cid_start = 33000 + cid_pool_size = 1000 + ``` + +### High-concurrency deployments: conntrack table full + +When running Gateway with many concurrent connections (>100K), the host's conntrack table may fill up, causing silent packet drops: + +``` +dmesg: nf_conntrack: table full, dropping packet +``` + +Each proxied connection creates multiple conntrack entries (client→gateway, gateway→WireGuard→backend). The default `nf_conntrack_max` (typically 262,144) is insufficient for high-concurrency gateways. + +**Fix:** + +```bash +# Check current limit +sysctl net.netfilter.nf_conntrack_max + +# Increase for production (persistent) +echo "net.netfilter.nf_conntrack_max = 1048576" >> /etc/sysctl.d/99-dstack.conf +echo "net.netfilter.nf_conntrack_buckets = 262144" >> /etc/sysctl.d/99-dstack.conf +sysctl -p /etc/sysctl.d/99-dstack.conf +``` + +Also increase inside bridge-mode CVMs if they handle many connections: + +```bash +sysctl -w net.netfilter.nf_conntrack_max=524288 +``` + +**Sizing rule of thumb:** Set `nf_conntrack_max` to at least 4× your target concurrent connection count (each connection may use 2-3 conntrack entries across NAT/bridge layers). + +### Error: Operation not permitted when building guest image + +Ubuntu 23.10+ restricts unprivileged user namespaces: + +```bash +sudo sysctl kernel.apparmor_restrict_unprivileged_userns=0 +``` diff --git a/docs/design-and-hardening-decisions.md b/docs/design-and-hardening-decisions.md new file mode 100644 index 0000000000..cfb883a1e8 --- /dev/null +++ b/docs/design-and-hardening-decisions.md @@ -0,0 +1,66 @@ +# Design and Hardening Decisions in the dstack Yocto Layer + +> [!NOTE] +> This document describes the deprecated Yocto backend. The default guest-OS +> backend is mkosi (`os/mkosi/`); see +> [`../os/mkosi/README.md`](../os/mkosi/README.md) for how its image is built +> and where it differs. + +## Overview + +The dstack-owned Yocto layer under `os/yocto/layers/meta-dstack/` is designed to create a minimally secure image for booting Confidential Virtual Machines (CVMs). Our design philosophy prioritizes attack surface reduction while maintaining TDX-aware functionality. This document outlines the architectural decisions and trade-offs made during development. + +## Key Design Decisions + +### 1. Yocto Kernel Recipe Selection + +**Decision**: We use `linux-yocto-dev` (development recipes) instead of `linux-yocto` (stable recipes). + +**Rationale**: We use Scarthgap version of Yocto, which is the latest version when we started the dstack project. The stable `linux-yocto` recipe in Scarthgap is based on kernel 6.6 which does not support RTMR[1-2]. So we switch to `linux-yocto-dev` to get the kernel 6.9 support. The latest released Yocto (Walnascar) updated kernel to 6.12 which meets our requirements. We plan to upgrade the Yocto version later, but this is not trivial as all downstream Yocto recipes need to be updated to adapt to the major Yocto version change. + +### 2. TDVF vs td-shim Boot Firmware + +**Decision**: We use Intel's TDVF implementation integrated in OVMF rather than td-shim. + +**Current State**: **TDVF** is a mature, proven solution currently in use. **td-shim** is a Rust-based implementation aimed at minimizing attack surface. + +**Rationale**: td-shim cannot currently boot our dstack system successfully. td-shim is considered too new for production use in our current requirements. TDVF provides stable, tested functionality for our TDX requirements. + +![alt text](./assets/td-shim-vs-tdvf.png) + +### 3. TDX Guest Driver Implementation + +**Decision**: We use the in-tree confidential guest drivers and the Linux TSM report interface where they are available. For Intel TDX, the dstack kernel configuration enables `CONFIG_TDX_GUEST_DRIVER=y` and `CONFIG_TSM_REPORTS=y`. + +**Rationale**: The in-tree TDX guest driver exposes the standard `/dev/tdx_guest` device and configfs-tsm report interface. Newer kernels also expose RTMR extension through the TSM measurement sysfs path, which dstack uses for RTMR3 runtime events. This keeps dstack aligned with the standard Linux kernel ABI while preserving measured runtime events. + +**Implementation Notes**: The unified dstack confidential-guest image also includes AMD SEV-SNP kernel features. Platform-specific native TEE interfaces are advanced compatibility surfaces for applications that need the kernel ABI directly. The dstack socket remains the normal application API for quotes, keys, application information, and runtime events. + +### 4. Randomness Generation and Seeding + +**Security Requirement**: Ensure cryptographically secure randomness without trusting the host system. + +We configure the kernel with specific command-line arguments: + +``` +random.trust_cpu=y +random.trust_bootloader=n +``` + +`random.trust_cpu=y` enables trust in CPU-provided randomness (Intel RDRAND). `random.trust_bootloader=n` prevents untrusted host-provided entropy. + +Intel RDRAND hardware RNG instruction. System Integration: Proper seeding of `/dev/random` and `/dev/urandom`. Application Support: Ensures container and application randomness needs. + +See [here](https://intel.github.io/ccc-linux-guest-hardening-docs/security-spec.html#linux-rng) for more details. + +### 5. Secure System Time + +**Implementation**: dstack OS enforces the guest kernel uses TSC as the only timer source by appending `tsc=reliable no-kvmclock` to the kernel cmdline. It also enforces the use of NTS with built-in [trusted servers](../os/yocto/layers/meta-dstack/recipes-core/chrony/files/chrony.conf) to synchronize system time. + +On AMD SEV-SNP the hypervisor controls the guest TSC unless the guest is launched with Secure TSC. The VMM enables it whenever `secure_time` is on in app-compose.json (the default), which needs QEMU >= 11.2, host kernel >= 6.18 and a CPU that supports Secure TSC. + +**Behavior**: When `secure_time` is enabled in the app-compose.json configuration, the system ensures time synchronization is completed before requesting application keys. It first checks that the host cannot move the clock between syncs and refuses to boot otherwise: the clocksource must be `tsc`, an AMD SEV-SNP guest must run with Secure TSC, and AWS is not supported. If `secure_time` is disabled, time synchronization is not enforced before application launch. + +**Rationale**: Time synchronization is provided as an optional feature because the process typically requires tens of seconds to complete. Applications can function without the `secure_time` option enabled and may implement their own time synchronization mechanisms if required. + +See [here](https://intel.github.io/ccc-linux-guest-hardening-docs/security-spec.html#tsc-and-other-timers) for more details. diff --git a/docs/development-without-tee.md b/docs/development-without-tee.md new file mode 100644 index 0000000000..560f99722f --- /dev/null +++ b/docs/development-without-tee.md @@ -0,0 +1,233 @@ +# Develop with dstack without TEE hardware + +Development guest images can run dstack's normal guest setup on a KVM machine +that has no TDX or SEV-SNP support. The VMM starts the guest with `no_tee`, the +guest supplies the TDX ABI through `dstack-tee-simulator`, and `swtpm` provides +persistent TPM-backed application keys. This is suitable for development and +integration testing, not for production workloads or secrets. + +## What this mode tests + +The development simulator provides configfs-tsm reports, RTMR extension files, +and a CCEL event log. Guest preparation, measurements, application key setup, +encrypted persistent storage, the guest agent, and Docker Compose therefore +use their normal code paths. + +It does not provide hardware isolation or a valid hardware-signed quote. The +host controls QEMU and swtpm, and a production verifier or KMS must reject the +simulated quote. + +## Build the development image on the host + +TEE hardware is not needed for the build. Follow the prerequisites in +[Build the dstack guest OS](building-guest-os.md), then run this from the +repository root: + +```bash +FLAVORS="dev" ./os/mkosi/repro-build/repro-build.sh +``` + +The artifact used below is +`os/mkosi/repro-build/build/out/dev/dstack-dev-.tar.gz`. Confirm that +it really is a development image: + +```bash +mkdir -p ~/.dstack-vmm/image +tar -xzf os/mkosi/repro-build/build/out/dev/dstack-dev-*.tar.gz \ + -C ~/.dstack-vmm/image +jq '{version, git_revision, is_dev}' \ + ~/.dstack-vmm/image/dstack-dev-*/metadata.json +``` + +Expected output includes `"is_dev": true`. Use a development image for this +workflow because production images do not include `dstack-tee-simulator`. + +## Install and configure the VMM + +Install QEMU and swtpm on the development host. On Ubuntu: + +```bash +sudo apt-get update +sudo apt-get install -y qemu-system-x86 swtpm swtpm-tools jq +test -r /dev/kvm && test -w /dev/kvm +``` + +Add the current user to the `kvm` group and log in again if the `/dev/kvm` +check fails because of its permissions. + +Build the VMM and supervisor from the same checkout as the image: + +```bash +cargo build --manifest-path dstack/Cargo.toml --release \ + -p dstack-vmm -p supervisor +``` + +Install both binaries and the CLI on the machine that will run QEMU. You can +also run them directly from the checkout during development: + +```bash +mkdir -p ~/.dstack-vmm +install -Dm755 dstack/target/release/dstack-vmm ~/.local/bin/dstack-vmm +install -Dm755 dstack/target/release/supervisor ~/.local/bin/supervisor +install -Dm755 dstack/vmm/src/vmm-cli.py ~/.local/bin/dstack +mkdir -p ~/.dstack-vmm +cp dstack/vmm/vmm.toml ~/.dstack-vmm/vmm.toml +``` + +Set these values in `~/.dstack-vmm/vmm.toml`: + +```toml +[image] +path = "/home/USER/.dstack-vmm/image" + +[cvm] +qemu_path = "/usr/bin/qemu-system-x86_64" + +[cvm.networking] +mode = "user" + +[cvm.tee_simulator] +# Development credential only. Use a different random 32-byte hex seed for +# each isolated test environment; never use it for production secrets. +mock_attestation_seed = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" +collateral_base_url = "http://10.0.2.2:18088" + +[supervisor] +exe = "/home/USER/.local/bin/supervisor" +``` + +These node-local settings provide development credentials and collateral URLs; +they do not enable simulation globally. Each deployment selects its simulated +platform with `--simulated-tee`. The VMM then writes an instance-specific +`.tee-simulator.json`, and the guest starts the simulator only when that file +is present in the host share. + +Start the VMM from a stable working directory because its default API socket is +relative to that directory: + +```bash +mkdir -p ~/.dstack-vmm/run +cd ~/.dstack-vmm/run +dstack-vmm -c ../vmm.toml +``` + +In another terminal, check that the development image is visible: + +```bash +cd ~/.dstack-vmm/run +dstack lsimage --json | jq '.[] | {name, version, is_dev}' +``` + +## Launch with no TEE and swtpm + +Create a small stateful workload: + +```yaml +# docker-compose.yml +services: + state-test: + image: alpine:3.20 + command: + - sh + - -c + - | + date -Iseconds >> /data/boots + touch /data/persistent-marker + sleep infinity + volumes: + - state-data:/data +volumes: + state-data: {} +``` + +Convert it to app-compose JSON and select the TPM key provider: + +```bash +dstack compose \ + --name swtpm-persistence \ + --docker-compose docker-compose.yml \ + --key-provider tpm \ + --public-logs \ + --public-sysinfo \ + --output app-compose.json +``` + +Deploy with the development image, no KMS, and an instance-specific simulated +TEE platform: + +```bash +dstack deploy \ + --name swtpm-persistence \ + --image dstack-dev- \ + --compose app-compose.json \ + --vcpu 2 --memory 3G --disk 10G \ + --simulated-tee dstack-tdx +``` + +Successful output contains a VM ID. `dstack info VM_ID` should eventually show +`Boot Progress: done`. The QEMU command line should contain the swtpm frontend +and no TDX guest object: + +```bash +ps aux | grep '[q]emu-system' | grep -E -- '-tpmdev|tpm-tis' +ps aux | grep '[s]wtpm socket' +``` + +The VMM stores both durable components below the VM work directory: + +```text +~/.dstack-vmm/vm/VM_ID/hda.img +~/.dstack-vmm/vm/VM_ID/swtpm/tpm2-00.permall +``` + +Do not delete either path if the VM must restart with the same state. + +## Verify encrypted storage and restart persistence + +First check the guest preparation log: + +```bash +dstack logs VM_ID -n 300 | grep -E \ + 'Generating app keys from TPM|Filesystem options|LUKS2 header|Device mapper' +``` + +A successful first boot includes output like: + +```text +Generating app keys from TPM +Filesystem options: encryption=true, filesystem=Zfs +Mounting tmpfs for in-memory LUKS header +Loading the LUKS2 header +Device mapper /dev/mapper/dstack_data_disk is ready +``` + +Record the instance ID, then perform a graceful restart: + +```bash +dstack info VM_ID | grep 'Instance ID' +dstack stop VM_ID +dstack start VM_ID +``` + +Wait for `Boot Progress: done`, then inspect the recent events and boot log: + +```bash +dstack info VM_ID +dstack logs VM_ID -n 300 | grep -E \ + 'mounting data disk|Loading the LUKS2 header|Device mapper|Container .* Started' +``` + +The restart passes when all of the following hold: + +1. the instance ID is unchanged; +2. the event stream says `mounting data disk`, not `initializing data disk`; +3. the LUKS mapping becomes ready without reformatting the disk; +4. Docker starts the existing container and volume, and + `/data/persistent-marker` and the earlier entries in `/data/boots` remain. + +## Common failures + +`tpm key provider requested but swtpm is not installed` means `swtpm` is not on +the VMM user's `PATH`. If QEMU reports that KVM is unavailable, confirm that +hardware virtualization is enabled and that `/dev/kvm` is writable by the VMM +user. diff --git a/docs/dstack-auth-operations.md b/docs/dstack-auth-operations.md new file mode 100644 index 0000000000..216f59af84 --- /dev/null +++ b/docs/dstack-auth-operations.md @@ -0,0 +1,476 @@ +# dstack-auth Operations Guide + +> **This guide is for self-hosted deployments** on your own TDX hardware. For cloud deployments, see [Quickstart](./quickstart.md). + +> [!WARNING] +> `dstack-auth` is intended for development, testing and evaluation only. Do not +> use it to protect production keys; use [auth-eth](../dstack/kms/auth-eth/) or +> an equivalent production-grade authorization service instead. + +`dstack-auth` is the file-based KMS authorization webhook. It allowlists OS +images, KMS instances and apps in one JSON file. For on-chain governance, use +[auth-eth](../dstack/kms/auth-eth/) instead +(see [On-Chain Governance](./onchain-governance.md)). + +This guide covers running `dstack-auth` and managing apps and devices with it. +For initial deployment setup, see [Deployment Guide](./deployment.md). + +## Overview + +The allowlist file whitelists: +- **OS images** - Which guest OS versions can boot +- **KMS nodes** - Which KMS instances can bootstrap, serve and onboard (`mrAggregated`, devices) +- **Apps** - Which applications can boot (appId, composeHash, devices) +- **Platform state (opt-in)** - Which TCB statuses and security advisories are acceptable + +The file is re-read on every request, so changes take effect immediately without restart. +A missing or invalid file denies every request. + +--- + +## Running dstack-auth + +### Installed by dstackup + +`dstackup` installs `dstack-auth` as the `dstack-auth.service` systemd unit, +listening on `127.0.0.1:8001`, and writes the allowlist to +`auth-allowlist.json` in its config directory. `dstack run` adds the compose +hash of each app it deploys. Edit that file to change the policy. + +### Running the binary yourself + +Build it from the repository: + +```bash +cd dstack +cargo build --release -p dstack-auth +./target/release/dstack-auth --config /path/to/auth-config.json --port 3001 +``` + +| Option | Default | Description | +|--------|---------|-------------| +| `--config` | `/var/lib/dstack/auth-allowlist.json` | Allowlist JSON file | +| `--address` | `127.0.0.1` | Bind address | +| `--port` | `8001` | Bind port | + +A KMS CVM on QEMU user-mode networking reaches the host loopback at `10.0.2.2`, +so the default address is enough for a KMS on the same host: point the KMS at +`http://10.0.2.2:`. Bind `--address 0.0.0.0` only when the KMS reaches the +host over a real network, and restrict access to that port. + +Point the KMS at it in `kms.toml`: + +```toml +[core.auth_api] +type = "webhook" + +[core.auth_api.webhook] +url = "http://10.0.2.2:3001" +``` + +--- + +## Config File Structure + +```json +{ + "osImages": ["0x..."], + "gatewayAppId": "0x...", + "kmsContractAddr": "0x", + "kms": { + "mrAggregated": ["0x..."], + "devices": ["0x..."], + "allowAnyDevice": true + }, + "apps": { + "0x": { + "composeHashes": ["0x..."], + "devices": ["0x..."], + "allowAnyDevice": true + } + }, + "rootEpochs": [{"caPubkey": "0x...", "k256Pubkey": "0x..."}], + "currentRootEpoch": 0 +} +``` + +> **Note:** `osImages` is always required for apps. For KMS authorization, you must also populate `kms.mrAggregated`; if it is left empty, dstack-auth denies all KMS boots. Add `gatewayAppId` after deploying the Gateway. Add `apps` entries as you deploy applications. + +Hex values are compared case-insensitively, with or without a `0x` prefix. + +### Configuration Fields + +| Field | Required | Description | +|-------|----------|-------------| +| `osImages` | Yes | Allowed OS image hashes (from `digest.txt`). Empty denies every app. | +| `gatewayAppId` | No | Gateway app ID (add after Gateway deployment). Several gateways: join their IDs with commas. | +| `kmsContractAddr` | For `/authorize*` | The attested app ID of the KMS. Every operation except `kms_bootstrap` is denied while it is unset, and a caller is accepted only on the endpoint matching its app ID (`/authorizeKms` for this ID, `/authorizeApp` for any other). Reported by `GET /`. | +| `chainId` | No | Informational, reported by `GET /` (default `0`). | +| `appImplementation` | No | Informational, reported by `GET /` as `appImplementation` and `appAuthImplementation`. | +| `allowedTcbStatuses` | No | When set, deny unless the verifier-derived `tcbStatus` is listed; `[]` denies everything. **Absent: not checked.** See [TCB and advisory policy](#tcb-and-advisory-policy). | +| `allowedAdvisoryIds` | No | When set, deny any reported advisory ID that is not listed; `[]` denies any advisory. **Absent: not checked.** | +| `sevSnpTcbRequirements` | No | The minimum TCB of each CPU the KMS judges an SEV-SNP TCB against, as the entries described in [AMD SEV-SNP](./amd-sev-snp.md). **Absent: a KMS judges a CPU only against its own list, and refuses one neither lists.** | +| `kms.mrAggregated` | Yes | Allowed KMS early aggregate MR values (boot-mr-done). Empty denies every KMS. | +| `kms.devices` | No | Allowed KMS device IDs. Empty denies all unless `kms.allowAnyDevice` is true. | +| `kms.allowAnyDevice` | No | If true, skip the device ID check for KMS | +| `apps..composeHashes` | No | Allowed compose hashes for this app | +| `apps..devices` | No | Allowed device IDs for this app. Empty denies all unless `allowAnyDevice` is true. | +| `apps..allowAnyDevice` | No | If true, skip the device ID check for this app | +| `apps..currentAppEpoch` | No | Current app key epoch (default `0`), served by `GET /app/`. A non-zero epoch denies the legacy `/bootAuth/app` route. | +| `rootEpochs` | No | KMS root public keys of each root epoch, indexed by epoch, `[{"caPubkey": "0x...", "k256Pubkey": "0x..."}]`. Epoch 0 is the original roots. Append only. `GET /` reports the current epoch as `rootEpoch` with its chain hash as `rootEpochHash`; the last entry is reported as `latestRootEpoch`, and entries beyond `currentRootEpoch` are pending activation. | +| `currentRootEpoch` | No | Root epoch KMS instances serve (default 0). Key-issuing operations (`kms_serve`, `app_get_key`, `app_get_cert`) may request up to this epoch; KMS key handover (`kms_export_keys`, `kms_import_keys`) may request any registered epoch, so the other KMS nodes can onboard from the rotated one while the new epoch is pending. Raise it only once every KMS node holds that epoch. | + +### Validation Logic + +KMS (`/authorizeKms`, `/bootAuth/kms`): + +1. `tcbStatus` must be in `allowedTcbStatuses`, if set +2. Every `advisoryIds` entry must be in `allowedAdvisoryIds`, if set +3. `mrAggregated` must be in `kms.mrAggregated` +4. `deviceId` must be in `kms.devices` unless `kms.allowAnyDevice` is true + +Apps (`/authorizeApp`, `/bootAuth/app`): + +1. `tcbStatus` must be in `allowedTcbStatuses`, if set +2. Every `advisoryIds` entry must be in `allowedAdvisoryIds`, if set +3. `osImageHash` must be in `osImages` +4. `appId` must exist in `apps` +5. `composeHash` must be in the app's `composeHashes` +6. `deviceId` must be in the app's `devices` unless `allowAnyDevice` is true + +KMS requests are not matched against `osImages`: `mrAggregated` already pins +the OS image measurements. The `/authorize*` endpoints and legacy `/bootAuth/*` +routes also enforce root epochs, see the +[KMS authorization protocol](../dstack/kms/README.md#authorization-protocol). + +--- + +## TCB and Advisory Policy + +By default `dstack-auth` does not check the platform TCB status or security +advisories. In the single-operator model the operator controls and trusts the +host, and real TDX hosts routinely report a non-`UpToDate` TCB when microcode or +the TDX module lags behind, so a hard TCB gate there adds friction without +adding trust. + +Deployments where the host operator is not the party relying on the policy +(a KMS serving other users, AWS, SEV-SNP) should enforce it explicitly: + +```json +{ + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [], + "osImages": ["0x..."], + "kms": { "mrAggregated": ["0x..."], "allowAnyDevice": true }, + "apps": {} +} +``` + +With this, any status other than `UpToDate` and any advisory ID denies. To +accept a known state temporarily, list it explicitly, for example +`"allowedTcbStatuses": ["UpToDate", "SWHardeningNeeded"]` or +`"allowedAdvisoryIds": ["INTEL-SA-00837"]`. + +AWS NitroTPM has no TDX/SNP-style TCB advisory surface, so the KMS normalizes a +verified NitroTPM attestation to `tcbStatus: "UpToDate"` before calling the +webhook; the policy above works unchanged there. + +--- + +## Migrating from auth-simple + +`auth-simple` (the Bun/TypeScript server in `dstack/kms/auth-simple`) has been +removed. `dstack-auth` reads the same config file format, so an existing +`auth-config.json` loads unchanged. To switch: + +1. Keep auth-simple's strict platform defaults by adding them explicitly, unless + your config already sets them: + + ```json + "allowedTcbStatuses": ["UpToDate"], + "allowedAdvisoryIds": [] + ``` + + Without these fields, dstack-auth accepts any TCB status and advisory. +2. Set `kmsContractAddr` to the attested KMS app ID if it is not set. auth-simple + defaulted it to the zero address and did not check it; dstack-auth denies + every `/authorize*` operation except `kms_bootstrap` without it. +3. Replace the start command. `PORT` and `AUTH_CONFIG_PATH` become flags, and + auth-simple listened on all interfaces while dstack-auth binds to loopback + by default: + + ```bash + # before + PORT=3001 AUTH_CONFIG_PATH=/path/to/auth-config.json bun run start + # after + dstack-auth --config /path/to/auth-config.json --port 3001 + ``` + + Add `--address 0.0.0.0` if the KMS reaches the webhook over a real network + rather than `10.0.2.2`. + +Other differences: KMS requests are no longer matched against `osImages` (see +[Validation Logic](#validation-logic)), `GET /` no longer reports `configPath`, +and rejection reasons are lowercase (for example `root epoch not registered`). + +--- + +## Adding an App + +### Step 1: Generate App ID + +App IDs are typically the contract address (for on-chain) or a unique identifier you choose. + +For dstack-auth, you can use any unique hex string (40 characters / 20 bytes): + +```bash +# Generate a random app ID +openssl rand -hex 20 +# Output: 7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b +``` + +### Step 2: Get Compose Hash + +The compose hash is computed from the normalized docker-compose file. The VMM displays it when deploying: + +``` +Docker compose file: +... +Compose hash: 0x700a50336df7c07c82457b116e144f526c29f6d8... +``` + +Or query from a running CVM: + +```bash +curl -s --unix-socket /var/run/dstack.sock http://localhost/Info | \ + jq -r '"0x" + (.tcb_info | fromjson | .compose_hash)' +``` + +> **Note:** The VMM normalizes YAML to JSON before hashing. For exact hash, use the value shown during deployment. + +### Step 3: Add to Config + +Edit your allowlist file: + +```json +{ + "apps": { + "0x7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b": { + "composeHashes": [ + "0x700a50336df7c07c82457b116e144f526c29f6d8..." + ], + "devices": [], + "allowAnyDevice": true + } + } +} +``` + +### Step 4: Deploy via VMM + +Use the App ID when deploying through VMM: + +```bash +./vmm-cli.py deploy \ + --app-id 7a3b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b \ + --compose docker-compose.yaml \ + ... +``` + +--- + +## Updating an App + +When you change your docker-compose.yaml, a new compose hash is generated. + +### Add New Hash (Keep Old Running) + +Add the new hash to the `composeHashes` array: + +```json +{ + "apps": { + "0x": { + "composeHashes": [ + "0x", + "0x" + ] + } + } +} +``` + +### Replace Hash (Force Upgrade) + +Remove the old hash to prevent old versions from booting: + +```json +{ + "apps": { + "0x": { + "composeHashes": [ + "0x" + ] + } + } +} +``` + +--- + +## Device Management + +Devices are identified by their TDX device ID (hardware-specific). + +### Get Device ID + +The `deviceId` is sent by the booting app/KMS in its auth request. dstack-auth +logs it with each decision (`journalctl -u dstack-auth` when installed by +`dstackup`): + +``` +authorize AppGetKey app=7a3b... compose=700a... mr=... os=0b32... device=e5a0... tcb=UpToDate advisories=[] -> authorized=true () +``` + +> **Tip:** Use `allowAnyDevice: true` initially, then restrict to specific devices after capturing IDs from logs. + +### Restrict App to Specific Devices + +```json +{ + "apps": { + "0x": { + "composeHashes": ["0x..."], + "devices": [ + "0xe5a0c70bb6503de2d31c11d85914fe3776ed5b33a078ed856327c371a60fe0fd" + ], + "allowAnyDevice": false + } + } +} +``` + +### Allow Any Device + +For initial testing or when device restriction isn't needed: + +```json +{ + "apps": { + "0x": { + "allowAnyDevice": true + } + } +} +``` + +--- + +## Removing an App + +Delete the app entry from the `apps` object. Running instances continue until +restarted; new key requests are rejected. + +--- + +## Setting the Gateway App (After Gateway Deployment) + +The `gatewayAppId` field is **optional** during initial KMS deployment. Add it after deploying the Gateway. + +The Gateway is a special app that routes traffic to other apps. Once deployed, add its App ID to your config: + +```json +{ + "gatewayAppId": "0x75537828f2ce51be7289709686A69CbFDbB714F1", + "apps": { + "0x75537828f2ce51be7289709686A69CbFDbB714F1": { + "composeHashes": ["0x..."], + "allowAnyDevice": true + } + } +} +``` + +The `gatewayAppId` is returned in authorization responses and used by KMS for key derivation. + +To trust several gateways, join their App IDs with commas (`"0xaaa...,0xbbb..."`). CVMs accept a gateway whose App ID is contained in this value. + +--- + +## KMS Onboarding (Multi-Node) + +To allow additional KMS nodes to onboard (receive root keys from the primary KMS), whitelist their `mrAggregated` value. + +### Get mrAggregated + +1. **Initial setup**: capture the first KMS measurement with `Onboard.GetAttestationInfo` and add it to `kms.mrAggregated` before bootstrap. An empty array denies all KMS boots. +2. **From dstack-auth logs**: every KMS request is logged with its measurement: + ``` + authorize KmsBootstrap app=... compose=... mr= os=... device=... -> authorized=false (kms mrAggregated not allowed) + ``` + +### Add to Config + +```json +{ + "kms": { + "mrAggregated": ["0x"], + "allowAnyDevice": true + } +} +``` + +> **Note:** All KMS nodes using the same OS image and compose will have the same mrAggregated, so you only need to capture it once. + +--- + +## Verification + +### Check Config is Valid + +```bash +curl -s http://127.0.0.1:3001/ | jq +``` + +Returns `status`, `gatewayAppId`, `kmsContractAddr` and, once `rootEpochs` is +configured, `rootEpoch` and `rootEpochHash`. An invalid `rootEpochs` +configuration returns HTTP 503. + +### Test Boot Authorization + +```bash +curl -s -X POST http://127.0.0.1:3001/bootAuth/app \ + -H "Content-Type: application/json" \ + -d '{ + "appId": "0x", + "composeHash": "0x", + "osImageHash": "0x", + "deviceId": "0x", + "tcbStatus": "UpToDate", + "advisoryIds": [] + }' | jq +``` + +Expected responses: +- `{"isAllowed": true, ...}` - App is authorized +- `{"isAllowed": false, "reason": "app not registered", ...}` - App ID not in config +- `{"isAllowed": false, "reason": "compose hash not allowed", ...}` - Hash not whitelisted +- `{"isAllowed": false, "reason": "tcb status not allowed", ...}` - `tcbStatus` not in `allowedTcbStatuses` + +--- + +## API Endpoints + +| Endpoint | Description | +|----------|-------------| +| `GET /` | Health check and info (`kmsContractAddr`, `gatewayAppId`, `chainId`, `appImplementation`, `rootEpoch`, `rootEpochHash`) | +| `POST /authorizeKms`, `POST /authorizeApp` | Epoch-aware authorization; return an `AuthorizationResult`. See the [KMS authorization protocol](../dstack/kms/README.md#authorization-protocol). | +| `GET /app/` | `{"currentAppEpoch": N}`; 404 for an app that is not configured | +| `POST /bootAuth/kms`, `POST /bootAuth/app` | Legacy boot authorization for older KMS binaries; return `{isAllowed, reason, gatewayAppId}` | + +--- + +## See Also + +- [Deployment Guide](./deployment.md) - Initial setup +- [On-Chain Governance](./onchain-governance.md) - Smart contract-based alternative diff --git a/docs/dstack-gateway.md b/docs/dstack-gateway.md new file mode 100644 index 0000000000..5b4c60ad94 --- /dev/null +++ b/docs/dstack-gateway.md @@ -0,0 +1,260 @@ +# Setup dstack-gateway for Production + +> **This guide is for self-hosted deployments** on your own TDX hardware. For cloud deployments, see [Quickstart](./quickstart.md). + +To set up dstack-gateway for production, you need a wildcard domain and a +Cloudflare API token. You do not need to obtain a certificate yourself: the +gateway links the `certbot` crate and runs ACME over dns-01 in its own process, +keeping the ACME account key and every certificate in its WaveKV store. The +`certbot` CLI under `dstack/certbot/cli` is a testing tool for the same crate +and has no part in this path. + +## Step 1: Set up the wildcard domain + +Set up a second-level wildcard domain using Cloudflare; make sure to disable proxy mode and use **DNS Only**. + +![add-wildcard-domain](./assets/tproxy-add-wildcard-domain.jpg) + +Then create an API token that can edit this zone's DNS records. The gateway uses +it to publish the `_acme-challenge` TXT records that answer dns-01, and the CAA +records that pin issuance to its own ACME account. + +## Step 2: Configure `gateway.toml` + +Focus on these fields in the `core.proxy` section: + +- `listen_addr` & `listen_port`: listen on `0.0.0.0` and preferably `443` in production. If using another port, specify it in the URL (see [URL Format](#url-format)) + +For example, if your base domain is `gateway.example.com`, app ID is ``, listening on `80`, and dstack-gateway is on port 7777, the URL would be `https://-80.gateway.example.com:7777` + +The base domain is not set here: it is the ZT domain you add in Step 3. + +Two more sections matter for certificates: + +```toml +[listeners.admin] +enabled = true +address = "127.0.0.1:9016" +auth_token = "" + +[core.sync] +data_dir = "/var/lib/dstack-gateway/data" +``` + +The admin API is where the ACME settings, the Cloudflare token and the domain +list live — they are stored in the gateway's KV store and there is no file to +put them in, so certificates cannot be issued without it. See +[Admin API authentication](#admin-api-authentication) for the credential +options. `data_dir` is where the ACME account key and the issued certificates +are persisted; point it somewhere writable that survives restarts, or the +gateway asks the CA for a fresh certificate every time it starts and will run +into Let's Encrypt's rate limits. The section is named for cluster sync, but +this store is used whether or not `enabled` is set. + +Start the gateway. + +## Step 3: Give the gateway its ACME configuration + +Open the admin dashboard at `http://` and fill in **Certbot +Configuration**, **DNS Credentials** and **ZT-Domains**, or do the same over the +admin API: + +```bash +ADMIN_ADDR=127.0.0.1:9016 +AUTH=(-H "Authorization: Bearer $ADMIN_API_TOKEN") + +# Start on staging: its certificates are not browser-trusted, but its rate +# limits leave room for mistakes. +curl -sf -X POST "${AUTH[@]}" "http://$ADMIN_ADDR/prpc/SetCertbotConfig" \ + -H "Content-Type: application/json" \ + -d '{"acme_url":"https://acme-staging-v02.api.letsencrypt.org/directory", + "renew_interval_secs":3600,"renew_before_expiration_secs":864000, + "renew_timeout_secs":300}' + +curl -sf -X POST "${AUTH[@]}" "http://$ADMIN_ADDR/prpc/CreateDnsCredential" \ + -H "Content-Type: application/json" \ + -d '{"name":"cloudflare","provider_type":"cloudflare", + "cf_api_token":"'"$CF_API_TOKEN"'","set_as_default":true}' + +curl -sf -X POST "${AUTH[@]}" "http://$ADMIN_ADDR/prpc/AddZtDomain" \ + -H "Content-Type: application/json" \ + -d '{"domain":"gateway.example.com","port":443,"priority":100}' +``` + +Add a ZT domain for every name the gateway terminates TLS on. An entry for +`gateway.example.com` gets a certificate covering `*.gateway.example.com`, which +is what app URLs live under — a certificate for `*.example.com` would not, since +a wildcard does not span a further label. `port` is the port that domain is +served on and `priority` breaks ties when more than one entry could be the +default base domain. + +Certificates are requested on the next renewal round rather than the moment a +domain is added. Watch for them to arrive: + +```bash +curl -sf "${AUTH[@]}" "http://$ADMIN_ADDR/prpc/ListZtDomains" \ + | jq '.domains[] | {domain: .config.domain, cert: .cert_status}' +``` + +`has_cert: true` with a `not_after` roughly 90 days out means the domain is +served. `POST /prpc/RenewCert` forces a round immediately instead of waiting for +`renew_interval_secs`. + +If something else issues the certificate, import it instead of adding a ZT +domain. It is replicated like an issued one, but the gateway never renews it: + +```bash +jq -n --arg cert "$(cat fullchain.pem)" --arg key "$(cat privkey.pem)" \ + '{domain: "gateway.example.com", cert_pem: $cert, key_pem: $key}' \ + | curl -sf -X POST "${AUTH[@]}" "http://$ADMIN_ADDR/prpc/ImportCert" \ + -H "Content-Type: application/json" -d @- +``` + +Pin issuance with `POST /prpc/SetCaa`, which writes CAA records naming Let's +Encrypt and the gateway's ACME account URI for every configured domain, so no +other account can have a certificate issued for them. + +Once the gateway serves traffic on staging certificates, switch to production: +`SetCertbotConfig` with `https://acme-v02.api.letsencrypt.org/directory`, then +`RotateAcmeCredentials` to register an account there and re-pin every domain's +CAA to it. Renewals refuse to run while the stored account and the configured +ACME URL disagree, so do not skip the rotation. + +## Step 4: Adjust Configuration in `vmm.toml` + +Open `vmm.toml` and adjust dstack-gateway configuration in the `gateway` section: + +- `base_domain`: The ZT domain added in Step 3 +- `port`: Same as `listen_port` from `gateway.toml`'s `core.proxy` section + +## URL Format + +The gateway supports the following URL format: +- `[-][].` + +Where: +- ``: The application identifier +- ``: Optional port number (defaults to 80 for HTTP, 443 for HTTPS) +- ``: Optional suffix flags: + - `s`: Enable TLS passthrough (proxy passes encrypted traffic directly to backend) + - `g`: Enable HTTP/2 (gRPC) support (proxy advertises h2 via ALPN) + +Examples: +- `.gateway.example.com` - Default HTTP on port 80 +- `-8080.gateway.example.com` - HTTP on port 8080 +- `-s.gateway.example.com` - TLS passthrough on port 443 +- `-443s.gateway.example.com` - TLS passthrough on port 443 +- `-50051g.gateway.example.com` - HTTP/2/gRPC on port 50051 + +Note: The `s` and `g` suffixes cannot be used together + +## Admin API authentication + +The gateway exposes a separate admin API (used for sync, WireGuard peer management, and other operator RPCs). Configure it in the `listeners.admin` section of `gateway.toml`: + +```toml +[listeners.admin] +enabled = true +address = "0.0.0.0:9016" +# generate with: openssl rand -hex 32 +auth_token = "" +# alternatively, an Apache bcrypt htpasswd file (htpasswd -B -c admin.htpasswd admin) +# htpasswd_file = "/etc/dstack/gateway-admin.htpasswd" +insecure_no_auth = false +``` + +- `enabled`: enable the admin API server. +- `address`: bind address/port for the admin API. +- `auth_token`: shared admin token. It can also be supplied via the environment variables `DSTACK_GATEWAY_ADMIN_TOKEN` or `ADMIN_API_TOKEN` instead of the config file. The older name `admin_token` is still accepted. +- `htpasswd_file`: path to an Apache bcrypt htpasswd file (create with `htpasswd -B -c admin.htpasswd admin`); only bcrypt entries are accepted. Can be used instead of, or alongside, `auth_token`. +- `insecure_no_auth`: development-only escape hatch that disables admin authentication. Never enable it on a network-reachable admin interface. + +The admin server is fail-closed: if it is enabled with no `auth_token` and no `htpasswd_file`, and `insecure_no_auth` is `false`, it refuses to start rather than exposing an unauthenticated admin API. + +Clients authenticate by sending `Authorization: Bearer ` or the `X-Admin-Token: ` header. + +## PROXY protocol on the gateway's own listeners + +Behind a TCP proxy such as HAProxy, the gateway's RPC and admin listeners see +the proxy's address. Set `proxy_protocol = true` in `[listeners.default]`, or in +one listener's section (`[listeners.guest]`, `[listeners.admin]`, +`[listeners.debug]`), to read the client address from a PROXY protocol (v1 or +v2) header; the RPC request logs then carry it as `remote`. With it on, the listener drops connections that send +no header within five seconds, and trusts the header as sent, so make it +reachable only through the proxy (HAProxy `send-proxy-v2`, plus +`check-send-proxy` for health checks). This is separate from +`[core.proxy] inbound_pp_enabled`, which covers the app traffic the gateway +proxies. It works on TCP listeners only: a listener bound to a Unix socket +(`address = "unix:..."`) fails to start with it, so set `proxy_protocol = false` +in that listener's section when `[listeners.default]` turns it on. + +## WireGuard key proof on registration + +A CVM registers its WireGuard public key with `RegisterCvm`. Without a proof +the gateway takes that key on trust, so a CVM that learned another CVM's public +key could claim it while the other CVM's record is recycled, and keep it once +that CVM comes back. Newer CVMs read the node's WireGuard key from `Info` and +attach a proof that they hold the matching private key, bound to their attested +app and instance ids. + +Whether registrations with a missing or invalid proof are refused is one +cluster-wide switch stored in the replicated KV, read with +`GetWgKeyProofConfig` and toggled at runtime with `SetWgKeyProofConfig` +(admin RPCs). It is off until set. Off, a missing or invalid proof is accepted, +and an invalid one is logged as a warning. On, both are refused. +Turn it on only after every CVM sends a proof and every node is upgraded: a node +verifies only the registrations it receives, and its peers accept whatever it +replicates. If the stored policy cannot be decoded, nodes fail closed and +require proofs until it is overwritten. The proof is checked at registration +and not stored, so records written before the policy was turned on are not +re-checked. + +A proof is made for one node's key, so if the CVM's gateway URL is a balancer, +it must keep a connection on one node (`Info` and `RegisterCvm` share it). A +balancer that routes each request separately can split the two, and that node +then refuses the proof. + +## Metrics + +The admin server exposes Prometheus metrics at `GET /metrics`. It is part of the +admin API, so it is only reachable when `listeners.admin.enabled` is true and it +requires the same credentials — unless `insecure_no_auth` is set, which exposes +it along with the rest of the admin API. The series name domains, node ids and +instance counts, which is topology that should not be readable without +authentication. + +```yaml +scrape_configs: + - job_name: dstack-gateway + static_configs: + - targets: [""] + authorization: + credentials: "" +``` + +### Cluster-scoped vs node-local series + +`dstack_gateway_cluster_*` describes replicated state: every node in the cluster +reports the same value, so summing across targets multiplies it by the number of +nodes. Everything else describes what one process did and sums normally. + +```promql +# Instances in the routing table — replicated, so take one node's view +max(dstack_gateway_cluster_instances) + +# Connections across the fleet — node-local, so add them up +sum(dstack_gateway_connections) + +# Nodes disagreeing about who is up: this is the replication-lag signal +max(dstack_gateway_cluster_nodes_active) - min(dstack_gateway_cluster_nodes_active) +``` + +### Series worth alerting on + +| Metric | Why | +|---|---| +| `dstack_gateway_wg_reconfigure_failures_total` | The gateway could not push a WireGuard config: it failed to render, failed to write, or `wg syncconf` rejected the whole file over one bad peer stanza. Routing updates have stopped reaching the data plane while the gateway still looks healthy. | +| `dstack_gateway_kv_decode_failures_total` | A replicated record that fails to decode is skipped, which makes the CVM behind it silently unroutable. Labelled by key prefix. Alert on `> 0`; the magnitude counts how often a bad record was *read*, not how many are bad, so do not read it as a severity. | +| `dstack_gateway_kv_peer_buffered_logs` | Entries still buffered for a peer. Sustained growth means that peer stopped acknowledging and the two nodes are drifting apart. | +| `dstack_gateway_cluster_cert_not_after_seconds` | Certificate expiry per domain; alert on `- time()` falling under the renewal window. Capped at 256 series — compare `dstack_gateway_cluster_cert_domains` to see whether the cap was hit. | +| `dstack_gateway_kv_persist_failures_total` | Periodic snapshots are failing, so a restart replays a growing WAL. | diff --git a/docs/encrypted-env-spec.md b/docs/encrypted-env-spec.md new file mode 100644 index 0000000000..c56afa1ce3 --- /dev/null +++ b/docs/encrypted-env-spec.md @@ -0,0 +1,502 @@ +# Encrypted Environment Variables + +dstack uses an ECIES variant (X25519 + AES-256-GCM) to protect application environment variables. The client encrypts env vars with an X25519 public key at deploy time. At boot, the CVM obtains the corresponding private key from KMS via TDX remote attestation and decrypts inside the TEE. + +## Encryption Public Key Source + +### Key Derivation Chain + +The KMS deterministically derives a per-application key pair from its root CA key: + +``` +KMS root CA key (P-256 KeyPair) + │ + └─ derive_dh_secret(context = [app_id, "env-encrypt-key"]) + → SHA256(derived_P256_key_DER) → 32 bytes + → X25519 StaticSecret (private key = env_crypt_key, delivered to TEE) + → X25519 PublicKey (public key, exposed to client for encryption) +``` + +The same `app_id` always derives the same key pair. + +### Computing `app_id` + +``` +app_id = SHA256(app-compose.json)[0..20] // first 20 bytes, 40 hex characters +``` + +`app-compose.json` here means the normalized JSON bytes that dstack uses for +compose hashing. Do not recompute from a re-formatted or re-serialized variant, +or you may get a different `app_id`. + +> This formula is the **default**. A deployment may pin an explicit `app_id` (in +> `.instance-info`); when it does, use that value — the attested `app_id` is the +> deploy-time value, not necessarily the compose hash. + +Example: + +```javascript +const composeHash = sha256(composeJsonString); // 32 bytes hex +const appId = composeHash.slice(0, 40); // first 20 bytes = 40 hex chars +``` + +### RPC Interface + +The public key is exposed through a two-level RPC chain: + +``` +Client/UI ──→ VMM (GetAppEnvEncryptPubKey) ──→ KMS (GetAppEnvEncryptPubKey) + pass-through proxy actual key derivation +``` + +**Request**: + +```protobuf +message AppId { + bytes app_id = 1; // 20-byte app_id +} +``` + +**Response**: + +```protobuf +message PublicKeyResponse { + bytes public_key = 1; // 32-byte X25519 public key + bytes signature = 2; // Legacy k256 signature (no timestamp) + uint64 timestamp = 3; // Unix timestamp in seconds when response was generated + bytes signature_v1 = 4; // New k256 signature (with timestamp, replay-resistant) +} +``` + +**HTTP call example** (prpc protocol): + +``` +POST {vmm_url}/prpc/Vmm.GetAppEnvEncryptPubKey +Content-Type: application/json + +{"app_id": ""} +``` + +### Public Key Signature Verification + +The response includes k256 (secp256k1) signatures from the KMS root key: + +- **signature** (legacy): `sign(Keccak256("dstack-env-encrypt-pubkey" + ":" + app_id + public_key))` +- **signature_v1** (new): `sign(Keccak256("dstack-env-encrypt-pubkey" + ":" + app_id + timestamp_be_bytes + public_key))` + +## Encrypt/Decrypt Protocol + +### Ciphertext Binary Format + +``` +Offset Length Content +─────────────────────────────────── +0 32 bytes ephemeral_public_key (sender's ephemeral X25519 public key) +32 12 bytes iv (AES-GCM nonce) +44 N+16 bytes ciphertext + auth_tag (AES-GCM ciphertext + authentication tag) +``` + +Stored as raw binary in `.encrypted-env`. SDK functions may return hex strings. + +### Plaintext Format + +```json +{"env": [{"key": "FOO", "value": "bar"}, {"key": "SECRET", "value": "123"}]} +``` + +### Encryption Flow (Client-Side) + +Input: `env_vars` (key-value list), `remote_public_key` (X25519 public key, 32 bytes) + +``` +1. plaintext = JSON.encode({"env": [{"key": k, "value": v}, ...]}) +2. ephemeral_sk = X25519.random_private_key() // 32 bytes +3. ephemeral_pk = X25519.public_key(ephemeral_sk) // 32 bytes +4. shared_secret = X25519.dh(ephemeral_sk, remote_public_key) // 32 bytes +5. iv = random(12) // 12 bytes +6. ciphertext = AES-256-GCM.encrypt( + key = shared_secret, // DH output used directly as AES key, no KDF + nonce = iv, + plaintext = plaintext, + aad = None // no associated data + ) +7. output = ephemeral_pk || iv || ciphertext +``` + +### Decryption Flow (Inside TEE) + +Input: `env_crypt_key` (X25519 private key, 32 bytes), `data` (complete ciphertext) + +``` +1. ephemeral_pk = data[0..32] +2. iv = data[32..44] +3. ciphertext = data[44..] // includes 16-byte GCM auth tag +4. shared_secret = X25519.dh(env_crypt_key, ephemeral_pk) // 32 bytes +5. plaintext = AES-256-GCM.decrypt( + key = shared_secret, + nonce = iv, + ciphertext = ciphertext, + aad = None + ) +6. result = JSON.decode(plaintext) // → {"env": [...]} +``` + +### Algorithm Parameters + +| Parameter | Value | +|-----------|-------| +| Key agreement | X25519 (RFC 7748), **not** ECDH P-256 | +| Symmetric encryption | AES-256-GCM | +| KDF | None — shared secret is used directly as the AES key | +| IV / Nonce | 12 bytes, randomly generated | +| AAD | None (no associated data) | +| Auth tag | 16 bytes (GCM default), appended to ciphertext | +| Key format | Raw 32 bytes, not PEM/DER | + +## `.appkeys.json` File Specification + +Path inside TEE: `/dstack/.host-shared/.appkeys.json` + +### JSON Structure + +```json +{ + "disk_crypt_key": "aabbccdd...", + "env_crypt_key": "0123456789abcdef...(64 hex chars)...", + "k256_key": "...", + "k256_signature": "...", + "gateway_app_id": "some-app-id", + "ca_cert": "-----BEGIN CERTIFICATE-----\n...", + "key_provider": { + "Kms": { + "url": "https://kms.example.com/prpc", + "pubkey": "..." + } + } +} +``` + +### Fields + +| Field | Rust Type | JSON Serialization | Description | +|-------|-----------|-------------------|-------------| +| `disk_crypt_key` | `Vec` | hex string | Disk encryption key | +| `env_crypt_key` | `Vec` | hex string | **X25519 private key (32 bytes = 64 hex chars)**, may be absent | +| `k256_key` | `Vec` | hex string | secp256k1 signing private key | +| `k256_signature` | `Vec` | hex string | KMS signature of the k256 key | +| `gateway_app_id` | `String` | plain string | Gateway application ID | +| `ca_cert` | `String` | PEM string | CA certificate | +| `key_provider` | tagged enum | see below | Key provider information | + +All `Vec` fields are hex strings in JSON (via `serde-human-bytes`, **not** base64). `env_crypt_key` may be absent (defaults to empty). + +### `key_provider` Field + +Rust externally tagged enum — an object with exactly one key: + +```json +{"None": {"key": ""}} +{"Local": {"key": "", "mr": ""}} +{"Tpm": {"key": "", "pubkey": ""}} +{"Kms": {"url": "...", "pubkey": ""}} +``` + +The tag is one of `"None"` / `"Local"` / `"Tpm"` / `"Kms"`. + +`Kms` carried `tmp_ca_key` / `tmp_ca_cert` before guests switched to self-issued +RA-TLS client certificates. Readers ignore the extra fields, so files written by +older guest images still parse. + +## Runtime File/Path Contract (dstack) + +For dstack runtime integration, treat these names/locations as protocol-level +conventions, not arbitrary user-defined outputs: + +- `/dstack/.host-shared/app-compose.json` +- `/dstack/.host-shared/.encrypted-env` +- `/dstack/.host-shared/.appkeys.json` +- `/dstack/.host-shared/.decrypted-env` +- `/dstack/.host-shared/.decrypted-env.json` + +Language examples below may use local relative paths for demonstration, but +production integrations should follow the dstack runtime contract above. + +## Language Implementation Guides + +### Parsing `.appkeys.json` + +**Rust**: + +```rust +use dstack_types::AppKeys; +let keys: AppKeys = serde_json::from_str(&json_str)?; +``` + +**Go**: + +```go +type AppKeys struct { + DiskCryptKey string `json:"disk_crypt_key"` + EnvCryptKey string `json:"env_crypt_key"` + K256Key string `json:"k256_key"` + K256Signature string `json:"k256_signature"` + GatewayAppId string `json:"gateway_app_id"` + CaCert string `json:"ca_cert"` + KeyProvider json.RawMessage `json:"key_provider"` +} + +keyBytes, err := hex.DecodeString(appKeys.EnvCryptKey) +``` + +**Python**: + +```python +import json + +with open(".appkeys.json") as f: + keys = json.load(f) + +env_crypt_key = bytes.fromhex(keys.get("env_crypt_key", "")) +``` + +**TypeScript**: + +```typescript +const keys = JSON.parse(fs.readFileSync(".appkeys.json", "utf-8")); +const envCryptKey = Buffer.from(keys.env_crypt_key ?? "", "hex"); +``` + +**Parsing `key_provider`**: + +```go +var raw map[string]json.RawMessage +json.Unmarshal([]byte(appKeys.KeyProvider), &raw) +``` + +```python +provider = keys["key_provider"] # {"Kms": {"url": "...", ...}} +provider_type = list(provider.keys())[0] # "Kms" +provider_data = provider[provider_type] +``` + +### Decryption + +**Rust** (see `dstack-util/src/crypto.rs`): + +```rust +use aes_gcm::{aead::Aead, Aes256Gcm, KeyInit, Nonce}; +use x25519_dalek::{PublicKey, StaticSecret}; + +pub fn decrypt(secret: [u8; 32], data: &[u8]) -> Result> { + let ephemeral_pk: [u8; 32] = data[..32].try_into()?; + let iv = &data[32..44]; + let ct = &data[44..]; + + let sk = StaticSecret::from(secret); + let pk = PublicKey::from(ephemeral_pk); + let shared = sk.diffie_hellman(&pk).to_bytes(); + + let cipher = Aes256Gcm::new_from_slice(&shared)?; + cipher.decrypt(Nonce::from_slice(iv), ct) +} +``` + +**Go**: + +```go +import ( + "crypto/aes" + "crypto/cipher" + "fmt" + + "golang.org/x/crypto/curve25519" +) + +func Decrypt(envCryptKey [32]byte, data []byte) ([]byte, error) { + if len(data) < 44 { + return nil, fmt.Errorf("ciphertext too short") + } + ephPk := data[:32] + iv := data[32:44] + ct := data[44:] + + shared, err := curve25519.X25519(envCryptKey[:], ephPk) + if err != nil { + return nil, err + } + + block, err := aes.NewCipher(shared) + if err != nil { + return nil, err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + return gcm.Open(nil, iv, ct, nil) +} +``` + +**Python**: + +```python +from cryptography.hazmat.primitives.asymmetric.x25519 import ( + X25519PrivateKey, X25519PublicKey, +) +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +def decrypt(env_crypt_key: bytes, data: bytes) -> bytes: + if len(data) < 44: + raise ValueError("ciphertext too short") + eph_pk = X25519PublicKey.from_public_bytes(data[:32]) + iv = data[32:44] + ct = data[44:] + + sk = X25519PrivateKey.from_private_bytes(env_crypt_key) + shared = sk.exchange(eph_pk) + + return AESGCM(shared).decrypt(iv, ct, None) +``` + +**TypeScript**: + +```typescript +import { x25519 } from "@noble/curves/ed25519"; +import crypto from "crypto"; + +async function decrypt(envCryptKey: Uint8Array, data: Uint8Array): Promise { + const ephPk = data.slice(0, 32); + const iv = data.slice(32, 44); + const ct = data.slice(44); + + const shared = x25519.getSharedSecret(envCryptKey, ephPk); + + const importedKey = await crypto.subtle.importKey( + "raw", shared, { name: "AES-GCM", length: 256 }, false, ["decrypt"] + ); + const plaintext = await crypto.subtle.decrypt( + { name: "AES-GCM", iv }, importedKey, ct + ); + return new Uint8Array(plaintext); +} +``` + +### Encryption + +**Python** (see `sdk/python/src/dstack_sdk/encrypt_env_vars.py`): + +```python +import json, secrets +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +def encrypt(envs: list[dict], public_key: bytes) -> bytes: + plaintext = json.dumps({"env": envs}).encode() + + sk = X25519PrivateKey.generate() + eph_pk = sk.public_key().public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + + remote_pk = X25519PublicKey.from_public_bytes(public_key) + shared = sk.exchange(remote_pk) + + iv = secrets.token_bytes(12) + ct = AESGCM(shared).encrypt(iv, plaintext, None) + + return eph_pk + iv + ct +``` + +**TypeScript** (see `sdk/js/src/encrypt-env-vars.ts`): + +```typescript +async function encrypt(envs: EnvVar[], publicKey: Uint8Array): Promise { + const plaintext = new TextEncoder().encode(JSON.stringify({ env: envs })); + + const privateKey = x25519.utils.randomPrivateKey(); + const ephPk = x25519.getPublicKey(privateKey); + const shared = x25519.getSharedSecret(privateKey, publicKey); + + const importedKey = await crypto.subtle.importKey( + "raw", shared, { name: "AES-GCM", length: 256 }, true, ["encrypt"] + ); + const iv = crypto.getRandomValues(new Uint8Array(12)); + const ct = new Uint8Array( + await crypto.subtle.encrypt({ name: "AES-GCM", iv }, importedKey, plaintext) + ); + + const result = new Uint8Array(ephPk.length + iv.length + ct.length); + result.set(ephPk); + result.set(iv, ephPk.length); + result.set(ct, ephPk.length + iv.length); + return result; +} +``` + +## Security Considerations + +### Encryption provides confidentiality, not origin authentication + +This scheme ensures only the target CVM can decrypt env vars (confidentiality), but it +cannot prove who created them (origin authentication). Because `app_id` is public and +`GetAppEnvEncryptPubKey` is callable with that `app_id`, any party with VMM access can: + +1. fetch the app encryption public key, +2. encrypt a different env payload, +3. submit the replacement payload. + +The CVM will decrypt and use that payload if decryption succeeds. + +### Developer responsibility: add application-layer authenticity checks + +Applications must validate env authenticity at startup. Recommended patterns: + +1. **APP_LAUNCH_TOKEN pattern**: include `APP_LAUNCH_TOKEN` in encrypted env vars and + verify its hash in prelaunch (the hash is measured via `app-compose.json`). +2. **custom signature**: sign env payload off-chain with a developer-held key and + verify inside the app before use. +3. **embedded shared secret**: include a developer/app-only secret in env vars and + fail startup if it does not match expected value. + +For production guidance, see: +- [security-best-practices.md](./security/security-best-practices.md#authenticated-envs-and-user_config) +- [security-model.md](./security/security-model.md#environment-variables-need-application-layer-authentication) + +### Related caveat: `user_config` + +`user_config` has the same integrity/authenticity risk and should be validated at the +application layer as well. + +## End-to-End Flow + +``` +┌─────────────────────────────────────────────────────────────────┐ +│ Deployment Phase (Client-Side) │ +│ │ +│ 1. Write docker-compose.yaml │ +│ 2. Normalize to app-compose.json │ +│ 3. app_id = SHA256(app-compose.json)[0..20] │ +│ 4. Call VMM.GetAppEnvEncryptPubKey({ app_id }) │ +│ → VMM proxies → KMS derives X25519 key pair from root key │ +│ → Returns PublicKeyResponse { public_key, signature, ... } │ +│ 5. Encrypt env vars with public_key → encrypted-env file │ +│ 6. Submit app-compose.json + encrypted-env to VMM for deploy │ +└─────────────────────────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────────────────────────┐ +│ Boot Phase (Inside CVM / TEE) │ +│ │ +│ 7. dstack-util setup reads encrypted-env from host-shared │ +│ 8. Requests AppKeys from KMS via TDX remote attestation │ +│ → KMS verifies TDX quote → derives and returns │ +│ env_crypt_key (X25519 private key) │ +│ 9. AppKeys written to /dstack/.host-shared/.appkeys.json │ +│ 10. Decrypts encrypted-env using env_crypt_key → JSON plaintext │ +│ 11. Writes .decrypted-env (shell format) and │ +│ .decrypted-env.json (JSON format) │ +│ 12. App containers consume env vars via env_file or direct read │ +└─────────────────────────────────────────────────────────────────┘ +``` diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000000..4f43b053a8 --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,33 @@ +# FAQ + +## CVM status turns to `exited` immediately + +First, check the stderr output of the CVM. + +> [!TIP] +> To view the CVM's stderr, append `ch=stderr` to the end of the log URL. +> If the log URL is `/logs?id=&follow=true&ansi=false&lines=20` +> The stderr URL would be `/logs?id=&follow=true&ansi=false&lines=20&ch=stderr`. + +If you see an error message in CVM's stderr output: + +``` +Could not access KVM kernel module: Permission denied +gemu-system-x86_64: -accel kvm: failed to initialize kvm: Permission denied +``` + +This means your supervisor is not running with an account that belongs to the `libvirt` and `kvm` groups. You need to ensure your account is added to these two groups. You can check this by running the following command: + +```shell +id +``` + +If you are not in these groups, you likely won't have the necessary privileges to run QEMU. + +Once you have the required privileges, make sure the supervisor process is shut down: + +```shell +ps aux | grep supervisor | grep $(whoami) | grep -v grep +``` + +Log out of all your sessions and log back in. Check your groups with the `id` command, and this should resolve the issue. diff --git a/docs/formal/key-rotation/DiskMigration.cfg b/docs/formal/key-rotation/DiskMigration.cfg new file mode 100644 index 0000000000..5ef9caddc3 --- /dev/null +++ b/docs/formal/key-rotation/DiskMigration.cfg @@ -0,0 +1,12 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + MaxEpoch = 3 +INVARIANTS + TypeOK + NoBootFailure + DataRecoverable + NoFormatOverData + RunningIsMigrated diff --git a/docs/formal/key-rotation/DiskMigration.tla b/docs/formal/key-rotation/DiskMigration.tla new file mode 100644 index 0000000000..23b3cf56fc --- /dev/null +++ b/docs/formal/key-rotation/DiskMigration.tla @@ -0,0 +1,186 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +---------------------------- MODULE DiskMigration ---------------------------- +(***************************************************************************) +(* Data disk setup and LUKS key migration across KMS key epochs, as *) +(* implemented by dstack-util (system_setup.rs: setup_data_disk, *) +(* luks_setup, open_encrypted_volume; system_setup/luks.rs: *) +(* sync_luks_epochs). *) +(* *) +(* A key epoch abstracts the (root, app) epoch pair: the disk key differs *) +(* per epoch and the KMS serves every epoch up to the current one. A boot *) +(* fetches its keys once, so it targets the epoch current at its start; *) +(* the KMS may rotate at any time. *) +(* *) +(* The header has two keyslots and a token recording a keyslot and its *) +(* epoch. Each cryptsetup command on the device (luksFormat, luksAddKey, *) +(* luksKillSlot, token import, config --label) is atomic: it writes a new *) +(* keyslot area before the header copies, each synced, and an outdated *) +(* copy is repaired from the newer one on the next load. A crash can stop *) +(* the boot between any two commands. *) +(***************************************************************************) +EXTENDS Integers + +CONSTANTS MaxEpoch + +Slots == {0, 1} +NoKey == -1 +NoToken == [slot |-> -1, epoch |-> -1] +Tokens == {NoToken} \cup [slot: Slots, epoch: 0..MaxEpoch] + +VARIABLES + current, \* current key epoch on chain + target, \* epoch whose keys this boot fetched + luks, \* the device holds a LUKS header + slots, \* keyslots: Slots -> key epoch or NoKey + token, \* the dstack-kms token + init, \* the header carries the initializing label + pc, \* boot step + oldSlot, \* sync_luks_epochs: the recorded keyslot being migrated from + slot, \* sync_luks_epochs: the keyslot holding the target key + hasData \* applications have written data to the volume + +vars == <> +boot == <> + +Keyslots == {s \in Slots: slots[s] # NoKey} +StoredEpoch == IF token = NoToken THEN 0 ELSE token.epoch +\* unlocked_keyslot: the first keyslot the target key opens. +Unlocked == {s \in Slots: slots[s] = target} +First(S) == IF 0 \in S THEN 0 ELSE 1 + +Init == + /\ current \in 0..MaxEpoch + /\ target = 0 + /\ luks = FALSE + /\ slots = [s \in Slots |-> NoKey] + /\ token = NoToken + /\ init = FALSE + /\ pc = "off" + /\ oldSlot = 0 /\ slot = 0 + /\ hasData = FALSE + +Rotate == + /\ current < MaxEpoch + /\ current' = current + 1 + /\ UNCHANGED <> + +\* setup_data_disk: an initialized disk is opened; an interrupted +\* initialization or a blank disk is formatted. +Boot == + /\ pc = "off" + /\ target' = current + /\ pc' = IF luks /\ ~init THEN "sync" ELSE "format" + /\ UNCHANGED <> + +\* luks_setup: luksFormat with the initializing label, key in keyslot 0. +Format == + /\ pc = "format" + /\ luks' = TRUE /\ init' = TRUE + /\ slots' = [s \in Slots |-> IF s = 0 THEN target ELSE NoKey] + /\ token' = NoToken + /\ pc' = IF target > 0 THEN "formatToken" ELSE "sync" + /\ UNCHANGED <> + +FormatToken == + /\ pc = "formatToken" + /\ token' = [slot |-> 0, epoch |-> target] + /\ pc' = "sync" + /\ UNCHANGED <> + +\* sync_luks_epochs, entry. +Sync == + /\ pc = "sync" + /\ LET old == IF token = NoToken THEN 0 ELSE token.slot IN + CASE StoredEpoch > target -> pc' = "fail" /\ UNCHANGED <> + [] Unlocked # {} -> pc' = "record" /\ slot' = First(Unlocked) /\ UNCHANGED oldSlot + [] StoredEpoch = target -> pc' = "fail" /\ UNCHANGED <> + \* The recorded keyslot must exist and open with the recorded epoch. + [] old \notin Keyslots \/ slots[old] # StoredEpoch -> + pc' = "fail" /\ UNCHANGED <> + [] OTHER -> pc' = "dropStale" /\ oldSlot' = old /\ UNCHANGED slot + /\ UNCHANGED <> + +\* Drop the keyslot whose epochs were never recorded, to make room. +DropStale == + /\ pc = "dropStale" + /\ slots' = [s \in Slots |-> IF s = oldSlot THEN slots[s] ELSE NoKey] + /\ pc' = "addKey" + /\ UNCHANGED <> + +AddKey == + /\ pc = "addKey" + /\ slots' = [slots EXCEPT ![1 - oldSlot] = target] + /\ slot' = 1 - oldSlot + /\ pc' = "record" + /\ UNCHANGED <> + +\* Record the target epoch for the keyslot that holds it; a legacy disk at +\* epoch 0 keeps no token. +Record == + /\ pc = "record" + /\ LET legacy == target = 0 /\ token = NoToken IN + token' = IF legacy THEN token ELSE [slot |-> slot, epoch |-> target] + /\ pc' = "killOld" + /\ UNCHANGED <> + +KillOld == + /\ pc = "killOld" + /\ slots' = [s \in Slots |-> IF s = slot THEN slots[s] ELSE NoKey] + /\ pc' = "open" + /\ UNCHANGED <> + +\* luksOpen with the target key, from the header loaded after the changes. +Open == + /\ pc = "open" + /\ pc' = CASE slots[slot] # target -> "fail" + [] init -> "mkfs" + [] OTHER -> "running" + /\ UNCHANGED <> + +\* mkfs on the volume, then cryptsetup config --label= on the device. +Mkfs == + /\ pc = "mkfs" + /\ init' = FALSE + /\ pc' = "running" + /\ UNCHANGED <> + +WriteData == + /\ pc = "running" /\ ~hasData + /\ hasData' = TRUE + /\ UNCHANGED <> + +\* Shutdown, a crash at any step, or a restart after a failed boot. +Stop == + /\ pc # "off" + /\ pc' = "off" + /\ UNCHANGED <> + +Next == + \/ Rotate \/ Boot \/ Format \/ FormatToken \/ Sync \/ DropStale \/ AddKey + \/ Record \/ KillOld \/ Open \/ Mkfs \/ WriteData \/ Stop + +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +TypeOK == + /\ current \in 0..MaxEpoch /\ target \in 0..current + /\ slots \in [Slots -> {NoKey} \cup (0..MaxEpoch)] + /\ token \in Tokens + +\* A boot never fails: a failed boot fails again on every retry. +NoBootFailure == pc # "fail" + +\* Data, once written, stays under a key the KMS still serves. +DataRecoverable == hasData => (luks /\ \E s \in Keyslots: slots[s] <= current) + +\* Reinitialization never runs over data. +NoFormatOverData == pc = "format" => ~hasData + +\* A running disk is keyed by its boot's epoch alone, and records it. +RunningIsMigrated == + pc = "running" => + /\ Keyslots = {slot} /\ slots[slot] = target + /\ IF token = NoToken THEN target = 0 ELSE token = [slot |-> slot, epoch |-> target] +============================================================================= diff --git a/docs/formal/key-rotation/EnvUpdate.cfg b/docs/formal/key-rotation/EnvUpdate.cfg new file mode 100644 index 0000000000..bf77ce3ce2 --- /dev/null +++ b/docs/formal/key-rotation/EnvUpdate.cfg @@ -0,0 +1,12 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + MaxEpoch = 2 + MaxOwnerWrites = 2 + Lossy = TRUE + FailClosed = TRUE +INVARIANTS + OwnerUpdateKept + NoAppEnv diff --git a/docs/formal/key-rotation/EnvUpdate.tla b/docs/formal/key-rotation/EnvUpdate.tla new file mode 100644 index 0000000000..69a0cd06c4 --- /dev/null +++ b/docs/formal/key-rotation/EnvUpdate.tla @@ -0,0 +1,112 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +------------------------------ MODULE EnvUpdate ------------------------------ +(***************************************************************************) +(* Environment re-encryption at boot (dstack-util unseal_env_vars) and the *) +(* VMM's once-per-boot update window (vmm app.rs update_sealed_env and the *) +(* boot.progress handler). *) +(* *) +(* An env value records which owner write it carries, the key epoch it is *) +(* encrypted to, and who stored it. The VMM opens the window when it *) +(* launches the VM, recording the stored env; the first update closes it *) +(* and is applied only over that env; boot progress reaching application *) +(* code also closes it. Owner updates (UpdateVm) can happen at any time. *) +(* *) +(* Lossy lets either host notification, or the answer to the guest's *) +(* update, be lost. With FailClosed (#1546) the guest starts applications *) +(* only once the host answered its update, retrying or stopping the boot *) +(* otherwise; without it, an unanswered update is only logged. *) +(***************************************************************************) +EXTENDS Naturals + +CONSTANTS MaxEpoch, MaxOwnerWrites, Lossy, FailClosed + +None == [owner |-> 0, epoch |-> 0, by |-> "none"] + +VARIABLES + current, \* current key epoch + store, \* env stored by the VMM + ownerWrites, \* number of owner updates so far + window, \* env recorded when the window opened, or None when closed + vm, \* guest step + seen \* env the guest read at boot + +vars == <> + +Init == + /\ current = 0 + /\ store = [owner |-> 0, epoch |-> 0, by |-> "owner"] + /\ ownerWrites = 0 + /\ window = None + /\ vm = "off" + /\ seen = None + +\* The VMM applies an update from the guest: once per boot, only over the +\* env the boot started with. +Deliver(env, empty) == + /\ window' = None + /\ store' = IF window # None /\ ~empty /\ store = window THEN env ELSE store + +Launch == + /\ vm = "off" + /\ vm' = "booting" + /\ window' = store + /\ seen' = store + /\ UNCHANGED <> + +\* Re-encrypt to the current epoch if needed and send it, empty otherwise. +\* An unanswered update, whether lost on the way or after the VMM applied +\* it, is retried under FailClosed; the boot may also stop (Stop). +GuestPush == + /\ vm = "booting" + /\ LET env == [owner |-> seen.owner, epoch |-> current, by |-> "guest"] + empty == seen.epoch = current + unanswered == IF FailClosed THEN "booting" ELSE "pushed" + IN \/ Deliver(env, empty) /\ vm' = "pushed" + \/ Lossy /\ Deliver(env, empty) /\ vm' = unanswered + \/ Lossy /\ UNCHANGED <> /\ vm' = unanswered + /\ UNCHANGED <> + +\* boot.progress "init-script": application code starts after this. +Progress == + /\ vm = "pushed" + /\ vm' = "app" + /\ \/ window' = None + \/ Lossy /\ UNCHANGED window + /\ UNCHANGED <> + +\* Application code calls the host API with an env of its choosing. +AppUpdate == + /\ vm = "app" + /\ Deliver([owner |-> seen.owner, epoch |-> current, by |-> "app"], FALSE) + /\ UNCHANGED <> + +OwnerUpdate == + /\ ownerWrites < MaxOwnerWrites + /\ ownerWrites' = ownerWrites + 1 + /\ store' = [owner |-> ownerWrites + 1, epoch |-> current, by |-> "owner"] + /\ UNCHANGED <> + +Stop == + /\ vm # "off" + /\ vm' = "off" + /\ window' = None + /\ UNCHANGED <> + +Rotate == + /\ vm = "off" /\ current < MaxEpoch + /\ current' = current + 1 + /\ UNCHANGED <> + +Next == Launch \/ GuestPush \/ Progress \/ AppUpdate \/ OwnerUpdate \/ Stop \/ Rotate + +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +\* The latest owner update is never replaced by an older one. +OwnerUpdateKept == store.owner = ownerWrites + +\* Application code never replaces the env. +NoAppEnv == store.by # "app" +============================================================================= diff --git a/docs/formal/key-rotation/EnvUpdateLossy.cfg b/docs/formal/key-rotation/EnvUpdateLossy.cfg new file mode 100644 index 0000000000..679e7c6431 --- /dev/null +++ b/docs/formal/key-rotation/EnvUpdateLossy.cfg @@ -0,0 +1,12 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + MaxEpoch = 2 + MaxOwnerWrites = 2 + Lossy = TRUE + FailClosed = FALSE +INVARIANTS + OwnerUpdateKept + NoAppEnv diff --git a/docs/formal/key-rotation/EpochPolicy.cfg b/docs/formal/key-rotation/EpochPolicy.cfg new file mode 100644 index 0000000000..18cb9cfe48 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicy.cfg @@ -0,0 +1,20 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Values = {v1, v2} + Keys = {1, 2} + MaxEpoch = 2 + MaxRegistrations = 5 + KeyByChainHash = FALSE + Composes = {c1} + MaxAppEpoch = 2 + LegacyIgnoresAppEpoch = FALSE +CHECK_DEADLOCK FALSE +INVARIANTS + TypeOK + RevocationIsTotal + AppKeyMatchesSelectedRow +PROPERTIES + RegistrationStartsEmpty diff --git a/docs/formal/key-rotation/EpochPolicy.tla b/docs/formal/key-rotation/EpochPolicy.tla new file mode 100644 index 0000000000..0a33a423e6 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicy.tla @@ -0,0 +1,166 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +----------------------------- MODULE EpochPolicy ----------------------------- +(***************************************************************************) +(* Epoch-scoped policy of DstackKms and DstackApp, and key release decided *) +(* on the selected rows. *) +(* *) +(* Root side (DstackKms): one row of allowed values (OS images; KMS MRs *) +(* and devices alike) per root epoch, written by *AtEpochs over a range *) +(* of registered rows. A pending epoch can be popped and registered again, *) +(* with the same or other keys. Rows are keyed by registration *) +(* (RootEpoch.registration); KeyByChainHash = TRUE models the earlier *) +(* contract, which keyed them by chain hash. *) +(* *) +(* App side (DstackApp): one row of allowed compose hashes per app epoch, *) +(* written over a range up to the next epoch. An app policy predating app *) +(* epochs (v0.5.x, v0.6.0) has only its flat mapping, which is row 0, and *) +(* epoch-less setters writing it; DstackKms authorizes it through *) +(* isAppAllowed for app epoch 0 only. Its owner may upgrade it at any *) +(* time, keeping the mapping as row 0. LegacyIgnoresAppEpoch = TRUE drops *) +(* the app epoch 0 check of that fallback. *) +(***************************************************************************) +EXTENDS Naturals, Sequences + +CONSTANTS Values, Keys, MaxEpoch, MaxRegistrations, KeyByChainHash, + Composes, MaxAppEpoch, LegacyIgnoresAppEpoch + +VARIABLES + keys, \* keys of the registered root epochs, epoch e at index e + 1 + regs, \* registration of each registered root epoch + nextReg, \* registrations so far + cur, \* current root epoch + rows, \* <> pairs allowed + revoked, \* values removed from every registered row, not added since + legacy, \* the app policy predates app epochs + appCur, \* current app epoch + appRows, \* <> pairs allowed + appRevoked, \* compose hashes removed from every app row, not added since + leaked, \* a key released for a revoked value or compose hash + mismatched \* an app key released for an app epoch whose row disallows it + +vars == <> +rootVars == <> +appVars == <> +ghostVars == <> + +Latest == Len(keys) - 1 +RowKey(ks, rs, e) == IF KeyByChainHash THEN SubSeq(ks, 1, e + 1) ELSE <> +Row(e) == {v \in Values: <> \in rows} +AppRow(a) == {c \in Composes: <> \in appRows} + +Init == + /\ \E k \in Keys: keys = <> + /\ regs = <<0>> /\ nextReg = 1 /\ cur = 0 + /\ rows = {} /\ revoked = {} + /\ legacy \in BOOLEAN /\ appCur = 0 /\ appRows = {} /\ appRevoked = {} + /\ leaked = {} /\ mismatched = FALSE + +\* ---- DstackKms ---- +Register(k) == + /\ Latest < MaxEpoch /\ nextReg < MaxRegistrations + /\ keys' = Append(keys, k) + /\ regs' = Append(regs, nextReg) + /\ nextReg' = nextReg + 1 + /\ UNCHANGED <> + +Activate == + /\ cur < Latest + /\ cur' = cur + 1 + /\ UNCHANGED <> + +Pop == + /\ Latest > cur + /\ keys' = SubSeq(keys, 1, Latest) + /\ regs' = SubSeq(regs, 1, Latest) + /\ UNCHANGED <> + +\* add*AtEpochs / remove*AtEpochs(from, to, v); one row is from = to. +Write(from, to, v, allowed) == + /\ from <= to /\ to <= Latest + /\ LET written == {<>: e \in from..to} + IN rows' = IF allowed THEN rows \cup written ELSE rows \ written + /\ revoked' = IF allowed THEN revoked \ {v} + ELSE IF from = 0 /\ to = Latest THEN revoked \cup {v} + ELSE revoked + /\ UNCHANGED <> + +\* ---- DstackApp ---- +AppWrite(from, to, c, allowed) == + /\ ~legacy /\ from <= to /\ to <= appCur + 1 + /\ LET written == {<>: a \in from..to} + IN appRows' = IF allowed THEN appRows \cup written ELSE appRows \ written + /\ appRevoked' = IF allowed THEN appRevoked \ {c} + ELSE IF from = 0 /\ to = appCur + 1 THEN appRevoked \cup {c} + ELSE appRevoked + /\ UNCHANGED <> + +\* The epoch-less setters of a legacy policy write its only row. +LegacyWrite(c, allowed) == + /\ legacy + /\ appRows' = IF allowed THEN appRows \cup {<<0, c>>} ELSE appRows \ {<<0, c>>} + /\ appRevoked' = IF allowed THEN appRevoked \ {c} ELSE appRevoked \cup {c} + /\ UNCHANGED <> + +Upgrade == + /\ legacy /\ legacy' = FALSE + /\ UNCHANGED <> + +Advance == + /\ ~legacy /\ appCur < MaxAppEpoch + /\ appCur' = appCur + 1 + /\ UNCHANGED <> + +\* ---- Key release ---- +\* kms_serve releases keys of the current epoch at most; the key handover +\* may carry a registered pending one. +KmsRelease(op, e, v) == + /\ e <= (IF op = "kms_export_keys" THEN Latest ELSE cur) + /\ v \in Row(e) + /\ leaked' = IF v \in revoked THEN leaked \cup {<<"root", e, v>>} ELSE leaked + /\ UNCHANGED <> + +\* app_get_key for root epoch e <= current and app epoch a. A legacy policy +\* is asked through isAppAllowed, which reads its only row. +AppRelease(e, a, v, c) == + /\ e <= cur /\ v \in Row(e) + /\ IF legacy + THEN (a = 0 \/ LegacyIgnoresAppEpoch) /\ c \in AppRow(0) + ELSE a <= appCur /\ c \in AppRow(a) + /\ leaked' = leaked \cup (IF v \in revoked THEN {<<"root", e, v>>} ELSE {}) + \cup (IF c \in appRevoked THEN {<<"app", a, c>>} ELSE {}) + /\ mismatched' = (mismatched \/ c \notin AppRow(a)) + /\ UNCHANGED <> + +Next == + \/ Activate \/ Pop \/ Upgrade \/ Advance + \/ \E k \in Keys: Register(k) + \/ \E from, to \in 0..MaxEpoch, v \in Values, allowed \in BOOLEAN: Write(from, to, v, allowed) + \/ \E from, to \in 0..MaxAppEpoch + 1, c \in Composes, allowed \in BOOLEAN: AppWrite(from, to, c, allowed) + \/ \E c \in Composes, allowed \in BOOLEAN: LegacyWrite(c, allowed) + \/ \E op \in {"kms_serve", "kms_export_keys"}, e \in 0..MaxEpoch, v \in Values: KmsRelease(op, e, v) + \/ \E e \in 0..MaxEpoch, a \in 0..MaxAppEpoch, v \in Values, c \in Composes: AppRelease(e, a, v, c) + +Spec == Init /\ [][Next]_vars + +----------------------------------------------------------------------------- +TypeOK == cur <= Latest /\ Latest <= MaxEpoch /\ Len(regs) = Len(keys) /\ appCur <= MaxAppEpoch + /\ (legacy => appCur = 0) + +\* A value or compose hash removed from every row gets no key of any root or +\* app epoch, for any operation, until it is added again; including through a +\* root epoch popped and registered again, and across the upgrade of a legacy +\* app policy. +RevocationIsTotal == leaked = {} + +\* An app key of app epoch a is released only when row a allows the compose +\* hash; for a legacy policy, only app epoch 0, its flat mapping. +AppKeyMatchesSelectedRow == ~mismatched + +\* A root epoch registration starts with an empty row, whatever its keys. +RegistrationStartsEmpty == + [][Len(keys') > Len(keys) => + \A v \in Values: <> \notin rows']_vars +============================================================================= diff --git a/docs/formal/key-rotation/EpochPolicyChainHash.cfg b/docs/formal/key-rotation/EpochPolicyChainHash.cfg new file mode 100644 index 0000000000..58751f4fb8 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicyChainHash.cfg @@ -0,0 +1,16 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Values = {v1, v2} + Keys = {1, 2} + MaxEpoch = 2 + MaxRegistrations = 5 + KeyByChainHash = TRUE + Composes = {c1} + MaxAppEpoch = 2 + LegacyIgnoresAppEpoch = FALSE +CHECK_DEADLOCK FALSE +INVARIANTS + RevocationIsTotal diff --git a/docs/formal/key-rotation/EpochPolicyLegacyAppEpoch.cfg b/docs/formal/key-rotation/EpochPolicyLegacyAppEpoch.cfg new file mode 100644 index 0000000000..b96abd94a7 --- /dev/null +++ b/docs/formal/key-rotation/EpochPolicyLegacyAppEpoch.cfg @@ -0,0 +1,16 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Values = {v1, v2} + Keys = {1, 2} + MaxEpoch = 2 + MaxRegistrations = 5 + KeyByChainHash = FALSE + Composes = {c1} + MaxAppEpoch = 2 + LegacyIgnoresAppEpoch = TRUE +CHECK_DEADLOCK FALSE +INVARIANTS + AppKeyMatchesSelectedRow diff --git a/docs/formal/key-rotation/KmsRotation.cfg b/docs/formal/key-rotation/KmsRotation.cfg new file mode 100644 index 0000000000..e1956460a7 --- /dev/null +++ b/docs/formal/key-rotation/KmsRotation.cfg @@ -0,0 +1,13 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +SPECIFICATION Spec +CONSTANTS + Nodes = {n1, n2, n3} + MaxRoots = 4 +SYMMETRY Symmetry +CHECK_DEADLOCK FALSE +INVARIANTS + ReleasedFromRegisteredRoots +PROPERTIES + HandoverAgreesWithRegistry diff --git a/docs/formal/key-rotation/KmsRotation.tla b/docs/formal/key-rotation/KmsRotation.tla new file mode 100644 index 0000000000..3a78bada7f --- /dev/null +++ b/docs/formal/key-rotation/KmsRotation.tla @@ -0,0 +1,123 @@ +\* SPDX-FileCopyrightText: © 2026 Phala Network +\* SPDX-License-Identifier: Apache-2.0 + +----------------------------- MODULE KmsRotation ----------------------------- +(***************************************************************************) +(* KMS root epochs: the DstackKms registry, KMS keyrings, onboarding and *) +(* key release, as implemented by the contract and dstack-kms *) +(* (main_service.rs servable_epoch/authorized_epoch, onboard_service.rs *) +(* ensure_handover_registered). *) +(* *) +(* A root is an opaque fresh value; a keyring is the sequence of roots of *) +(* epochs 0..latest. A node serves the current epoch when its keyring *) +(* holds it and the chain hash over epochs 0..current matches the *) +(* registry, which is equality of the prefixes. *) +(* *) +(* The owner registers whatever a generating node attests (the evidence *) +(* binds the epoch and keys, not the earlier roots) and activates an epoch *) +(* once some node can serve it. Operators may wipe a node to re-onboard. *) +(***************************************************************************) +EXTENDS Naturals, Sequences, TLC + +CONSTANTS Nodes, MaxRoots + +VARIABLES + reg, \* registered roots, epoch e at index e + 1 + cur, \* current epoch + kr, \* keyring of each node; <<>> before bootstrap or onboarding + fresh, \* next fresh root + released \* <> pairs whose derived keys were released + +vars == <> + +Prefix(s, n) == SubSeq(s, 1, n) +Latest(n) == Len(kr[n]) - 1 + +\* servable_epoch: the keyring holds the current epoch with its chain hash. +Serves(n) == Len(reg) > 0 /\ Len(kr[n]) > cur /\ Prefix(kr[n], cur + 1) = Prefix(reg, cur + 1) + +Init == + /\ reg = <<>> /\ cur = 0 /\ kr = [n \in Nodes |-> <<>>] + /\ fresh = 1 /\ released = {} + +Bootstrap(n) == + /\ kr[n] = <<>> /\ fresh <= MaxRoots + /\ kr' = [kr EXCEPT ![n] = <>] + /\ fresh' = fresh + 1 + /\ UNCHANGED <> + +\* Handover from src (onboard_service.rs ensure_handover_registered): src +\* passes its kms_export_keys self-check (it serves the current epoch) and +\* holds nothing beyond the latest registered epoch. Epochs past the current +\* one are checked only through the latest registered epoch's chain hash, +\* so a source holding some of them must hold the latest one and match it. +\* A rotation starts from the current epoch with nothing pending. +CanHandOver(src, rotate) == + LET held == Latest(src) + latest == Len(reg) - 1 + IN /\ Serves(src) + /\ held <= latest + /\ ~(held > cur /\ held < latest) + /\ held = latest => kr[src] = reg + /\ rotate => held = cur /\ latest = cur + +Join(dst, src) == + /\ kr[dst] = <<>> /\ CanHandOver(src, FALSE) + /\ kr' = [kr EXCEPT ![dst] = kr[src]] + /\ UNCHANGED <> + +RotationJoin(dst, src) == + /\ kr[dst] = <<>> /\ CanHandOver(src, TRUE) /\ fresh <= MaxRoots + /\ kr' = [kr EXCEPT ![dst] = Append(kr[src], fresh)] + /\ fresh' = fresh + 1 + /\ UNCHANGED <> + +\* registerRootEpoch with the keys node n generated for the next epoch. +Register(n) == + /\ Len(kr[n]) = Len(reg) + 1 + /\ reg' = Append(reg, kr[n][Len(reg) + 1]) + /\ UNCHANGED <> + +Activate == + /\ Len(reg) > cur + 1 + /\ \E n \in Nodes: Len(kr[n]) > cur + 1 /\ Prefix(kr[n], cur + 2) = Prefix(reg, cur + 2) + /\ cur' = cur + 1 + /\ UNCHANGED <> + +Pop == + /\ Len(reg) > cur + 1 + /\ reg' = SubSeq(reg, 1, Len(reg) - 1) + /\ UNCHANGED <> + +Wipe(n) == + /\ kr[n] # <<>> + /\ kr' = [kr EXCEPT ![n] = <<>>] + /\ UNCHANGED <> + +\* GetAppKey for epoch e <= current, current or historical. +Release(n, e) == + /\ Serves(n) /\ e <= cur + /\ released' = released \cup {<>} + /\ UNCHANGED <> + +Next == + \/ Activate \/ Pop + \/ \E n \in Nodes: Bootstrap(n) \/ Register(n) \/ Wipe(n) \/ \E e \in 0..cur: Release(n, e) + \/ \E d, s \in Nodes: d # s /\ (Join(d, s) \/ RotationJoin(d, s)) + +Spec == Init /\ [][Next]_vars + +Symmetry == Permutations(Nodes) + +----------------------------------------------------------------------------- +\* Keys are only ever released from the registered root of their epoch, so +\* no two roots are ever used for one epoch. +ReleasedFromRegisteredRoots == + \A r \in released: r[1] <= cur /\ reg[r[1] + 1] = r[2] + +Agrees(k) == \A e \in 1..Len(k): e <= Len(reg) => k[e] = reg[e] + +\* An ordinary handover only passes on roots the registry agrees with, so a +\* recipient can serve every registered epoch it received once activated. +HandoverAgreesWithRegistry == [][\A d, s \in Nodes: Join(d, s) => Agrees(kr[s])]_vars +============================================================================= diff --git a/docs/formal/key-rotation/README.md b/docs/formal/key-rotation/README.md new file mode 100644 index 0000000000..b5e8cfede8 --- /dev/null +++ b/docs/formal/key-rotation/README.md @@ -0,0 +1,74 @@ + + +# Key rotation models + +TLA+ models of the [KMS key rotation protocol](../../kms-emergency-key-rotation-protocol.md) +as implemented, checked exhaustively with TLC within the stated bounds. + +| Model | Covers | Implementation | +| --- | --- | --- | +| `KmsRotation.tla` | Root epoch registry, KMS keyrings, onboarding, key release | `DstackKms.sol`, `kms/src/main_service.rs`, `kms/src/onboard_service.rs` | +| `DiskMigration.tla` | Data disk setup and LUKS key migration, with crashes and rotations | `dstack-util/src/system_setup.rs`, `system_setup/luks.rs` | +| `EnvUpdate.tla` | Env re-encryption at boot and the VMM update window | `dstack-util/src/system_setup.rs`, `vmm/src/app.rs` | +| `EpochPolicy.tla` | Root and app epoch policy rows, range setters, pop and re-registration, legacy app policies, key release on the selected rows | `DstackKms.sol`, `DstackApp.sol` | + +## Running + +```bash +java -cp tla2tools.jar tlc2.TLC -config DiskMigration.cfg DiskMigration.tla +``` + +| Config | Bounds | Result | +| --- | --- | --- | +| `KmsRotation.cfg` | 3 nodes, 4 roots | `ReleasedFromRegisteredRoots` and `HandoverAgreesWithRegistry` hold (4,423 states); also with 4 nodes, 5 roots (57,889 states) | +| `DiskMigration.cfg` | epochs 0-3 | all invariants hold (828 states) | +| `EnvUpdate.cfg` | epochs 0-2, 2 owner updates, lossy host API, fail-closed guest | `OwnerUpdateKept` and `NoAppEnv` hold (267 states) | +| `EnvUpdateLossy.cfg` | same, guest only logs an unanswered update | `NoAppEnv` violated | +| `EpochPolicy.cfg` | root epochs 0-2, 5 registrations, 2 choices of keys, 2 values; app epochs 0-2, 1 compose hash | `RevocationIsTotal`, `AppKeyMatchesSelectedRow` and `RegistrationStartsEmpty` hold (6,104,564 states) | +| `EpochPolicyChainHash.cfg` | same, rows keyed by chain hash | `RevocationIsTotal` violated | +| `EpochPolicyLegacyAppEpoch.cfg` | same, legacy app fallback ignores the requested app epoch | `AppKeyMatchesSelectedRow` violated | + +Checked with TLC 2026.11.06 on OpenJDK 21. `EnvUpdate.cfg` models the guest of +#1546; `EnvUpdateLossy.cfg` the guest before it. + +Each model was checked against mutations of the implementation, each of which +produces a counterexample: + +- `DiskMigration`: requiring a single keyslot when the current key unlocks none + (a migration interrupted before a later rotation then fails every boot); + opening without removing the old keyslot; treating a disk that still carries + the initializing label as initialized. +- `KmsRotation`: skipping the latest registered epoch's chain hash check on + handover, which lets an ordinary join pass on a losing pending root. +- `EnvUpdate`: starting applications after an unanswered update. +- `EpochPolicy`: the two configs above; and treating a removal from the + current epoch through the latest as a revocation, as the epoch-less setters + before #1561 did, which lets a historical row still release the key. + +## Abstractions + +- A key epoch in `DiskMigration` and `EnvUpdate` stands for the (root, app) + epoch pair; the KMS serves every epoch up to the current one. Authorization + is assumed to allow the instance at each of them; `EpochPolicy` models the + rows that decide it, and a migrating instance must be allowed in the old + rows too. +- In `KmsRotation`, keys are released for epochs up to the current one and + handed over up to the latest registered one, the operation bounds of + `kms_serve`/`app_get_key` and `kms_export_keys`/`kms_import_keys`. +- `EpochPolicy` merges the root materials (OS image, KMS MR and device) into + one row per epoch, and the app materials into compose hashes; a release + needs one allowed value in each selected row. It has one app and no KMS + nodes; `KmsRotation` covers the keyrings. +- A boot fetches its keys once; the KMS may rotate at any point of + `DiskMigration`, and between boots in `EnvUpdate`. +- Each cryptsetup command on the device is atomic: it writes a new keyslot + area before the header copies, syncs each, and repairs an outdated copy on + the next load. A crash may stop a boot between any two commands. +- Roots are unique values; chain hash comparison is prefix equality. +- The owner registers what a generating node attests and activates an epoch once + some node can serve it. Governance and attestation are trusted. +- `EnvUpdate` does not model a VMM without `UpdateSealedEnv`, which has no + update window. diff --git a/docs/guest-api-auth.md b/docs/guest-api-auth.md new file mode 100644 index 0000000000..0531145a5a --- /dev/null +++ b/docs/guest-api-auth.md @@ -0,0 +1,182 @@ +# Guest Agent API access control + +The guest agent's external listener (port 8090) is reachable by anyone who can +route to the CVM. It refuses callers it cannot identify: every request names a +scope, and a scope is granted either by a signed token or by the host's +configuration. + +This is an exposure control, not a confidentiality one. It decides who may +*ask*. Whether the answer may leave the TEE is decided by the app's measured +`public_logs` / `public_sysinfo` / `public_tcbinfo` switches, and a token can +only narrow what those allow. See +[the two gates](#the-two-gates) below. + +## Scopes + +| Scope | Grants | +|---|---| +| `guest:version` | `Worker.Version` on either pRPC surface | +| `guest:health` | `Worker.Health` (`/prpc/v1`) | +| `guest:info` | `Worker.Info` on either surface, and the identity block on the dashboard | +| `guest:attest-app-key` | the frozen `Worker.GetAttestationForAppKey` | +| `guest:dashboard` | the dashboard page itself | +| `guest:containers` | the container table on the dashboard | +| `guest:logs` | `/logs/`, when the app sets `public_logs` | +| `guest:metrics` | `/metrics`, and the sysinfo block on the dashboard | + +`/prpc`, `/prpc/v0` and `/prpc/v1` are matched after percent-decoding and +segment normalisation, so `/prpc/Worker.Info`, `/prpc/v0/Info` and +`/%70rpc/Info` all need `guest:info`. + +The check fails closed: a path the table does not name is answered with 401, +not passed to the router. + +## Default: nothing anonymous + +With no `[cvm.guest_agent_api]` block, an anonymous caller is granted nothing: +the dashboard, its identity block, `/metrics` and the log views all need a +token. The gateway still works, because it is issued one internally. The app's +own SDKs are unaffected: they use the internal Unix socket, which is +unauthenticated and reachable only by the application. + +The sample `vmm.toml` ships the block filled in with what an unconfigured 8090 +used to serve, so a host that copies the sample keeps the page it had: + +| Scope | Effect | +|---|---| +| `guest:version` | `Worker.Version` answers | +| `guest:health` | `Worker.Health` answers | +| `guest:info` | the identity block renders | +| `guest:dashboard` | the page loads at all | + +Everything else is about the app's *contents* and stays behind a token even in +that sample: the container table, `/metrics`, the log views and +`Worker.GetAttestationForAppKey`. + +The dashboard does not fetch `Info` unless a block would show it, so an +anonymous visitor granted only `guest:dashboard` costs the TEE no attestation. + +## Configuring anonymous access + +Anonymous access is a host decision, made in sys-config. The VMM writes it from +`[cvm.guest_agent_api]`: + +```toml +[cvm.guest_agent_api] +anonymous_scopes = ["guest:dashboard", "guest:version", "guest:health", "guest:info"] +``` + +The same block in the guest's `/dstack/.host-shared/.sys-config.json`: + +```json +{ + "guest_agent_api": { + "anonymous_scopes": ["guest:dashboard", "guest:version", "guest:health", "guest:info"] + } +} +``` + +The list is whole, not additive, and there is no built-in default to fall back +on: omitting `anonymous_scopes`, or leaving the list empty, closes the listener +to anonymous callers. Removing the block entirely does the same. + +Listing `guest:dashboard` without `guest:containers`, `guest:info`, `guest:logs` +or `guest:metrics` gives an anonymous visitor the page with every block hidden. +Scopes are independent: each one adds exactly its own block. + +An unknown name is a boot error rather than a permission that silently never +matches. + +## External issuers + +Other than its own token, the agent accepts tokens from issuers the host names: + +```toml +[[cvm.guest_agent_api.external_issuers]] +name = "ops" +public_keys = ["2f8d...c1"] # hex Ed25519 public keys, 32 bytes each +``` + +`name` is the exact `iss` claim a token must carry; `public_keys` is a list so a +key can be rotated by publishing the new one beside the old, waiting until the +tokens it signed have expired, then dropping the old one. The agent does not +cap token lifetimes; there is no revocation list, so `exp` is the issuer's +only exposure control. + +Tokens must be Ed25519. `alg: none`, HMAC, and headers carrying key material +(`jku`, `x5u`, `jwk`) are not rejected by policy -- the header is a constant, +so they cannot be expressed. + +### Where the internal issuer comes from + +The gateway does not hold the app root key; the CVM mints its token and hands +it over on registration, bound to the app id: + +1. The agent and `dstack-util`, both inside the CVM, derive the same Ed25519 + key: `derive_app_key(app_root_key, "dstack:guest-api:issuer:v1", Ed25519)`. + That domain string is final: it is a wire contract between `dstack-util` and + the agent, which are upgraded together but may briefly disagree, so it is + never versioned again. +2. `dstack-util` signs a token with `iss = "dstack:guest-api:"`, + `aud = `, only the `guest:health` scope, `iat` rounded down to the + year and `exp` ten years later. Every registration within a year carries + the same token, and it never lapses while registration is down. +3. Registration carries it to the gateway, which presents it on the v1 `Health` + poll. + +The host cannot mint an internal token: the signing key is derived from the app +root key, which KMS releases only after the boot measurement is verified. The +host can still name its own [external issuer](#external-issuers) and grant +itself any scope; that is the same exposure as listing the scope in +`anonymous_scopes`, and still bounded by the measured switches. + +### Trust inside the CVM + +The CVM is one trust domain; the agent does not sandbox the processes in it. The +issuer key is an ordinary v1 application key, so any process that can reach +`dstack.sock` can obtain it with +`GetKey(domain = "dstack:guest-api:issuer:v1", algorithm = ed25519)` and mint a +token with any scope. That is by design -- the same process can already read +the data those scopes expose -- and it is also how an app issues tokens of its +own. Do not mount `dstack.sock` into a container you would not trust with +that. + +## The two gates + +Two independent checks decide what a caller sees, and both must pass: + +| Gate | Source | Measured | Answers | +|---|---|---|---| +| `public_logs`, `public_sysinfo`, `public_tcbinfo` | app-compose | yes | may this data leave the TEE at all? | +| scopes | sys-config | no | may this caller ask? | + +They combine with `&&`. A token cannot reveal logs the app kept private -- with +`public_logs = false` the route is not even mounted -- and an anonymous caller +cannot see a block it was not granted, however public the app made it. + +Scope configuration is deliberately unmeasured. Host-supplied sys-config is not +part of the attestation, so a host could grant a caller more than the operator +intended. That grants nothing beyond what anonymous 8090 access already granted +before this change: the data is still gated by the measured switches, which a +host cannot alter without changing the app id. + +## Compatibility + +A guest with this change answers 401 to an old gateway that presents no token. +The gateway counts that as unreachable and drops the instance after +`failure_threshold` consecutive polls, so a mixed cluster rebalances away from +new guests until the gateway is upgraded. + +During the rollout, either upgrade the gateway first, or leave the host open: + +```toml +[cvm.guest_agent_api] +anonymous_scopes = ["guest:version", "guest:health", "guest:info", "guest:dashboard"] +``` + +The reverse direction is quieter. A new guest registers with an old gateway +node that does not store `agent_token`; when that record syncs to an upgraded +node, the missing token means the upgraded node's health probe is refused too. +The instance drops out of rotation while `order_by_stickiness` keeps routing +user traffic to it. Upgrade every gateway node in the cluster before rolling +guests, not just the one the VMM talks to. diff --git a/docs/guest-api-v0.md b/docs/guest-api-v0.md new file mode 100644 index 0000000000..9dfacba919 --- /dev/null +++ b/docs/guest-api-v0.md @@ -0,0 +1,738 @@ +# dstack Guest Agent API v0 (frozen) + +This is the normative specification of the unversioned guest agent API, the +surface dstack 0.6.0 froze at exactly what v0.5.11 served. It defines the URL +scheme, the key derivation function, the signature chain encoding, and the +per-algorithm signing modes, so that a client written against this surface has a +written contract rather than an implementation to read. + +Read it as the contract. The proto file +(`dstack/guest-agent/rpc/proto/agent_rpc.proto`) describes the message shapes; +this document pins the bytes. Where an implementation and this document disagree, +one of them is a bug. + +**New code should target v1.** [`docs/guest-api-v1.md`](./guest-api-v1.md) is the +current API and the one under active development. This document exists because +the frozen surface is permanently closed and every 0.5.x client deployed today +speaks it, not because it is where new work belongs. + +## Scope and status + +The surface is closed. It gains no methods, no fields, no renumbering, and no +semantic changes to what is already there. It exists so a v0.5.x client keeps +working against a 0.6 agent unchanged. Every new capability goes to +`dstack.guest.v1`. + +Three services are frozen: `DstackGuest`, `Worker` and `Tappd`, all three in +the `dstack_guest` proto package. `Tappd` predates the naming scheme the other +two follow. + +The freeze is mechanical, not a convention. `the_frozen_services_match_their_pinned_shape` +in `dstack/guest-agent/rpc/tests/frozen_surface.rs` hashes each frozen service's +descriptor against a pinned SHA-256. The descriptor covers the method list and +the full field list of every message reachable from it, `reserved` ranges +included. +Any addition changes the digest and fails the test, including a wire-compatible +one. That is deliberate: "frozen except for additions" is how `GpuInfo`, +`AttestGpu` and `Worker.Health` accumulated on this surface between v0.5.11 and +0.6.0 without ever being released. +`the_frozen_services_expose_the_v0_5_11_methods` in the same file spells the +method lists out so a failure is readable. + +The descriptor digest pins the shape, not the behaviour. Behaviour is held by +the agent's own tests: `get_key_pins_the_frozen_chain_link` in +`dstack/guest-agent/src/rpc_service.rs` pins a chain link byte for byte, and +`the_internal_v0_mount_is_an_alias_for_the_unversioned_path`, +`the_external_v0_mount_is_an_alias_for_the_unversioned_path` and +`each_internal_mount_serves_only_its_own_surface` in +`dstack/guest-agent/src/server.rs` exercise the real mount table rather than a +restatement of it. + +One addition is sanctioned: the `root_epoch` and `app_epoch` selectors on +`GetKey`, described in [Key epochs](#key-epochs). A KMS key rotation changes +every key this surface derives, and v1 derives different keys altogether, so +without them a v0 key from before a rotation would be unreachable. + +Two behaviour changes in 0.6.0 are sanctioned and do not alter the wire shape: +`GetQuote` fails on a platform without Intel TDX instead of returning an empty +quote, and `GetTlsKey` rejects a `not_before` that is not earlier than +`not_after`. A third method, `EmitEvent`, always fails. Each is described in +[The remaining methods](#the-remaining-methods). + +## Transport and mounts + +| Listener | Service | Mount | Example path | +|---|---|---|---| +| Internal socket | `DstackGuest` | `/v0` | `/v0/GetKey` | +| Internal socket | `DstackGuest` | `/` | `/GetKey` | +| External | `Worker` | `/prpc/v0` | `/prpc/v0/Info` | +| External | `Worker` | `/prpc` | `/prpc/Worker.Info` | +| Tappd socket | `Tappd` | `/prpc/` | `/prpc/Tappd.Info` | + +The unversioned mounts are aliases, kept so a pre-0.6 client keeps working +unchanged. They are additional mounts of the *same* handler, not a parallel +implementation, so they cannot drift from the versioned path. New code that must +stay on this surface should say `/v0` and `/prpc/v0` explicitly. + +Both `Worker` mounts strip a `Worker.` service-name prefix from the method +segment, so `/prpc/Worker.Info` and `/prpc/Info` both reach `Info`. `Tappd` +strips `Tappd.` the same way. The internal `DstackGuest` mounts do not strip +anything: the method segment is the bare method name. + +The internal socket is `/var/run/dstack.sock`, reachable only by the application +itself, and it is the only place key material is served. The external listener is +reachable by anyone who can route to the CVM, and `Worker` never returns key +material. `Tappd` has its own socket, `/var/run/tappd.sock`. + +Version selection is by URL path and nothing else. There is no header +negotiation and no default-version redirect. + +Both listeners run the same prpc transport. A `POST` carrying +`Content-Type: application/json` takes a JSON body and returns JSON; any other +content type takes a protobuf-encoded request message and returns a +protobuf-encoded response. A `GET` takes its fields as query parameters and +returns JSON. + +In the JSON encoding, a proto `bytes` field is a lowercase hex string. On input +an optional `0x` prefix is accepted and stripped. This applies to every `bytes` +field on this surface, including `GetKeyResponse.key`, each element of a +`signature_chain`, `SignRequest.data`, and `report_data`. + +### Status codes + +These are transport-level and identical on both surfaces. + +| Status | Body | Meaning | +|---|---|---| +| 200 | the response message | Success | +| 404 | the server's own 404 page | No such mount: this agent has no surface at that path | +| 404 | `{"error": "Service not found: "}` | The surface is mounted; it has no such method | +| 400 | `{"error": ""}` | The method ran and failed | +| 413 | `{"error": ""}` | The request body exceeded the configured limit | +| other | `{"error": ""}` | A handler chose the status; the message says why | + +A handler failure is a 400 with the error text in the body. In the protobuf +encoding the same error arrives as a `ProtoError` message rather than JSON. + +## GetKey + +`GetKey` derives an application key from the application root key and returns it +with a two-link signature chain proving where it came from. It is the reason this +document exists: it is the one method on this surface whose output other parties +depend on, and until now its bytes lived only in the implementation. + +`GetKeyArgs` has five fields. + +| Field | Type | Reaches the KDF | +|---|---|---| +| `path` | string | **yes**, verbatim | +| `purpose` | string | no | +| `algorithm` | string | no | +| `root_epoch` | optional uint32 | selects the IKM | +| `app_epoch` | optional uint32 | selects the IKM | + +Only `path` reaches the KDF. `purpose` is echoed into the chain claim of link 0 +and has no other effect: two calls differing only in `purpose` return the same +32 bytes in `key` and differ only in `signature_chain[0]`. `algorithm` selects +how those 32 bytes are *interpreted* and how the public key is encoded; it does +not domain-separate the derivation. + +Derivation is flat. `path` is an opaque byte string used as HKDF `info` and +nothing more. `a/b` is not a child of `a`, no key derived here derives another, +and there is no BIP-32-style hierarchy. The empty string is a valid `path`. + +### The KDF + +```text +salt = "RATLS" (5 bytes, ASCII: 52 41 54 4c 53) +IKM = app root secp256k1 private key (32 bytes, of the selected key epochs) +info = path (the caller's bytes, verbatim) +L = 32 + +key = HKDF-SHA256(salt, IKM, info, L) (RFC 5869: extract, then expand) +``` + +`ra_tls::kdf::derive_key` is the implementation. It takes `context_data` as a +slice of byte slices and hands that slice straight to ring's HKDF `expand`, which +concatenates the parts to form `info`. `GetKey` passes exactly one part, +`request.path.as_bytes()`, so `info` is the raw `path` bytes with no separator, +no tag, and no length prefix. + +The salt is the constant `LEGACY_SALT` in `dstack/ra-tls/src/kdf.rs`. It is the +five ASCII bytes `RATLS`. It is baked into every key deployed before the +versioned API and must never change. + +### Key epochs + +`root_epoch` and `app_epoch` select the KMS root key epoch and the application +key epoch whose app root key is the IKM. Each defaults to the CVM's current +epoch, which is the app root key in `.appkeys.json`; epoch 0 is the original +keys. A selector newer than the current epoch fails. An older one makes the agent +fetch that epoch's app root key from the KMS, which must still authorize this +instance under the policy of that epoch; the agent keeps it in memory afterwards. + +The epochs change the IKM and nothing else: the KDF, the algorithm handling and +the chain encoding are as below, and link 1 is the KMS signature of the selected +epoch. With no selector set, a CVM that never saw a key rotation derives exactly +the keys v0.5.11 did. + +`GetKeyResponse.root_epoch` and `app_epoch` report the epochs the key was derived +from. An agent older than these fields ignores the selectors and omits them from +its response, so a client that sets a selector must check that the response +carries the epochs it asked for. `Tappd.DeriveK256Key` takes `GetKeyArgs` too and +honours the selectors, but its response has no epoch fields. + +### Algorithm selection + +`normalize_algorithm` maps the caller's string to a canonical name: `k256` +becomes `secp256k1`, and every other value passes through unchanged. `GetKey` +then matches on the result. + +| `algorithm` sent | Behaviour | +|---|---| +| `secp256k1` | secp256k1 | +| `k256` | alias; identical to `secp256k1`, same key bytes | +| `""` (empty or field absent) | secp256k1, the default | +| `ed25519` | ed25519 | +| `secp256k1_prehashed` | **error.** Prehashing is a signing mode, not a key type; `Sign` accepts it, `GetKey` does not | +| anything else | error, `Unsupported algorithm` | + +An unrecognised value is an error rather than a silent fallback to the default. +Only the literal empty string defaults. + +### Output encoding + +`key` is the 32 derived bytes, raw. It is not a PEM, not a DER, and not +algorithm-tagged; the caller knows which algorithm it asked for. In the JSON +encoding it is a 64-character hex string. + +- **secp256k1**: the 32 bytes are the big-endian private scalar. If it is zero or + at least the group order the call fails with `Failed to parse k256 key`. The + public key is the SEC1 **compressed** point, 33 bytes, `0x02`/`0x03` prefix. +- **ed25519**: the 32 bytes are the RFC 8032 seed, from which the key expands as + usual. The public key is the RFC 8032 raw public key, 32 bytes. + +`GetKeyResponse` has no `public_key` field. A caller derives the public key from +`key` itself, and a verifier of the chain must reproduce the same encoding, as +described below. (v1 added `public_key` to the response for exactly this reason.) + +### One secret, three curves + +The derivation ignores `algorithm`, so `GetKey(path, *, "secp256k1")` and +`GetKey(path, *, "ed25519")` return **the same 32 bytes**. One secret is served +in two representations: a secp256k1 scalar and an ed25519 seed. + +`Tappd.DeriveKey` makes it three. It runs the identical construction -- +HKDF-SHA256, salt `RATLS`, `info` = `path` -- and reads the result as a **P-256** +scalar, which it hands back as a PKCS#8 PEM on `/var/run/tappd.sock`. So +`GetKey("x")` and `Tappd.DeriveKey("x")` are the same secret on a third curve, +and the PEM is a more convenient form to walk off with than either. + +This is a property callers must account for, not a bug in an individual call. +Anyone who can reach either socket can request any of the three interpretations, +so the keys are not independent: compromise of one is compromise of all, and a +protocol that assumes a per-curve key does not get one here. Encoding the +algorithm into `path` -- `backup-signing/secp256k1` and `backup-signing/ed25519` +-- separates the two `GetKey` curves from each other, but not from +`Tappd.DeriveKey`, which will derive the very same secret from the very same +string. The only real boundary is the socket: nothing inside this surface makes +one derived key unreachable through another method. + +This is one of the things v1 changed: the v1 KDF binds the canonical algorithm +name and a version tag into `info` under its own salt, so the two curves never +share a secret. See +[Key derivation](./guest-api-v1.md#key-derivation) and +[Migration from the unversioned API](./guest-api-v1.md#migration-from-the-unversioned-api). + +### The signature chain + +`GetKeyResponse.signature_chain` has exactly two elements. + +```text +[0] app root key signs the v0 key claim (specified here) +[1] KMS root key signs the app root public key +``` + +Both are 65 bytes in the same envelope: + +```text +link = r || s || v (65 bytes) +``` + +`r` and `s` are 32-byte big-endian integers, low-S normalised, and `v` is the +one-byte recovery id in `0..=3`. The recovery byte lets a relying party recover +the signing public key from the link alone. `ra_tls::api_v1::sign_recoverable_keccak256` +produces both links; only the preimage differs. + +**Link 0, the key claim.** + +```text +claim = purpose || ":" || lowercase_hex(public_key) +digest = keccak256(claim) +link0 = r || s || v +``` + +`purpose` is the caller's string verbatim. `public_key` is the derived public key +in the encoding from [Output encoding](#output-encoding), SEC1 compressed for +secp256k1 and RFC 8032 raw for ed25519. It is hex-encoded in lowercase and +appended as **text**, not as raw bytes. The claim is a UTF-8 byte string, since +`purpose` is a proto3 `string`, and the digest is keccak256 over those bytes. + +The claim is a `:`-joined string over a caller-chosen `purpose`, which means an +application can steer much of what its own app root key signs. That is inside the +application's own trust domain, because the caller already holds the derived +key, but it is why v1's claim is length-prefixed instead, and why a v0 claim can +never be mistaken for a v1 one. See +[Why this cannot be forged through v0](./guest-api-v1.md#why-this-cannot-be-forged-through-v0). + +**Link 1, the KMS attestation.** Produced by the KMS, outside the agent, and +passed through byte-for-byte from `k256_signature` in `.appkeys.json`. It is the +same bytes v1 serves in its own `signature_chain[1]`. + +```text +message = "dstack-kms-issued" || ":" || app_id || sec1_compressed(app_root_pubkey) +digest = keccak256(message) +link1 = r || s || v +``` + +`app_id` is the raw app id bytes and the app root public key is SEC1 compressed, +33 bytes. `sign_message` in `dstack/kms/src/crypto.rs` builds the preimage as +`[prefix, b":", appid, message].concat()`. Note there is no separator between +`app_id` and the public key. + +### Verifying a chain + +A relying party holds `key` (or the public key derived from it), a +`signature_chain`, the `(path, purpose, algorithm)` the key was requested under, +and the `app_id`. + +1. **Anchor.** Obtain the KMS root public key from a source you trust + independently of the agent being checked: the `DstackKms` contract's + `kmsInfo().k256Pubkey`, or a value pinned out of band. This step carries the + security of everything below it. An attacker who can answer your query for the + anchor can also mint a self-consistent chain, so reading the anchor from the + KMS you are checking proves nothing. + +2. **Rebuild the claim.** Encode the public key as + [Output encoding](#output-encoding) specifies, hex-encode it in lowercase, and + compute `digest0 = keccak256(purpose || ":" || hex)`. + +3. **Recover the app root key.** Split `signature_chain[0]` into `r`, `s`, `v` + and recover the secp256k1 public key from `(digest0, r, s, v)`. Reject a + non-canonical high-S `s`. Call the result `app_root_pubkey`, SEC1 compressed. + +4. **Rebuild the KMS message.** Compute + `digest1 = keccak256("dstack-kms-issued" || ":" || app_id || app_root_pubkey)`. + +5. **Check link 1.** Verify `signature_chain[1]` over `digest1` against the anchor + from step 1, either by recovering and comparing to the anchor or by verifying + `(r, s)` against it directly. Reject high-S here too. + +6. **Bind the application.** Confirm the `app_id` you used in step 4 is the + application you meant to talk to. The chain proves that the KMS issued this app + root key to *some* application; only this step ties it to yours. + +Step 2 is where a v0 verifier can go wrong in a way a v1 verifier cannot: the +claim is built from a `purpose` the verifier must already know out of band, and +from a hex string whose case and public-key encoding must match exactly. A +verifier that guesses `purpose`, uppercases the hex, or uses the uncompressed +SEC1 point computes a different digest and recovers a different, meaningless +public key in step 3, which then simply fails at step 5. + +### Test vector + +`get_key_pins_the_frozen_chain_link` in `dstack/guest-agent/src/rpc_service.rs` +pins link 0. With the fixture app root key `DUMMY_K256_KEY` from that test +module, + +```text +app root key = 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b +path = "test" +purpose = "signing" +algorithm = "secp256k1" +``` + +`signature_chain[0]` is + +```text +c8a3dcf06c4e95bd78a5d7a1c8fcff171fc5848cfae804c6fc11bda4dc5d4062 +379995390843827444992c4c0e4bac70f0f878e01b9fc8b98cd7126fe5a3876b +01 +``` + +ECDSA here is deterministic (RFC 6979), so this vector pins the whole encoding +including the recovery byte. It is the only committed vector for a signature +chain on this surface; the values above are asserted on every test run. +[Report data](#report-data) has two of its own. + +## Sign + +`Sign` signs a caller-supplied payload with a key the agent derives itself. The +key is not chosen by the caller: `Sign` calls `GetKey` internally with +`path = "vms"` and `purpose = "signing"`, always, and only `algorithm` varies. +That is the same key `Worker.GetAttestationForAppKey` attests. + +`SignRequest.algorithm` goes through `normalize_algorithm` first, so `k256` is +accepted as an alias for `secp256k1` here too. Unlike `GetKey`, `Sign` has **no +default**: an empty `algorithm` derives a key and then fails with +`Unsupported algorithm`, because the empty string matches no signing mode. + +### Modes + +| `algorithm` | Key derived as | Bytes signed | Hash | Signature | +|---|---|---|---|---| +| `secp256k1` | secp256k1 at `vms`/`signing` | `data`, raw | SHA-256, by the agent | 64 bytes, `r \|\| s` | +| `k256` | alias for the row above | — | — | — | +| `secp256k1_prehashed` | secp256k1 at `vms`/`signing` | `data`, used **as the digest** | none | 64 bytes, `r \|\| s` | +| `ed25519` | ed25519 at `vms`/`signing` | `data`, raw | RFC 8032 (SHA-512, internal) | 64 bytes, `R \|\| S` | +| anything else | — | — | — | error, `Unsupported algorithm` | + +`r` and `s` are 32-byte big-endian integers and `s` is low-S normalised. Note the +shape: a payload signature is **64 bytes and carries no recovery byte**, unlike +the 65-byte chain links. It is the fixed-width form, not DER. + +`public_key` is the SEC1 compressed point (33 bytes) for both secp256k1 modes and +the RFC 8032 raw public key (32 bytes) for ed25519. + +The prehashed mode derives its key under the base name `secp256k1`, because +prehashing is a signing mode and not a key type. `secp256k1` and +`secp256k1_prehashed` therefore use the **same key** and produce the **same** +`public_key` and the same `signature_chain[1]` and `[2]`. + +Because `GetKey`'s derivation ignores the algorithm, the ed25519 and secp256k1 +modes also share one 32-byte secret, the one derived at `path = "vms"`. See +[One secret, two curves](#one-secret-two-curves). + +**`secp256k1_prehashed` puts the hash on the caller.** `data` must be exactly 32 +bytes; any other length fails with a message naming the length received. The +agent signs those 32 bytes directly as the digest and does not hash them again. +Consequences the caller owns: + +- Choose the hash function, and make sure the verifier uses the same one. The + agent records nothing about it, and neither does the signature. +- Domain-separate the payload before hashing. The agent will sign any 32 bytes, + including 32 bytes that are a digest of something else entirely, so a caller + that reuses one signing key across message types must build that distinction + into the preimage. +- The non-prehashed `secp256k1` mode hashes with SHA-256 inside the agent, so the + two modes produce different signatures over the same `data`, and a signature + from one does not verify under the other's rules. + +### The signature chain + +`SignResponse.signature_chain` has exactly three elements. The proto comment on +the field describes it accurately. + +```text +[0] the payload signature (64 bytes; the same bytes as `signature`) +[1] app root key signs "signing:" || hex(public_key) (65 bytes) +[2] KMS root key signs the app root public key (65 bytes) +``` + +Elements `[1]` and `[2]` are exactly `GetKey`'s `signature_chain[0]` and `[1]` +for a call with `path = "vms"`, `purpose = "signing"` and the mode's base +algorithm. Verify them by the steps in +[Verifying a chain](#verifying-a-chain), with `purpose = "signing"`. + +Element `[0]` duplicates the top-level `signature` field; it is there so that one +array carries the whole path from the payload to the KMS root. It is a different +shape from the other two: 64 bytes, no recovery byte, and verified against +`public_key` under the mode's own rules rather than recovered. + +## Verify + +`Verify` checks one signature against one public key. It is legacy: verification +needs no key material and no attestation, and the agent's answer arrives over the +socket unattested, so a relying party gains nothing over verifying locally. It is +retained because it is part of this frozen surface and the SDKs' v0 clients still +expose it. v1 has no counterpart. + +`algorithm` goes through `normalize_algorithm`, so the accepted values are +`ed25519`, `secp256k1`, `k256` (alias), and `secp256k1_prehashed`. An empty or +unrecognised value is an error, not `valid: false`. + +| `algorithm` | `public_key` | `data` | +|---|---|---| +| `ed25519` | RFC 8032 raw, 32 bytes | the message; hashed per RFC 8032 | +| `secp256k1` / `k256` | SEC1, compressed (33) or uncompressed (65) | the message; hashed with SHA-256 | +| `secp256k1_prehashed` | SEC1, compressed or uncompressed | the digest, used as-is | + +`signature` is the 64-byte `r || s` (or `R || S`) fixed-width form. DER is not +accepted. + +A malformed input is an error, not a verdict: a `public_key` that is not a valid +point, or a `signature` that is not 64 bytes or whose `r` or `s` is zero or at +least the group order, fails the call with HTTP 400. `valid: false` means the +inputs parsed and the signature did not check out. + +**A non-canonical high-S secp256k1 signature does not verify.** It parses, +because `r` and `s` are in range, and is then rejected by k256's verification, +so the call answers `valid: false` rather than failing. The effect is that a +malleated copy of a valid signature is not accepted here, which matters because +callers may be treating this answer as a uniqueness check. Verify the same way +if you replace this call with a local check. + +`secp256k1_prehashed` is more permissive here than in `Sign`, which is an +asymmetry worth knowing about. `Sign` requires `data` to be exactly 32 bytes. +`Verify` accepts any length from 16 bytes up: a shorter `data` is zero-padded on +the left to 32 and a longer one is truncated to its leftmost 32 bytes, both +silently. Below 16 bytes it is not an error either -- the length rejection is +swallowed and the answer is `200` with `valid: false`, like any other signature +that does not check out. Pass exactly the 32-byte digest and the two agree. + +A relying party that wants more than a single-signature check wants the chain +verification in [Verifying a chain](#verifying-a-chain), which this method does +not do: `Verify` never looks at a `signature_chain` and never touches a trust +anchor. + +## The remaining methods + +### GetTlsKey + +Issues a certificate and returns it with the key that backs it. The name is +misleading and v1 renamed it `IssueCert`: the operation is certificate issuance, +and the key is a by-product. + +**The key is freshly generated on every call, not derived.** No request field +feeds it, and two identical requests return two unrelated keys. It is a P-256 +key whose scalar comes from 32 bytes of `ring::rand::SystemRandom` output run +through the same HKDF-SHA256/`RATLS` step the derived keys use -- with a random +input, so the result is random and unreproducible either way -- returned as a +PKCS#8 PEM string in `key`. `GetKey` is the method that returns a stable, +re-derivable key. + +The agent builds a `CertSigningRequestV2` over the public key, signs the CSR with +the generated key, and relays it. With a KMS key provider the CSR goes to the KMS +`SignCert` RPC; without one it is signed by the local CA the app booted with. The +returned `certificate_chain` is whatever the signer produced. + +`usage_ra_tls` requests the RA-TLS quote extension, and `with_app_info` the app +info extension. `subject`, `alt_names`, `usage_server_auth` and +`usage_client_auth` map onto the certificate directly. + +`not_before` and `not_after` are seconds since the UNIX epoch and are optional +independently. When **both** are set, `not_before` must be strictly earlier than +`not_after`; otherwise the call fails. Setting only one is not validated here. +That check is one of 0.6.0's two sanctioned behaviour changes on this surface: a +0.5.x client that sent an inverted pair got a certificate; it now gets an error. + +### GetQuote + +Returns a raw Intel TDX quote over caller-supplied report data, with the event +log, the padded report data and the VM config. + +`report_data` is up to 64 bytes and is zero-padded on the right to 64. More than +64 bytes is an error, never a truncation. `GetQuoteResponse.report_data` is the +padded 64 bytes as the platform saw them. + +**As of 0.6.0 this method is Intel TDX only.** It used to answer on every +platform, returning an empty `quote`; a platform without a TDX quote now gets an +error naming `Attest` as the replacement. This is a behaviour change on a frozen +surface, and it is deliberate: an empty quote is not evidence, and a client that +treated it as one was already broken. See the 0.6.0 CHANGELOG entry beginning +"guest-agent: `GetQuote` is restricted to Intel TDX". + +On GCP Confidential VMs the gate passes, because there is a TDX quote, but the +answer carries the TDX half only. `GetQuoteResponse` has no field for the vTPM +quote GCP's own verification also binds, so a relying party there wants +`Attest`. + +`event_log` is a JSON array of TDX event log entries. V2 runtime events include +the hex-encoded preimage of their digest; a verifier should check that +`sha384(hex_decode(preimage))` equals the digest. + +### Attest + +Returns a `VersionedAttestation` over caller-supplied report data, as opaque +bytes in `attestation`. Report data padding is the same as `GetQuote`'s: up to 64 +bytes, zero-padded on the right, longer is an error. + +Unlike `GetQuote` it answers on every supported platform, and the attestation it +returns already carries the TDX quote and event log where those exist. The wire +format and how to extract a quote from it are specified in +[Extracting a quote from an attestation](./guest-api-v1.md#extracting-a-quote-from-an-attestation); +the format is shared between the two surfaces. + +`AttestResponse` on this surface carries `attestation` and nothing else. Field 2 +is `reserved`: it briefly carried `boottime_gpu_evidence` on an unreleased build. +Boot-time GPU evidence is a v1 feature, and a request sending +`include_boottime_gpu_evidence` here is ignored rather than honoured. + +### EmitEvent + +**Always fails, as of 0.6.0.** It answers HTTP 400 with + +```text +EmitEvent was removed in dstack 0.6.0; runtime RTMR3 events are system-owned and cannot be extended by apps +``` + +Runtime RTMR3 events became system-owned, so an application can no longer extend +the measurement chain. Applications bind their data through `report_data` +instead. + +The method was kept rather than deleted so that a pre-0.6 client gets a +self-explanatory error. Deleting it would answer HTTP 404 +`Service not found: EmitEvent`, which says nothing about why the events stopped +being recorded. The explanatory failure is the entire reason the method still +exists; `EmitEventArgs` is kept for the same reason, so an old client's request +still decodes and reaches the handler. + +### Info + +Returns application identity and configuration. It is not attestation: the +response arrives over a socket with no quote behind it, and nothing in it is +evidence. A relying party confirms these values against an attestation. + +`app_id`, `instance_id`, `device_id`, `mr_aggregated`, `os_image_hash` and +`compose_hash` are raw bytes (hex strings in JSON). `app_name`, +`key_provider_info` and `vm_config` are strings. `cloud_vendor` and +`cloud_product` are the DMI `sys_vendor` and `product_name` values, empty when +unreadable. + +`tcb_info` is a pretty-printed JSON string, not a message. It carries `mrtd` and +`rtmr0` through `rtmr3`, the full `event_log`, the verbatim `app_compose` +document, and hex copies of `mr_aggregated`, `os_image_hash`, `compose_hash` and +`device_id` that also appear as top-level fields. `compose_hash` is `sha256` over +the exact `app_compose` bytes, so do not parse and re-serialize before hashing. + +`app_cert` is a demo certificate the agent mints for a dashboard. It proves +nothing, it is requested lazily in the background, and it is an empty string +until that request completes. v1 dropped it. + +**What `public_tcbinfo` hides.** The gating applies only on the external +listener, and only when the app-compose does not set `public_tcbinfo`. In that +case `tcb_info` and `vm_config` come back as **empty strings**; every other +field, `key_provider_info` included, is served as normal. The internal +`DstackGuest.Info` applies no gating at all: the caller there is the application +itself, which cannot need protecting from its own configuration. + +Note that this is not what v1's `Worker.Info` does; v1 also blanks +`key_provider_info`. The difference is intentional and the frozen behaviour is +unchanged. See +[public_tcbinfo on the external surface](./guest-api-v1.md#public_tcbinfo-on-the-external-surface). + +### Version + +Returns the agent's `version` (its Cargo package version) and `rev` (the git +revision it was built from). It takes no arguments and touches nothing, which +makes it the cheapest liveness probe on either listener. + +### Worker.GetAttestationForAppKey + +On the external listener. Derives the application key for `algorithm`, builds +report data committing to its public key, and returns a `GetQuoteResponse` over +it. The caller cannot build that report data itself, because it does not know the +public key until the agent derives it. That is why attesting an app key needs +its own method rather than the caller-supplied `report_data` that `GetQuote` and +`Attest` take. + +The key is `GetKey(path = "vms", purpose = "signing", algorithm)`, the same key +`Sign` uses. `algorithm` goes through `normalize_algorithm`, and +`secp256k1_prehashed` derives under `secp256k1` exactly as it does in `Sign`. An +empty or unrecognised `algorithm` is an error. + +The report data is a DIP-1 tagged ASCII string, zero-padded on the right to 64 +bytes: + +```text +report_data = prefix || base64url_nopad(public_key) then right-padded with 0x00 to 64 +``` + +| `algorithm` | `prefix` | `public_key` | Total length | +|---|---|---|---| +| `secp256k1`, `k256`, `secp256k1_prehashed` | `dip1::secp256k1c-pk:` (20 bytes) | SEC1 compressed, 33 bytes | 20 + 44 = 64, no padding | +| `ed25519` | `dip1::ed25519-pk:` (17 bytes) | RFC 8032 raw, 32 bytes | 17 + 43 = 60, padded with 4 zero bytes | + +The base64 alphabet is URL-safe and unpadded. The construction fails rather than +truncating if it would exceed 64 bytes, so a commitment can never silently become +a valid-looking commitment to a different key. Note that the secp256k1 form fills +the field exactly: there is no trailing NUL to parse against, so a reader should +stop at 64 bytes or at the first NUL, whichever comes first. + +The `c` in `secp256k1c` records that the point is compressed. A verifier that +re-derives the commitment from an uncompressed point gets a different string. + +`app_key_report_data_matches_its_vectors` in +`dstack/guest-agent/src/rpc_service.rs` pins both forms against the fixture app +root key from [Test vector](#test-vector): + +```text +ed25519 "dip1::ed25519-pk:5Pbre1Amf1hrp2V2bbfKlIfxpQb2pJAmrgmhxgVoG9s\0\0\0\0" +secp256k1 "dip1::secp256k1c-pk:A6t_JdVkVdMAocH3f1f20WGT6JzdntxcXimUtEax8zc9" +``` + +`app_key_report_data_accepts_secp256k1_prehashed` asserts that +`secp256k1_prehashed` produces the second one unchanged. + +Because it returns a `GetQuoteResponse`, this method answers on Intel TDX and +fails everywhere else, exactly as `GetQuote` does. + +v1 ships no counterpart, on purpose: no v1 `GetKey(domain, algorithm)` can return +the key this attests, so a v1 method would hand back an attestation of a public +key whose private half the caller could not obtain. A v1 application attests its +own key instead. See +[There is no v1 AttestAppKey](./guest-api-v1.md#there-is-no-v1-attestappkey). + +## Tappd + +`Tappd` predates v0 and is deprecated. It is served on its own socket +(`/var/run/tappd.sock`) at `/prpc/`, with the `Tappd.` service-name prefix +stripped, and it is frozen by the same descriptor digest. New code should not +call it; the notes below exist so a reader of an old client can tell what it did. + +Every method maps onto a `DstackGuest` one, except where noted. + +| Method | Relationship to `DstackGuest` | +|---|---| +| `DeriveK256Key` | `GetKey`, verbatim. Same arguments, same bytes, fields renamed to `k256_key` and `k256_signature_chain` | +| `Info` | `Info`, with internal semantics: no `public_tcbinfo` gating | +| `Version` | `Version` | +| `TdxQuote` | `GetQuote`, but it hashes the report data first (see below) | +| `RawQuote` | `TdxQuote` with `hash_algorithm = "raw"`; requires exactly 64 bytes and does not pad | +| `DeriveKey` | *No `DstackGuest` equivalent.* See below | + +`TdxQuote` builds report data as `hash(prefix || ":" || content)` rather than +taking it raw. **The agent supplies the colon**; `prefix` is the tag alone. The +default is `app-data`, which the response echoes back without a colon, so +`hash_algorithm = "sha512"` over `content` digests `app-data:` + `content`. A +caller who passes `prefix = "app-data:"` because a quote is documented as +`hash("app-data:" + content)` gets `app-data::` + `content` and a quote nothing +will verify. The digest is left-aligned in the 64 bytes and the rest is zero. +`hash_algorithm = "raw"` passes `report_data` through unchanged and then requires +it to be exactly 64 bytes. + +`DeriveKey` is the one method with no counterpart: it derives a **P-256** key +pair at `path` and issues a certificate for it. Unlike `GetTlsKey`, whose key is +random, this key is derived from the app root key through the same +HKDF-SHA256/`RATLS` construction, so it is stable across calls, unless +`random_seed` is set, which replaces the app root key with 32 fresh random bytes +and makes the result unreproducible. It always requests `ext_app_info = false` +and takes no validity window. + +## Migration to v1 + +[`docs/guest-api-v1.md`](./guest-api-v1.md) is the current API. Its +[Field mapping](./guest-api-v1.md#field-mapping) table lists every v0 method and +field against its v1 counterpart, and +[Migration from the unversioned API](./guest-api-v1.md#migration-from-the-unversioned-api) +covers what changes for an application that moves. + +The one thing to read before doing anything else: **v1 derives different key +material.** Deriving under the same name on `/v1` returns different bytes than +`/v0` does, by design and with no compatibility mode. An application holding +assets or identity under a v0 key must migrate them deliberately rather than +switching URLs. + +Nothing forces a migration. This surface stays available and closed, and a +v0.5.x client keeps working against a 0.6 agent unchanged. + +## Related documents + +- [dstack Guest Agent API v1](./guest-api-v1.md), the current API and the + normative spec for `dstack.guest.v1` +- [Attestation on Intel TDX](./attestation-tdx.md) +- [App Compose format](./normalized-app-compose.md), for the document behind + `compose_hash` and `AppInfo.tcb_info`'s `app_compose` +- [On-chain governance](./onchain-governance.md), for the `DstackKms` contract + that publishes the KMS root public key used as the chain's trust anchor +- [`sdk/curl/api.md`](../sdk/curl/api.md), a curl-oriented tour of both surfaces diff --git a/docs/guest-api-v1.md b/docs/guest-api-v1.md new file mode 100644 index 0000000000..652b8fff5e --- /dev/null +++ b/docs/guest-api-v1.md @@ -0,0 +1,762 @@ +# dstack Guest Agent API v1 + +This is the normative specification of `dstack.guest.v1`, the versioned guest +agent API introduced in dstack 0.6.0. It defines the URL scheme, the key +derivation function, the signature chain encoding, and the steps a relying party +follows to verify what the agent produces. + +Read it as the contract. The proto file +(`dstack/guest-agent/rpc/proto/agent_rpc_v1.proto`) describes the message shapes; +this document pins the bytes. Where an implementation and this document disagree, +one of them is a bug. + +## What v1 is for + +v1 exists because the unversioned surface cannot be fixed without breaking the +v0.5.x clients that depend on it. That surface is closed at exactly the v0.5.11 +shape. v1 is where the corrections live. + +The guest agent is not a general-purpose crypto service. It holds two things no +caller can obtain elsewhere: the application root key, and the platform's ability +to attest. v1 serves those two things and nothing else. + +That is the organising principle behind the method set. `Sign` and `Verify` are +absent because they are pure computation over material the caller already has. +Any process that can reach this socket can ask `GetKey` for the private key +itself, so a server-side `Sign` grants no capability, adds an IPC round trip, and +adds an entry point to audit. Verification does not even need a key. + +Four things changed for the operations that remain. + +**Keys are domain-separated.** v0 derived a key from a path alone and handed the +same 32 bytes to both secp256k1 and ed25519. v1 binds the algorithm and a +versioned context tag into the derivation, so the two curves never share a secret +and a v1 key is never a v0 key. + +**A key is named by one field.** v0 had `path` and `purpose`, of which only `path` +reached the KDF while `purpose` was echoed into the chain claim. v1 merges them +into `domain`, and both `domain` and `algorithm` affect the derived key. + +**The chain claim is unambiguous.** v0's claim is a `:`-joined string over a +caller-chosen `purpose`, which lets an application steer what the app root key +signs. v1's claim is length-prefixed and binds raw public key bytes. + +**Names say what things are.** `GetTlsKey` became `IssueCert`, because the +operation is certificate issuance. `Info` no longer nests documents inside a JSON +blob called `tcb_info`. + +## Transport and versioning + +Every surface the agent serves is now a closed v0 fossil plus a v1. The +unversioned surfaces are exactly v0.5.11 and never change again; new capability +arrives only in `dstack.guest.v1`. + +The scheme is uniform: `v0` names the frozen v0.5.11 surface, `v1` the current +one, on both listeners. + +| Listener | Version | Service | Mount | Example path | +|---|---|---|---|---| +| Internal socket | v1 | `DstackGuest` | `/v1` | `/v1/GetKey` | +| Internal socket | v0 | `DstackGuest`, frozen | `/v0` | `/v0/GetKey` | +| Internal socket | v0 alias | `DstackGuest`, frozen | `/` | `/GetKey` | +| External | v1 | `Worker` | `/prpc/v1` | `/prpc/v1/Health` | +| External | v0 | `Worker`, frozen | `/prpc/v0` | `/prpc/v0/Info` | +| External | v0 alias | `Worker`, frozen | `/prpc` | `/prpc/Worker.Info` | + +The unversioned paths are compatibility aliases, kept so a pre-0.6 client keeps +working unchanged. They are additional mounts of the *same* handler, not a +parallel implementation, so they cannot drift from `/v0`. New code should say +which version it means. + +Both packages name their services `DstackGuest` and `Worker`. The version lives +in the package (`dstack.guest.v1`) and in the mount path, not in the service +name -- `dstack.guest.v1.DstackGuestV1` would say it twice. Where this document +needs to distinguish them it writes "the v1 `DstackGuest`" or "the frozen +`Worker`". + +`Tappd` is unchanged and outside this scheme: it predates v0 and stays on its own +socket at `/prpc/`. + +The internal socket is `/var/run/dstack.sock`, reachable only by the application +itself. The external listener is reachable by anyone who can route to the CVM. +That difference is the whole reason there are two services rather than one +mounted twice: the v1 `DstackGuest` hands out key material, and the v1 `Worker` +never does. + +Version selection is by URL path and nothing else. There is no header +negotiation, no `Accept-Version`, and no default-version redirect, so a request +URL is the complete record of which contract the caller asked for. An agent that +predates v1 has no `/v1` mount at all, so it answers `/v1/...` with a plain +HTTP 404 -- see [Detecting an agent without v1](#detecting-an-agent-without-v1). + +Both surfaces run over the same prpc transport. A `POST` carrying +`Content-Type: application/json` takes a JSON body and returns JSON; any other +content type takes a protobuf-encoded request message and returns a +protobuf-encoded response. A `GET` takes its fields as query parameters and +returns JSON. + +### Status codes + +| Status | Body | Meaning | +|---|---|---| +| 200 | the response message | Success | +| 404 | the server's own 404 page | No such mount: this agent has no surface at that path | +| 404 | `{"error": "Service not found: "}` | The surface is mounted; it has no such method | +| 400 | `{"error": ""}` | The method ran and failed | +| 501 | `{"error": ""}` | `AttestGpu` on an image that ships no GPU attestation | +| other | `{"error": ""}` | A handler chose the status; the message says why | + +A handler failure is a 400 with the error text in the body unless the handler +chose otherwise, and `AttestGpu` is the only v1 method that does. v1 does not +default, coerce, or truncate a malformed request into a well-formed one. + +### Detecting an agent without v1 + +Both "this agent is too old for v1" and "v1 exists but has no such method" +answer 404, so the status alone does not separate them. The body does. + +- 404 whose body is **not** JSON carrying `Service not found` -- there is no + surface mounted at that path. The agent predates v1. +- 404 whose body **is** `{"error": "Service not found: "}` -- v1 is + mounted and does not have that method. + +`/v1/Version` is the cheapest probe: it takes no arguments and touches nothing. + +## The internal surface + +The v1 `DstackGuest` has six methods. + +| Method | Purpose | +|---|---| +| `IssueCert` | Issue a certificate, with a freshly generated key | +| `GetKey` | Derive an application key and return it with its signature chain | +| `Attest` | Produce a versioned attestation over caller-supplied report data | +| `AttestGpu` | Collect GPU evidence now, against a caller-chosen nonce | +| `Info` | Return application identity and configuration | +| `Version` | Return the agent version | + +Five v0 methods are deliberately absent. + +`Sign` and `Verify` are absent for the reason above: neither needs the TEE. +Applications sign locally with a standard crypto library, using the key `GetKey` +returns, and verify locally following this document. A v0 client may keep calling +the unversioned `Verify` for single-signature checks; the v0 `Sign` RPC's +per-algorithm signing modes are specified in +[dstack Guest Agent API v0](./guest-api-v0.md#sign), which is the normative +document for that surface. + +`GetQuote` is absent because `Attest` subsumes it. `GetQuote` answers on Intel TDX +and nowhere else, and the `VersionedAttestation` that `Attest` returns already +carries the TDX quote and the event log. See +[Extracting a quote from an attestation](#extracting-a-quote-from-an-attestation). + +Boot-time GPU evidence has no method of its own. `Attest` with +`include_boottime_gpu_evidence` returns it, in the same `GpuEvidenceBundle` +shape `AttestGpu` uses, so one parser handles both and one round trip fetches +the evidence together with the attestation needed to authenticate it. + +`EmitEvent` is absent because runtime RTMR3 events became system-owned in 0.6.0. +An application binds its data through `report_data` instead. + +### Naming conventions + +Every request message is `Request` and every response is +`Response`, including for methods that take no arguments. An empty message +can gain a field later; `google.protobuf.Empty` cannot. + +A field's encoding lives in its doc comment, not in its name. Fields carrying JSON +documents say so and name who owns the schema. + +## Certificate issuance + +`IssueCert` is certificate issuance. The agent generates a key, builds a CSR, +signs the CSR with that key, and relays it to the KMS `SignCert` RPC, or to the +local CA when the application runs without a KMS. It returns the chain the signer +produced. + +v0 called this `GetTlsKey`, which named the by-product rather than the request. +The private key is incidental: it is freshly generated on every call, no request +field feeds it, and two identical requests produce two unrelated keys. `GetKey` is +the method that derives a stable, attestable key. + +`not_before` must be earlier than `not_after` when both are set; otherwise the +call fails. + +With `usage_ra_tls` set, the certificate carries the CVM's attestation in the +`PHALA_RATLS_ATTESTATION` extension (OID `1.3.6.1.4.1.62397.1.8`). v1 always puts +the MessagePack V1 schema there (see [Attestation](#attestation)), both in the CSR +and in the certificate issued from it, because the signer embeds the attestation +in the form it received. Two requirements follow: the KMS that signs the CSR must +be 0.5.9 or later, and so must any RA-TLS peer that verifies the certificate. +v0 `GetTlsKey` keeps the legacy SCALE form wherever it can represent the +attestation. + +This first cut serves only the integrated one-step mode, where the agent holds the +key. A mode that signs a caller-supplied CSR or public key, so the private key +never leaves the caller, is a plausible extension. It would arrive as added fields +or a sibling method, never as a change to what these fields mean. + +## Key derivation + +### Inputs + +A v1 application key is named by exactly two values. + +`domain` is a caller-chosen domain-separation string. It is not a DNS name; the +certificate fields on `IssueCertRequest` are the ones that take those. It may be +any byte string a proto3 `string` can carry, including one containing `:`, `/`, or +NUL. + +`algorithm` is `secp256k1` or `ed25519`. There is no default and no alias. An +empty string is an error, and so is any other value, including `k256` and +`secp256k1_prehashed`. + +Derivation is **flat**. Two domains yield unrelated keys. `a/b` is an opaque +string that happens to contain a slash, not a child of `a`, and no key derived +here can be used to derive another. There is no BIP-32-style hierarchy. The old +`path` name invited that reading, which is part of why it is gone. + +### Length-prefixed encoding + +Every construction below builds its input from length-prefixed fields. Write +`LP(x)` for: + +```text +LP(x) = uint32_be(len(x)) || x +``` + +`len(x)` is the byte length, encoded big-endian in exactly four bytes. Encoding +fails if a field is longer than 2^32 - 1 bytes. + +The prefix is what makes the encoding injective. A domain is arbitrary +caller-chosen bytes, so any delimiter it could also contain would let two +different `(domain, algorithm)` pairs encode to one byte string and share a key. +Joining with `:` or `/` is not sufficient here and is not what v1 does. + +### The KDF + +```text +salt = "dstack-guest-v1" (15 bytes, ASCII; v0 uses "RATLS") +IKM = app root secp256k1 private key (32 bytes, `k256_key` from .appkeys.json) +info = LP("dstack-guest-v1-key") || LP(algorithm) || LP(domain) +L = 32 + +key = HKDF-SHA256(salt, IKM, info, L) (RFC 5869: extract, then expand) +``` + +`algorithm` is bound as its canonical name, `secp256k1` or `ed25519`, never as the +string the caller sent. + +The primitive is unchanged from v0, which also used HKDF-SHA256 over the same +input key material. Two things changed. The `info` now binds the algorithm and a +version tag, where v0 passed the path alone, so the algorithm did not participate +and one 32-byte secret served both curves. And the salt is v1's own. + +The salt is what makes v1 a separate derivation tree rather than a +differently-labelled branch of the old one. Under a shared salt the two surfaces +would be separated only by their HKDF `info` -- and the legacy `info` is the +caller's `path` verbatim, so a caller that passed the v1 `info` byte string as a +v0 `path` would reproduce a v1 key exactly. Different salts close that by +construction, whatever either side puts in `info`. + +That collision was never a privilege boundary: both derivations serve the same +single-tenant application from the same root key, and that application may call +either surface. It is closed because a KDF whose separation depends on nobody +choosing an awkward input is one refactor away from not separating anything, and +the fix costs nothing on a surface with no deployed keys yet. + +The 32 output bytes are used directly: + +- **secp256k1**: the big-endian private scalar. If it is zero or at least the + group order, the call fails. That is a ~2^-128 event for a given domain, and the + caller can choose another one. Folding the scalar into range would silently land + two domains on one key. +- **ed25519**: the RFC 8032 seed, from which the key expands as usual. + +### Public key encoding + +| Algorithm | Encoding | Length | +|---|---|---| +| `secp256k1` | SEC1 compressed point, `0x02`/`0x03` prefix | 33 bytes | +| `ed25519` | RFC 8032 raw public key | 32 bytes | + +These are the exact bytes returned in `public_key` and the exact bytes bound into +the chain claim. A relying party never has to re-derive the public key from the +private key to check the chain. + +### Test vectors + +Generated with an app root key of + +```text +1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b +``` + +| domain | algorithm | private key | public key | +|---|---|---|---| +| `""` | secp256k1 | `59f60584ce6fd2a3a31997256db9d77322463fc8a6b1520110401bcb1ee92387` | `0377c7fb050db181d392266a3cee9adb2901c6d665f11bac68be5457f577ba4908` | +| `""` | ed25519 | `b023493030669cf22e9cafa6a464d4cf3ae4edfe5474ec796710f21ea011946d` | `a3dc149fd5b765eab2eb7d3174fa939e39386898f10b15b7b146f6f1358ecf2a` | +| `storage-encryption` | secp256k1 | `5510330f86902ddae38c6d89c93a8408019332c17a429e1abd01c4a28d1544a6` | `03d962450a41748021c8b02787ac36ce642ff0ae25f4c55019eb527e1112cfd764` | +| `storage-encryption` | ed25519 | `3c4c3ece12fa99ccb93fc0090877f80e70545fdd971e2ac93d3398c4684538d3` | `2380c4a33a60b60613fa43866421e5b96eb8dcde211317200fd0d41e7e491288` | +| `a/b/c` | secp256k1 | `7f0973449298085d2d36a3b4c4d3243c100ba1981ffa885fe9e9dee883e69538` | `02e9b1a61b6d70aa9b241753828c316bf90e33e77b2e113f9ba75a8b6dc3cde5c1` | +| `k\0:ey` | ed25519 | `42da8bf0b479ed125c370e3b91f982735bf08ff592abbd586985affa43ee96a1` | `c833107822b003ff5675b33b90b151d4315c3ab9162b17d876e8dffde41abf9b` | + +The last row's domain is the five bytes `6b 00 3a 65 79`. It is there because a +delimiter-joined encoding would mishandle it. + +The same vectors are asserted in `dstack/ra-tls/src/api_v1.rs`, which pins the +private-key column next to the primitives that produce it; +`dstack/guest-agent/src/rpc_service_v1/keys.rs` pins the public-key column +through the type the handler actually serves. They describe deployed key +material, so a diff against them is a bug in the derivation, not a stale fixture. + +## The signature chain + +`GetKey` returns a two-element `signature_chain` alongside the key. + +```text +[0] app root key signs the v1 key claim (specified here) +[1] KMS root key signs the app root public key (unchanged from v0) +``` + +Link 1 is produced by the KMS, outside the agent, and both API surfaces pass the +same bytes through. Only link 0 is new. + +### Link 0: the key claim + +```text +claim = LP("dstack-guest-v1-key-claim") + || LP(algorithm) + || LP(domain) + || LP(public_key) + +digest = keccak256(claim) +link0 = r || s || v (65 bytes) +``` + +`link0` is a recoverable ECDSA secp256k1 signature over `digest` by the app root +key. `r` and `s` are 32-byte big-endian integers, low-S normalised, and `v` is the +one-byte recovery id in `0..=3`. `public_key` is the raw derived public key from +the table above, not a hex string. + +A worked claim, for `domain = "storage-encryption"` and `algorithm = "secp256k1"`: + +```text +00 00 00 19 "dstack-guest-v1-key-claim" 25 bytes +00 00 00 09 "secp256k1" 9 bytes +00 00 00 12 "storage-encryption" 18 bytes +00 00 00 21 03 d9 62 45 ... d7 64 33 bytes +``` + +With the app root key from the test vector table, `link0` is + +```text +5b6193729ce7976ec67863f21692d4b98c69832698aae8e001a7d33a6f818b6e +46ca950725b6e90e8ca9bcf394abd03ce264bf9b7eec1e91693247f9dd53c269 +01 +``` + +The signature is deterministic (RFC 6979), so this vector pins the whole encoding +including the recovery byte. + +#### Why this cannot be forged through v0 + +v0's claim is `keccak256("{purpose}:{hex(pubkey)}")`, and `purpose` is an +arbitrary caller-supplied string. A malicious application can therefore make the +app root key sign nearly any ASCII byte string that ends in `:` followed by +lowercase hex. If a v1 claim were reachable that way, the v1 chain would be worth +nothing. + +It is not reachable, and the reason is structural rather than probabilistic. + +Every v0 preimage ends with `:` followed by the hex encoding of a public key, so +its last 64 bytes (ed25519) or 66 bytes (secp256k1) are all lowercase hex +characters. A v1 claim ends with `LP(public_key)`, whose four length bytes are +`00 00 00 21` for secp256k1 and `00 00 00 20` for ed25519, sitting 37 or 36 bytes +from the end. That is inside the region a v0 preimage requires to be hex-only, and +`0x00` is not a hex character. No choice of `purpose` reproduces a v1 claim byte +string, and since the two byte strings can never be equal, matching their keccak +digests would require a preimage attack on keccak256. + +The regression test is `a_v0_claim_cannot_be_crafted_into_a_v1_claim` in +`dstack/ra-tls/src/api_v1.rs`. It builds the strongest available forgery, a +`purpose` set to the v1 claim minus exactly the suffix v0 appends on its own, +then asserts both that the byte strings differ and that the structural property +holds. + +The two context tags are also distinct, so a derivation input can never be read as +a claim: `dstack-guest-v1-key` for the KDF, `dstack-guest-v1-key-claim` for the +claim. Because both are length-prefixed, neither encoding is a prefix of the other. + +### Link 1: the KMS attestation + +Unchanged from v0 and reproduced here so this document is self-contained. + +```text +message = "dstack-kms-issued" || ":" || app_id || sec1_compressed(app_root_pubkey) +digest = keccak256(message) +link1 = r || s || v (65 bytes) +``` + +`link1` is a recoverable ECDSA secp256k1 signature over `digest` by the KMS root +key. `app_id` is the raw app id bytes, and the app root public key is SEC1 +compressed, 33 bytes. + +### Verifying a chain + +A relying party holds a `public_key`, a `signature_chain`, the `(domain, +algorithm)` the key was requested under, and the `app_id`. It performs the +following. + +1. **Anchor.** Obtain the KMS root public key from a source you trust + independently of the agent being checked: the `DstackKms` contract's + `kmsInfo().k256Pubkey`, or a value pinned out of band. This step carries the + security of everything below it. An attacker who can answer your query for the + anchor can also mint a self-consistent chain, so reading the anchor from the + KMS you are checking proves nothing. + +2. **Rebuild the claim.** Compute + `claim = LP("dstack-guest-v1-key-claim") || LP(algorithm) || LP(domain) || LP(public_key)` + using the canonical algorithm name and the raw public key bytes, then + `digest0 = keccak256(claim)`. + +3. **Recover the app root key.** Split `signature_chain[0]` into `r`, `s`, `v` and + recover the secp256k1 public key from `(digest0, r, s, v)`. Reject a + non-canonical high-S `s`. Call the result `app_root_pubkey`, SEC1 compressed. + +4. **Rebuild the KMS message.** Compute + `digest1 = keccak256("dstack-kms-issued" || ":" || app_id || app_root_pubkey)`. + +5. **Check link 1.** Verify `signature_chain[1]` over `digest1` against the anchor + from step 1, either by recovering and comparing to the anchor or by verifying + `(r, s)` against it directly. Reject high-S here too. + +6. **Bind the application.** Confirm the `app_id` you used in step 4 is the + application you meant to talk to. The chain proves that the KMS issued this app + root key to *some* application; only this step ties it to yours. + +To also check a payload signature an application produced with a key from +`GetKey`, verify that signature against `public_key` under whatever scheme the +application used, then run steps 2 through 6 to establish that `public_key` is what +it claims to be. The two halves are independent: a valid payload signature under an +unverified public key says nothing. + +Step 3 recovers the app root key rather than requiring it as an input, which is why +link 0 carries a recovery byte. A verifier that already knows the expected app root +public key may verify `(r, s)` against it directly and compare instead. + +## The external surface + +The v1 `Worker` has three methods, served at `/prpc/v1`. + +| Method | Purpose | +|---|---| +| `Info` | Application identity and configuration, subject to `public_tcbinfo` | +| `Version` | The agent version | +| `Health` | Report whether the application is serving | + +Nothing here returns key material, and no caller chooses what gets signed or +attested. + +Every method also needs a scope, granted by a signed token or by the host's +configuration. With no configuration the listener answers only token holders; +see [Guest Agent API access control](./guest-api-auth.md) for the vocabulary and +for how the gateway authenticates its health polls. + +### There is no v1 AttestAppKey + +The frozen surface has `Worker.GetAttestationForAppKey`, which attests a key the +agent derives from an algorithm name alone. v1 has no counterpart, on purpose. + +That method attests the key v0's KDF derives at path `vms` with purpose +`signing`. No v1 `GetKey(domain, algorithm)` call can return that key: the v1 +KDF has a different salt, a different `info`, and no `purpose` input at all. A +v1 application calling it would receive an attestation of a public key whose +private half it has no way to obtain, which is worse than having no method -- +it looks like it works. + +A v1 application attests its own key instead: + +1. Derive the key: `GetKey(domain, algorithm)` on the internal socket. +2. Commit to it: build `report_data` over `public_key` yourself. Prefix it so a + verifier can tell what it is looking at -- see the `dip1::` convention the + frozen method uses. +3. Attest it: `Attest(report_data)` on the internal socket. +4. Publish it: hand the resulting attestation to relying parties. The + application serves it; the agent's external listener does not. + +This is strictly more capable than the method it replaces. The application picks +which of its keys to attest, and picks the commitment format, instead of being +limited to the single key the agent would derive for it. + +Legacy flows keep using `Worker.GetAttestationForAppKey`, unchanged and frozen. +It is Intel TDX only, because it returns a `GetQuoteResponse`. + +`Health` is polled by the gateway to decide whether an instance belongs in its +application's load-balancing rotation. It answers from a cache the agent +refreshes on its own timer, so one call costs a lock and a clone however many +gateway nodes are polling. Only instances that opted in via +`RegisterCvmRequest.health_check` are ever polled; see +[Application health checks](./app-health-checks.md). + +An app that never opted in answers `healthy: true` with an empty `unhealthy` +and no `error`, whatever its containers are doing: it declared itself +un-polled, so the agent computes no verdict and returns what the gateway would +have assumed. A caller other than the gateway must read that `true` as "nobody +asked me to know", not as a health check that passed. + +### public_tcbinfo on the external surface + +The v1 `Worker.Info` returns the same `InfoResponse` the internal surface returns, +minus what the application asked to keep private. Unless the app-compose sets +`public_tcbinfo`, the three document fields come back as empty strings: + +- `app_compose` +- `vm_config` +- `key_provider_info` + +Identity and the measurement hashes are always present. + +This is close to, but deliberately not the same as, what the frozen +`Worker.Info` does. That one blanks `tcb_info` and `vm_config`, and serves +`key_provider_info` externally in every case. v1 blanks `key_provider_info` too: +it names the component holding the application's keys, and an external caller +has no use for it. The frozen behaviour is unchanged on its own surface, so a +v0.5.x client sees exactly what it always did. + +| Field | frozen `Worker.Info` | v1 `Worker.Info` | +|---|---|---| +| identity, measurement hashes | always served | always served | +| `tcb_info` / measurement registers | blanked | not in the message at all | +| `vm_config` | blanked | blanked | +| `app_compose` | (nested in `tcb_info`, blanked) | blanked | +| `key_provider_info` | **always served** | **blanked** | + +The internal v1 `DstackGuest.Info` applies no gating at all. The flag decides what +an outside party may learn, and the caller on the internal socket is the +application itself; an application cannot need protecting from its own +configuration. + +## Attestation + +`Attest` is v1's only CVM attestation entry point. It takes up to 64 bytes of +`report_data`, zero-padded on the right to 64; more than 64 bytes is an error +rather than a truncation. It returns the versioned dstack attestation format, +which covers every supported platform. + +### Extracting a quote from an attestation + +`AttestResponse.attestation` is a `VersionedAttestation`. The authoritative +implementation is `dstack/dstack-attest/src/v1.rs`, and `dstack-verifier` is the +reference consumer. + +v1 `Attest` always returns the V1 schema: a MessagePack map produced by +`rmp_serde::to_vec_named`, whatever platform the CVM runs on and whatever +runtime event-log version it uses: + +```text +{ "version": u64, + "platform": { "kind": , "data": { ... } }, + "stack": { "kind": , "data": { ... } } } +``` + +`platform.kind` is one of `tdx`, `gcp-tdx`, `nitro-enclave`, `aws-nitro-tpm`, or +`sev-snp`. For `tdx` and `gcp-tdx`, `platform.data` carries `quote` (the raw TDX +quote bytes, exactly what the unversioned `GetQuote` returned) and `event_log`. +`gcp-tdx` additionally carries `tpm_quote`, which GCP's own verification binds and +which `GetQuote` had no field for. The other three platforms have no TDX quote, +which is why `GetQuote` could not answer on them at all. + +`stack.data.report_data` carries the 64 bytes the caller asked for. + +A general `VersionedAttestation` decoder still has to accept the legacy form, in +which the first byte is `0x00` and the rest is SCALE-encoded V0. The frozen v0 +`Attest` and `GetTlsKey` still produce it, and so do the KMS and gateway +certificates built on them and every older release; a decoder tells the two +forms apart by that first byte. A client that reads only v1 `Attest` can treat +anything other than a MessagePack map as malformed. MessagePack needs dstack +0.5.9 or later on the verifying side (`dstack-verifier`, KMS, gateway); earlier +releases decode only SCALE. + +V2 runtime events in the event log always include the hex-encoded preimage of +their digest; a verifier should check that `sha384(hex_decode(preimage))` equals +the digest. + +### GPU evidence + +Both GPU methods return the same thing: a list of `GpuEvidenceBundle`, each +carrying `vendor`, `format`, and opaque `evidence` bytes. `AttestGpu` returns +its bundles directly; `Attest` returns them in +`AttestResponse.boottime_gpu_evidence`. A consumer writes one bundle parser and +dispatches on `(vendor, format)`. + +| Source | `vendor` | `format` | Answers | +|---|---|---|---| +| `AttestGpu` | `nvidia` | `nvidia-nvattest-collect-evidence-json-v1` | is this device genuine right now | +| `Attest` | `nvidia` | `nvidia-nvattest-boottime-json-v1` | what the boot looked like | + +The two `format` values are deliberately distinct. They answer different +questions and a verifier for one does not appraise the other, so sharing a tag +would leave a consumer no way to tell a live measurement from a boot record. + +`boottime_gpu_evidence` is populated only when the request sets +`include_boottime_gpu_evidence` and boot-time output exists. Absence is the +empty list; there is no sentinel value. + +Its `evidence` is the exact bytes of the nvattest output as the agent read them +from disk. That exactness is the contract, not an implementation detail: the +only thing tying this evidence to the boot is `sha256` over precisely those +bytes, compared against the `evidence_sha256` field of the measured +`gpu-attestation` event after replaying the runtime event log. Parsing and +re-serializing the JSON before hashing changes the digest and breaks the +comparison. + +That evidence is not bound to `report_data` -- nvattest ran at boot against its +own nonce, so a fresh `report_data` says nothing about it. + +It is also a historical statement about the boot, not a live one: it does not +prove the GPU is still attached. Sampling the GPU at attestation time would not +fix it, because an NVIDIA report binds the device and a nonce but not the TD the +device is attached to, so a fresh report can be relayed from a genuine remote +GPU. Only TDISP/TEE-IO device binding closes that gap. + +`AttestGpu` answers the narrower question of whether the device reachable right +now is a genuine CC-enabled GPU that signs a caller-chosen 32-byte nonce. It +returns vendor-native evidence rather than a local verdict, so a relying party +appraises it with its own verifier: select one by `vendor` and `format`, then +check the signature, certificate chain, measurements, and the nonce embedded in +the evidence. + +## Info + +`Info` returns identity and configuration. It is not attestation, and nothing it +returns is evidence: the response arrives over a local socket with no quote behind +it. + +That is why the measurement registers and the event log are absent. v0's +`AppInfo.tcb_info` carried MRTD, RTMR0-3 and the event log inside a JSON string, +which invited relying parties to read measurements out of an unattested response. +Those values belong to `Attest`, whose attestation carries them quote-backed. + +`mr_aggregated`, `os_image_hash` and `compose_hash` remain, deliberately. They +identify *which* application and image this is, which is the question `Info` +answers. They are typed bytes rather than hex strings inside a JSON blob, and each +appears exactly once; v0 returned all three both as top-level fields and again, +hex-encoded, inside `tcb_info`. They are still unattested, and a relying party +still confirms them against an attestation. + +`app_cert` is gone. It was a self-issued demo certificate the agent minted for a +dashboard, and it proved nothing. + +`app_compose` carries the verbatim deployed document. `compose_hash` is `sha256` +over exactly those bytes, so do not parse and re-serialize before hashing: key +order, whitespace and unknown fields all change the digest, and that digest is +what gets whitelisted on chain. + +The v1 `DstackGuest.Info` on the internal socket applies no hiding: the caller is the +application itself, which cannot need protecting from its own configuration. +The v1 `Worker.Info` on the external listener honours `public_tcbinfo`; see +[public_tcbinfo on the external surface](#public_tcbinfo-on-the-external-surface), +which is the authoritative description. + +## Errors + +| Condition | Behaviour | +|---|---| +| Empty or unrecognised `algorithm` | Error naming the accepted values | +| Derived secp256k1 scalar out of range | Error; the caller picks another domain | +| `report_data` longer than 64 bytes | Error | +| `nonce` not exactly 32 bytes | Error naming the required length | +| GPU attestation unavailable in this image | HTTP 501; `AttestGpu` has nothing to collect | +| `not_before` not earlier than `not_after` | Error | +| Unknown method on a mounted surface | HTTP 404, `Service not found: ` | +| `/v1/...` on an agent that predates v1 | HTTP 404, no such mount | + +Every row that does not name a status is an HTTP 400 with the message in the +body. See [Status codes](#status-codes) for the full mapping. v1 does not +default, coerce, or truncate a malformed request into a well-formed one. + +The GPU row is a 501 rather than a 400 because it is a property of the image, +not of the call: the request is well-formed, and no other request would succeed +either. A client that reads 400 there retries with different arguments forever; +one that reads 501 stops and falls back to whatever it does without a GPU. A +malformed nonce is still the caller's fault and still a 400. + +## Migration from the unversioned API + +**v1 keys are different keys.** Deriving under the same name on `/v1` that an +application used on `/` returns different key material. This is the point of the +new KDF, not a defect: the v0 derivation ignored the algorithm, so one secret +served two curves. There is no compatibility mode and no flag to get the old bytes +back from `/v1`. + +An application holding assets or identity under a v0 key must migrate them +deliberately. Derive the v1 key, move the asset with a transaction signed by the +v0 key, and only then cut over. An application with no persistent state can switch +by pointing at the new URL. + +Both unversioned surfaces stay available and closed, and they have their own +normative specification: [dstack Guest Agent API v0](./guest-api-v0.md) pins the +frozen KDF, the `:`-joined chain claim, and the per-algorithm `Sign` and `Verify` +modes. A v0.5.x client keeps working against a 0.6 agent with no changes: `Sign`, `Verify` and `EmitEvent` +remain on the internal one (`EmitEvent` fails with a message naming its removal), +and `GetAttestationForAppKey` remains on the external one. Nothing forces a +migration. + +**SDK shape.** All four SDKs ship two clients mirroring the two surfaces, and +**the unsuffixed client is this one**: `DstackClient` names the v1 client and is +the recommended default. `DstackClientV0` is the closed unversioned API, +explicitly named and marked legacy, and still carries its `Sign` and `Verify` +RPCs. They are transport mirrors, not a compatibility layer: neither translates +a call to the other, and each one's method set is exactly its surface's. + +Every field this document declares `bytes` is that language's byte type in the +v1 clients -- `Vec`, `bytes`, `[]byte`, `Uint8Array` -- with hex confined to +serialization. `public_key` is why: the claim above is built over the raw key, +and a hex string handed to a claim builder silently produces a chain that never +verifies. The v0 clients keep their hex strings and `decode_*` helpers, because +that surface is frozen. + +That alias flipped in 0.6.0. Code that used the unsuffixed client for v0 calls +fails loudly on upgrade -- the v1 signatures differ and `GetKey` requires +`algorithm` explicitly -- rather than silently deriving different keys under the +new KDF. To stay on the frozen surface, name `DstackClientV0`. + +`ClientV1` has no `Sign` and no `Verify`, because v1 has neither. An application +signs locally with the key `GetKey` returns, and a relying party verifies +locally, following the rules above. The SDKs deliberately ship no verification +helper: verifying needs no client and no connection, and this document is what a +verifier implements against. + +## Field mapping + +For readers porting from the unversioned API. + +| v0 | v1 | Note | +|---|---|---| +| `GetTlsKey` | `IssueCert` | Renamed; the embedded RA-TLS attestation is always MessagePack V1 | +| `GetKeyArgs.path` + `.purpose` | `GetKeyRequest.domain` | Merged; both KDF inputs now | +| `GetKeyArgs.algorithm` (defaulted) | `GetKeyRequest.algorithm` | Required; no `k256` alias | +| — | `GetKeyResponse.public_key` | Added | +| `GetQuote` | `Attest` | TDX-only channel subsumed | +| `AppInfo.tcb_info` | — | Measurements are typed fields; the rest belongs to `Attest` | +| `AppInfo.app_cert` | — | Dashboard artifact | +| `AppInfo.vm_config` | `InfoResponse.vm_config` | Unchanged content | +| `AppInfo.key_provider_info` | `InfoResponse.key_provider_info` | Unchanged content | +| (nested in `tcb_info`) | `InfoResponse.app_compose` | Promoted to top level | +| `Sign` | — | Removed; sign locally with the key from `GetKey` | +| `Verify` | — | Removed; verify locally per this document | +| `EmitEvent` | — | Removed; RTMR3 is system-owned | +| `Worker.GetAttestationForAppKey` | — | No v1 counterpart; a v1 app attests its own key, see above | +| frozen `Worker.Info` | v1 `Worker.Info` | Also gates `key_provider_info`; see above | + +## Related documents + +- [dstack Guest Agent API v0](./guest-api-v0.md), the normative spec for the + frozen unversioned surface +- [Attestation on Intel TDX](./attestation-tdx.md) +- [Application health checks](./app-health-checks.md), for `/prpc/v1/Health` +- [App Compose format](./normalized-app-compose.md), for the schema behind + `InfoResponse.app_compose` +- [On-chain governance](./onchain-governance.md), for the `DstackKms` contract that + publishes the KMS root public key diff --git a/docs/guest-netfilter-capabilities.md b/docs/guest-netfilter-capabilities.md new file mode 100644 index 0000000000..ce7f3bc5e8 --- /dev/null +++ b/docs/guest-netfilter-capabilities.md @@ -0,0 +1,211 @@ +# Guest netfilter capabilities + +Which packet-filtering capabilities a dstack guest image provides, and which +firewall path an application running nested container managers (Incus, LXD, +libvirt, a nested Docker) should expect to work. + +Applications that only publish ports through docker-compose do not need this +page: dstack's own networking and Docker's published ports work on every image. +It matters when something inside the CVM programs its own bridges and firewall +rules. + +## One dataplane: nftables + +Every netfilter frontend in the image writes to nftables. `iptables`, +`ip6tables` and `ebtables` are the nft-backed frontends, so Docker's rules, +dstack's own `DSTACK_WG` chain and anything a tenant workload writes all land +in one ruleset that a single `nft list ruleset` can show. + +This matters more than tidiness. The legacy and nf_tables rulesets register at +the same netfilter hooks but cannot see each other, so on a mixed image the +effective ruleset is only knowable by querying both. A container manager that +selects a firewall driver by probing which ruleset is already in use gets +steered by whatever Docker happened to do — which is what made Incus managed +bridges fail on 0.5.x, where the frontends were legacy. + +Both backends reach this the same way, but from different directions: + +| | `os/yocto` | `os/mkosi` | +| --- | --- | --- | +| Frontend | `xtables-nft-multi`, linked in `iptables_%.bbappend` | Debian's nft frontend | +| How it is guaranteed | built explicitly by the recipe | asserted in `parity.json` | +| `NETFILTER_XTABLES_LEGACY` in kernel | `y` (from `netfilter.scc`) | not set | +| Legacy frontends still present | yes, as `*-legacy` | binaries exist, no kernel tables | + +Neither image *removes* the legacy binaries, so `iptables-legacy` remains +callable. On Yocto it still works, because that kernel keeps the legacy tables; +on mkosi it has no tables behind it. Use the unsuffixed commands. + +## Capability matrix + +Everything listed is a loadable module (`=m`) unless stated. Values were read +from a built `kernel-config` artifact for Yocto, and from the `.config` that +`x86_64_defconfig` plus `os/mkosi/components/kernel/kernel.config` produces for +mkosi. + +| Capability | Kconfig symbol | Yocto | mkosi | Since | +| --- | --- | --- | --- | --- | +| nftables core | `NF_TABLES` | yes | yes | 0.5.x | +| xtables-over-nftables | `NFT_COMPAT` | yes | yes | 0.5.x | +| nftables bridge family | `NF_TABLES_BRIDGE` | yes | yes | 0.6.0 (mkosi) | +| bridge meta / reject | `NFT_BRIDGE_META`, `NFT_BRIDGE_REJECT` | yes | yes | 0.6.0 | +| ebtables framework | `BRIDGE_NF_EBTABLES` | yes | yes | 0.5.x | +| ebtables matches | `BRIDGE_EBT_ARP`, `_IP`, `_IP6`, `_AMONG`, `_LIMIT`, `_VLAN` | yes | yes | 0.6.0 | +| ebtables legacy tables | `BRIDGE_NF_EBTABLES_LEGACY`, `BRIDGE_EBT_T_*` | **no** | **no** | — | +| CHECKSUM target | `NETFILTER_XT_TARGET_CHECKSUM` | yes | yes | 0.6.0 (mkosi) | +| IPv4 tables | `IP_NF_IPTABLES` | yes | built in | 0.5.x | +| IPv4 legacy tables | `IP_NF_IPTABLES_LEGACY` | yes | **no** | — | +| IPv6 tables | `IP6_NF_IPTABLES` | yes | built in | 0.6.0 (Yocto) | +| IPv6 NAT / filter / mangle | `IP6_NF_NAT`, `IP6_NF_FILTER`, `IP6_NF_MANGLE` | yes | n/a | 0.6.0 (Yocto) | +| ipset | `IP_SET` and the hash/bitmap set types | yes | yes | 0.5.x | + +Userspace: both images ship `iptables` and `nftables`. `ebtables` is the +nft-backed frontend from the same multi-call binary, not the standalone legacy +package. + +Three entries deserve a note. + +**The legacy ebtables tables are deliberately absent.** +`BRIDGE_NF_EBTABLES` builds only the matches, targets and watchers; since the +6.15 legacy-tables split the tables and `ebtables.ko` itself hang off +`BRIDGE_NF_EBTABLES_LEGACY`, which defaults to `n`. Nothing on an nft frontend +uses them — `ebtables-nft` emits nft bridge rules and reaches the `ebt_*` +match modules through `nft_compat`. + +**The IPv6 legacy tables on Yocto are for completeness, not for the default +path.** The nft frontend synthesises whatever table it is asked for, so +`ip6tables` needs no `ip6table_nat` module. They are enabled because that +kernel keeps `NETFILTER_XTABLES_LEGACY` on and has the full IPv4 legacy set, so +IPv6 being the one missing family meant `ip6tables-legacy` could not even list +a table. + +**`CHECKSUM` is still required.** The DHCP path of a managed bridge appends +`-j CHECKSUM --checksum-fill` so dnsmasq's replies reach guests with +checksum-offloading virtio NICs. On an nft frontend that is programmed through +`nft_compat`, which still needs the `xt_CHECKSUM` module. + +## Beyond netfilter: traffic control and checkpoint/restore + +Two more guest-kernel capabilities a nested container manager depends on live +in the same two fragments. Both are built in (`=y`), so neither backend has a +module to package or autoload. + +| Capability | Kconfig symbol | Yocto | mkosi | Since | +| --- | --- | --- | --- | --- | +| HTB qdisc | `NET_SCH_HTB` | built in | built in | 0.6.0 | +| ingress qdisc | `NET_SCH_INGRESS` | built in | built in | 0.6.0 | +| u32 classifier | `NET_CLS_U32` | built in | built in | 0.6.0 | +| police action | `NET_ACT_POLICE` | built in | built in | 0.6.0 | +| checkpoint/restore | `CHECKPOINT_RESTORE` | built in | built in | 0.6.0 (mkosi) | +| macvlan | `MACVLAN` | built in | built in | 0.6.0 (mkosi) | +| comment match | `NETFILTER_XT_MATCH_COMMENT` | yes | yes | 0.6.0 (mkosi) | +| socket diag | `UNIX_DIAG`, `INET_DIAG`, `PACKET_DIAG`, `NETLINK_DIAG` | built in | built in | 0.6.0 (mkosi) | + +**Per-instance bandwidth limits need all four `tc` pieces.** Incus implements +`limits.max` (and `limits.ingress` / `limits.egress`) on a bridged NIC as an +HTB root qdisc and class on the host-side veth for egress, and an ingress +qdisc with a u32 filter and a police action for ingress. `NET_SCHED` and +`NET_CLS_ACT` alone do not provide any of them: on 0.5.x the manager accepts +the setting and then fails to start the instance with `Specified qdisc kind is +unknown` (#1176). + +**`CHECKPOINT_RESTORE` is what lets the LXC monitor be found.** LXC retitles +its monitor process to `[lxc monitor] ` with +`prctl(PR_SET_MM, PR_SET_MM_MAP, ...)`, and Incus's seccomp notification +handler resolves a monitor PID to its instance by that title. The prctl is +only implemented under `CHECKPOINT_RESTORE`; without it the monitor keeps its +`incusd forkstart` command line, the daemon logs `Failed to find container +for monitor `, and every intercepted syscall +(`security.syscalls.intercept.*`) is resumed unhandled instead of getting the +container-aware answer (#1180). Everything the symbol gates needs +`CAP_CHECKPOINT_RESTORE` or `CAP_SYS_ADMIN`, and none of it faces the host. +The Yocto 6.18 kernel already had it through meta-virtualization's +`cfg/lxc.scc` and `cfg/criu.scc`; the mkosi kernel did not, and the 6.9 +kernel of 0.5.9 did not either. + +**LXC's own audit runs against both kernels.** `lxc-checkconfig` is the +script LXC ships to check a kernel for what containers need, and it is the +closest thing Incus has to Docker's `check-config.sh` — Incus itself has no +equivalent, and its documentation defers to "any kernel feature required by +the LXC version in use". It is vendored at `os/common/scripts/lxc-checkconfig` +and `check-lxc-kernel-config.sh` runs it after the fragment gate in both +builds, failing on anything it reports missing. The last three rows above are +what it flagged on the mkosi kernel the first time it ran: `MACVLAN` (Incus +`nictype=macvlan`), `xt_comment` (`-m comment` on the xtables frontends) and +the socket-diag interfaces `ss` and CRIU use. It does not know about traffic +control, so the `tc` rows are asserted by the fragments alone. + +## Running a nested bridge manager alongside Docker + +Having the capabilities is not the whole story. Docker sets the `FORWARD` chain +policy to `drop`, and `br_netfilter` is loaded with +`net.bridge.bridge-nf-call-iptables = 1`, so frames bridged between two +containers on someone else's bridge still traverse that chain. nftables base +chains in different tables are evaluated independently at the same hook, so a +manager that installs its own `accept` rules in its own table — Incus creates +`table inet incus` with `policy accept` and per-bridge accept rules — does not +override Docker's `drop`. The bridge comes up, DHCP works, containers get +addresses, and then nothing can talk to anything. + +This is the long-standing interaction between Docker's forward policy and +libvirt/LXD/Incus-style bridge managers, and it is what every distribution that +defaults to the nftables frontend already behaves like. + +It is, however, a behaviour change for the Yocto image, which programmed the +legacy tables before dstack 0.6.0. On that path Incus selected its xtables +driver and installed its accept rules with +`iptables -I filter FORWARD -i -j ACCEPT` — into Docker's *own* chain, +ahead of the policy — so forwarding worked without any extra rule. Under the +nftables driver the accept lands in a separate table and no longer pre-empts +Docker's policy. In practice the older image could not create a working managed +bridge at all (that is what #1032 reports), so few deployments will have relied +on it, but a setup that used the reported workaround of disabling DHCP and IPv6 +will now need the rule below. + +One rule per managed bridge fixes it: + +```sh +iptables -w 5 -I DOCKER-USER -i -o -j ACCEPT +ip6tables -w 5 -I DOCKER-USER -i -o -j ACCEPT +``` + +Measured in a CVM with Incus 6.0.4 and two system containers on a managed +bridge: 100% packet loss before, 0% after, for both IPv4 and IPv6. + +One benefit of the single nftables dataplane is that this is now diagnosable. +`nft list ruleset` shows Docker's `policy drop` and Incus's accept rules +together; when the two lived in different rulesets, neither `iptables -L` nor +`nft list ruleset` alone showed both halves of the interaction. + +## Adding a capability + +Kernel configuration lives in two fragments, one per backend: + +- `os/yocto/layers/meta-dstack/recipes-kernel/linux/files/dstack-docker.cfg` +- `os/mkosi/components/kernel/kernel.config` + +Their bridge-filtering blocks are deliberately identical. Keep them that way: +that is the capability the two images silently disagreed on. + +A fragment line is a request, not a guarantee. Kconfig silently drops a symbol +whose dependencies are unmet, and silently clamps a tristate to the value of +what it depends on — `CONFIG_BRIDGE_NF_EBTABLES=y` under `CONFIG_BRIDGE=m` +becomes `=m`, and the build still succeeds. Check the produced `.config` rather +than assuming, with `os/common/scripts/check-kernel-config.sh <.config> +`; both backends run it, mkosi during the kernel build and Yocto +in `os/yocto/scripts/export-artifacts.sh` before anything is published. +`os/common/scripts/check-lxc-kernel-config.sh <.config>` runs at the same two +points and is the second gate to satisfy: it fails on anything LXC's +`lxc-checkconfig` reports missing, with the two `IP*_NF_TARGET_MASQUERADE` +compat aliases (pure `select`s of `NETFILTER_XT_TARGET_MASQUERADE`, which both +kernels build) as the only exemptions. + +On the Yocto backend a module also has to be *packaged* into the rootfs. +`RDEPENDS:${KERNEL_PACKAGE_NAME}-base` is cleared in +`layers/meta-dstack/conf/machine/dstack.conf`, so the image contains only the +`kernel-module-*` packages named explicitly in +`layers/meta-dstack/recipes-core/images/dstack-rootfs-base.inc` plus those +pulled in by `RRECOMMENDS` — notably the `ip6table_*` and `xt_checksum` modules +recommended by the `iptables` recipe, which are installed only once the kernel +actually builds them. The mkosi backend runs a full `modules_install`, so every +module its config produces is present. diff --git a/docs/hardware-enablement.md b/docs/hardware-enablement.md new file mode 100644 index 0000000000..fb5030d475 --- /dev/null +++ b/docs/hardware-enablement.md @@ -0,0 +1,64 @@ +# Hardware enablement + +Use this page to prepare a bare-metal host before running the [self-hosted quick onboarding guide](./onboarding.md). + +dstack does not enable confidential-computing hardware by itself. The host firmware, kernel, device nodes, and QEMU build must already support the target platform. + +## Intel TDX hosts + +Use the [Canonical TDX setup guide](https://github.com/canonical/tdx) for Ubuntu hosts. The Canonical guide covers supported processors, host OS setup, BIOS settings, reboot, and host verification. + +For dstack, the host must have: + +- Intel TDX enabled in firmware and the host OS. +- SGX enabled in firmware and exposed to Linux. +- A TDX-capable QEMU available at `/usr/bin/qemu-system-x86_64`. +- SGX device nodes for the local key provider: + - `/dev/sgx_enclave` + - `/dev/sgx_provision` + +Check the host after you complete the platform setup: + +```bash +sudo dmesg | grep -i tdx +test -e /dev/sgx_enclave && test -e /dev/sgx_provision +/usr/bin/qemu-system-x86_64 --version +``` + +The Canonical guide's TDX verification expects `dmesg` to show that the TDX module initialized. If the SGX device nodes are missing, `dstackup install` cannot start the default local key provider. + +Do not install a generic QEMU package as a substitute for TDX host setup. Use the QEMU and kernel stack from your TDX host enablement path. + +## AMD SEV-SNP hosts + +Use your vendor or distribution's SEV-SNP enablement path. The [AMDSEV project](https://github.com/AMDESE/AMDSEV) documents CPU, BIOS, firmware, kernel, QEMU, OVMF, and verification requirements for SEV-SNP hosts. Confidential Containers also keeps platform setup separate from its [quickstart](https://github.com/confidential-containers/documentation/blob/main/quickstart.md) and points SEV users to AMD host preparation from its [SEV guide](https://github.com/confidential-containers/documentation/blob/main/guides/sev.md). + +After the host is enabled, follow [AMD SEV-SNP Support](./amd-sev-snp.md) for +the dstack guest image, installation, attestation, and KMS release policy. + +For dstack, the host must have: + +- AMD SEV-SNP enabled in firmware and the host OS. +- `/dev/sev` exposed to Linux. +- A QEMU and OVMF stack that supports SEV-SNP. + +Check the host after you complete the platform setup: + +```bash +test -e /dev/sev +sudo dmesg | grep -e SEV-SNP -e RMP +cat /sys/module/kvm_amd/parameters/sev_snp +``` + +The AMDSEV verification path expects `dmesg` to show SEV-SNP and RMP initialization, and `sev_snp` to read `Y`. + +Host enablement is necessary but not sufficient for onboarding with KMS. The selected guest image must also contain `digest.txt`, which `dstackup install` uses to pin apps to the measured OS image. + +## What dstackup checks + +`dstackup install` does a local platform preflight before it writes host config: + +- For TDX, it checks the SGX device nodes used by the local key provider. +- For AMD SEV-SNP, it checks `/dev/sev`. + +These checks catch missing runtime devices. They do not replace the host enablement process above. diff --git a/docs/kms-emergency-key-rotation-protocol.md b/docs/kms-emergency-key-rotation-protocol.md new file mode 100644 index 0000000000..350af7558b --- /dev/null +++ b/docs/kms-emergency-key-rotation-protocol.md @@ -0,0 +1,371 @@ +# KMS emergency key rotation protocol + +**Status:** Implemented. + +## 1. Scope and assumptions + +- Threat model: KMS root private keys are exposed, while disk data, LUKS headers, + and provider/host access are not. Repair the KMS environment before rotation. +- Stop all application CVMs and gateways; upgrade their OS and restart together. +- Reuse DstackKms governance and its OS allowlist. Assume configured chain RPCs + are trusted; RPC rollback and malicious-host/data anti-rollback are out of scope. +- Keep existing root-public-key pins. Affected deployments are handled separately. +- Rotate LUKS keyslots only; the underlying volume key remains unchanged. +- Every current KMS stores and hands over the complete root history, epochs 0..N. +- KMS stores no individual migration progress. No JWT, live rotation, or gateway + admission-lease protocol is introduced. + +**Storage boundary:** old root + old LUKS header reveals the unchanged volume +key. If ciphertext is later exposed, this can affect post-rotation data too. +Treat historical headers/snapshots as sensitive and inventory/isolate/dispose of +copies operationally. Full reencryption is future work if host/storage exposure +enters the threat model; slot replacement is not equivalent protection. + +## 2. Behavior summary + +Historical GetAppKey requests return complete epoch material and stay available +without a deadline, so late or restored instances can still migrate. Automatic recovery covers +disk keyslots and environment ciphertext with cloud-platform assistance; +application-owned GetKey data and wallets remain application responsibilities. +Onboarding supports ordinary full-history import and rotation import followed +by local generation of the next epoch. Sections 6-7 specify these flows. + +## 3. Roots, policy, and compatibility + +`api_version` selects protocol behavior; `root_epoch` identifies root material. +Epoch 0 is the existing roots, with existing derivation formulas and outputs +unchanged. Every epoch selector is optional; unset means the current epoch. +The name leaves room for a separate per-app epoch later. Generate +independent fresh CA and secp256k1 roots for each new epoch; existing derivation +formulas can remain unchanged. Never reuse an epoch for different roots. + +DstackKms keeps a registry of each epoch's root public keys, whose keys and +chain hash never change once registered (a pending epoch may be popped), an +`evidenceUrl` locating the attestation that proves where they were generated, and +a chain hash `h_n = keccak256(h_{n-1} || keccak256(caPubkey) || keccak256(k256Pubkey))` +(zero `h_{-1}`) committing to every key up to `n`; the position in the chain +fixes `n`, and hashing each key first keeps the preimage fixed-length. The +contract accepts only the encodings the KMS produces: a 91-byte P-256 DER +SubjectPublicKeyInfo with an uncompressed point, and a 33-byte compressed +secp256k1 key, so one key cannot be registered under two encodings. The +evidence stays off chain (stored on chain it would cost about 720 gas per byte) +and needs no hash: its report data binds the keys, so only availability depends +on the URL, which the owner can update (`setRootEpochEvidenceUrl`) when the +evidence moves. Registering an epoch and +making it current are separate: `registerRootEpoch` appends (epoch 0 becomes +current at once) and `activateRootEpoch(n)` moves the current epoch forward one +step. `popRootEpoch(n, chainHash)` drops the last epoch while it is still pending, for when +the nodes holding it are lost before activation; a re-rotation then registers a +new `n`, whose OS image, KMS MR and device rows start empty because policy rows +are keyed by the epoch's chain hash. Prepare them again before activating. A +current epoch is never popped. `kmsInfo` follows the current epoch: +registering epoch 0 and each activation copy its keys there and clear the legacy +quote and event log; the legacy `setKmsInfo`, `setKmsQuote` and `setKmsEventlog` setters are removed. Epoch 0 must be the `kmsInfo` keys +when those are set; a legacy `kmsInfo` quote and event log are converted off +chain into the standard attestation encoding (`Attestation::from_tdx_quote`) +before publishing. The KMS sends the epoch it serves and its chain hash (`rootEpoch`, +`rootEpochHash`) in every boot check, and the auth backend owns the policy: it +denies a KMS that does not serve the current epoch with the registered keys. +Info responses report the current epoch for KMS startup and onboarding; boot +responses are unchanged, and so is the on-chain `AppBootInfo`. +Governance credentials must remain independent and uncompromised. + +The KMS keyring and backups contain every epoch the node holds, not just the +latest two. Keeping old roots does not authorize issuing old derived keys. There +is no local epoch configuration: a KMS serves the current epoch on chain, +provided its keyring holds it and reproduces its chain hash, and waits +otherwise. When the current epoch moves, the KMS restarts to follow it and +re-signs its RPC certificate under the new root CA. Each epoch is stored under +`epochs//` with the attestation produced when its keys were generated, and +onboarding hands both over; a `root-epoch` marker records the newest stored +epoch. + +Historical epochs are not time-limited. Their roots are already exposed, so +withholding derived keys from authorized CVMs would not reduce what an attacker +can derive, while it would strand instances or backups that miss a deadline. +Old OS images are cut off through the OS allowlist instead. If host-side disk +rollback enters the threat model, a release deadline can be added later. + +Compatibility: keep accepting GetAppKey versions 0/1. An absent selector means +the current epoch, which before any rotation is epoch 0, so old OS images see no +change. After rotation they cannot open migrated disks; remove old OS images +through the existing allowlist and retain OS-image verification. Historical +epoch access never overrides OS/application authorization. + +## 4. GetAppKey additive extension + +Reuse the existing [GetAppKey transport and authorization path](../dstack/kms/src/main_service.rs), +without claiming a new KMS measurement-allowlist check on the guest. Preserve +root-public-key checking through `key_provider_id`; there is no separate guest +epoch pin or chain query. Unpinned deployments retain their existing KMS identity +limitations: this proposal does not create independent replacement-root trust +for them. Changing a pin can change compose/config hashes and related allowlists +or verifier expectations; affected deployments need separate coordinated updates. + +Keep `api_version = 1`; add one epoch selector: + +```protobuf +message GetAppKeyRequest { + uint32 api_version = 1; + string vm_config = 2; + // Unset = the current epoch, N = epoch N. + optional uint32 root_epoch = 3; +} +// Add to AppKeyResponse; preserve fields 1-8 and their types. +uint32 root_epoch = 9; +``` + +Unset resolves to current once for this request; unknown epochs are rejected. +Response `root_epoch` and all epoch-dependent material in fields 1-8 belong to +the resolved epoch. There is no separate source disk field. Every epoch up to +current uses the same normal authorization. A guest asks for an older epoch by +number only when it needs one, so a boot with nothing to migrate makes a single +request. + +An allowed historical request returns the complete historical AppKeyResponse, +including env and application keys, to preserve legacy compatibility. This +replaces the earlier disk-only server response proposal: the new OS extracts +only disk_crypt_key and, when needed, env_crypt_key for migration, discarding +other historical material. It retains its latest bundle for app startup. This +accepted tradeoff restricts recipients, not cryptographic uses of returned keys. + +The guest checks explicit epoch responses against the requested number. An old +KMS ignores the selector and serves epoch 0, reporting 0; that is +indistinguishable from a not-yet-rotated KMS using these fields alone. +Existing root-public-key pins and removal of old KMS endpoints remain essential; +unpinned clients gain no new downgrade protection. Do not rely on cached/disabled +KMS self-authorization for immediate revocation. Test JSON compatibility separately. + +Authenticate the KMS connection against current configured trust. Historical +ca_cert in the response is historical data, not a replacement transport trust +anchor: do not install it or compare it as though it were the current server pin. + +## 5. OS slot migration and LUKS header metadata + +Store the epochs in one LUKS2 JSON token bound to the keyslot holding their key: + +```json +{"type":"dstack-kms","keyslots":["0"],"root_epoch":2,"app_epoch":0} +``` + +The validator rejects nonzero subsystem, unexpected labels, and any token but +this one. It accepts keyslot 0, keyslot 1, or both (only mid-migration), each +with the same pinned parameters, and requires both header copies to agree. +Disks without the token are epoch 0. Requires cryptsetup 2.5 or later +(`--token-replace`, `--new-key-slot`); Debian trixie ships 2.7. + +```text +copy the header to tmpfs -> validate the copy + initialization label set -> reformat (the disk holds no data yet) + token_or_0 > current -> refuse + current key unlocks a keyslot of the copy -> finish + otherwise, token_or_0 < current -> refuse unless + unsafe_allow_disk_migration + -> old keys of epoch token_or_0 + -> check they unlock the recorded slot (token slot, else slot 0) + -> luksKillSlot any other slot + -> luksAddKey (old key authorizes the new key in the free slot) + -> recopy and validate -> finish + finish: token import (current epochs, surviving slot) -> luksKillSlot others + -> recopy, validate, and check the result -> open with the copy +``` + +Each step is one LUKS2 metadata commit, which cryptsetup keeps crash-consistent +across both header copies. Whatever step a crash interrupts, the next boot +finds either the old key alone or a keyslot the current key already unlocks, +so trying the current key first resumes the migration. If another rotation +happens before that boot, the current key unlocks neither of the two keyslots +an interrupted migration leaves; the token still names the slot of the recorded +epochs, so the other slot is dropped, but only once the recorded epochs' key is +confirmed to unlock that slot, and the migration restarts from it. A crash between +`luksFormat` and the token import leaves the initialization label set, which is +cleared only after the filesystem exists, so such a disk is reformatted. Never +format on unlock failure. Invalid or unsupported metadata requires recovery. +The disk is opened only with the last validated in-memory copy. + +The guest refuses such a disk unless the app compose sets +`requirements.unsafe_allow_disk_migration`, which is strongly discouraged. +Re-keying keeps the volume key. The old root and any copy of the old LUKS +header reveal it, and every host, storage backend or snapshot that saw the disk +before the rotation has such a copy, since the header is plaintext. Whoever +holds both can read and modify a migrated disk at any time, before or after the +migration, and no later check can tell. Disabling the flag afterwards does not +help: the disk is then at the current epochs and never migrates again. Use it +only when the old root is known not to have leaked, or when losing the data is +worse than exposing it to whoever holds that root; otherwise start from a fresh +disk and restore data at the application layer. A resumed migration whose +current key already unlocks a keyslot needs no flag. Refusing historical keys to +the new image in the old policy row also blocks migration, but for every app and +together with env migration and historical `GetKey`. + +No extra reboot is required. Historical material is confined to the migration +step, not persisted or passed to applications. +Old OS implementations with the existing validator reject a token-bearing disk; +this is an additional defense, not a substitute for the OS allowlist. Because of +that, an epoch-0 disk is never tagged: before any rotation the new OS leaves the +header untouched, so rolling back to an older OS image still works. Disks +formatted at a later epoch are tagged immediately. + +Tested in a Debian trixie container (cryptsetup 2.7.5, 32 MiB file images, +LUKS2/PBKDF2, no dm mapping): full migrations, resumption after each step, +disagreeing header copies, failed `luksAddKey` or denied old epochs leaving the +old epochs in place, failed token import, and disks recording newer epochs. +Old key-area wiping remains a release blocker. + +## 6. Environment migration, application keys, and TLS + +First decrypt env using latest. On authentication failure, try historical keys +from current down to 0, at most once each per boot; no platform metadata is +required. Skip an epoch whose key the KMS refuses, or that does not decrypt, until +one does: each historical key is still authorized by the KMS, and stopping at a +refusal would strand env encrypted under an older epoch whose image is approved +there but not in a newer row. The search costs at most current+1 RA-TLS requests, +only until the env has been migrated. Ciphertext no key decrypts fails closed; +env epoch is independent of the disk token. Empty env requires no migration. + +Decrypt/re-encrypt only inside the CVM, using current env public key, existing +format, and fresh randomness. The guest does not read the replacement back: +sealing and opening are deterministic code, so integration tests guarantee that +a re-sealed env opens on the next boot, after the VMM has replaced the old one. +The guest pushes the result to the VMM with `HostApi.UpdateSealedEnv` on +every boot, before any application code runs, sending an empty env when nothing +changed. The host API is reached over the VM's own vsock, so the VMM knows which +VM sent it. The VMM records the env each boot starts with and accepts one update +per boot, only if the stored env is still the boot env, so an owner's concurrent +update is never overwritten. The update closes the window, and the guest starts +init scripts and containers only once the VMM has answered, failing the boot +otherwise; application-stage progress reports close it as well. Application +containers and scripts therefore cannot replace the env. Rocket's per-method limit bounds the request (1 MiB by default). A +missed update is retried on the next boot. Plaintext and private keys never +leave the CVM. + +`GetAppEnvEncryptPubKey` keeps its interface. It always derives and signs with +the current epoch's roots and never serves historical epochs: env public keys +encrypt new data, so serving an older epoch would encrypt new secrets to a leaked +key. The signer public key identifies the epoch; no response field is added. +SDKs/frontends refresh cached env public keys before uploads; old-key uploads +are still migrated at boot, but put new secrets under an exposed key. Prompt owners to replace exposed +external credentials: reencryption alone does not revoke passwords/tokens. + +Guest API v1 `GetKey` takes an optional `root_epoch` (unset = current) and reports the epoch it +derived from; the SDKs expose it as an optional argument. The default is the +current epoch so new keys never come from an exposed root by accident. GetKey +outputs therefore change after a rotation: owners migrate app-encrypted records, +signing trust, wallets, and permissions by reading old keys with an explicit +`root_epoch` before releasing business services. The guest agent fetches an +older epoch's app root from the KMS the first time GetKey names it and keeps it +in memory; old roots are not stored in the keys file. The frozen v0 surface +always uses the current epoch. A per-app epoch, if added later, follows the same convention. SignCert +retains existing checks and signs under current roots; GetMeta is not a trust +anchor. Change CVM/gateway certificate trust in both directions. Public ACME +certificates remain separate. Orchestration gates all business activity, including +outbound workers, until readiness. + +## 7. Full-history KMS onboarding + +Onboarding imports the source's whole keyring, 0..S, and checks it against the +recipient's `authorizeKms` result: the current epoch's chain hash, and the latest +registered epoch L (`latestRootEpoch`, `latestRootEpochHash`). It never selects a +subset. A source holding epochs beyond L is refused ("source KMS holds +unregistered root epochs"). When S = L, the chain hash of L must match; chain +hashes are cumulative, so this binds the whole pending tail, not only the current +prefix. A source holding exactly the current epoch still joins; one stopping +between the current epoch and L is refused, since its tail cannot be checked. With +`rotate`, it then generates epoch S+1. + +| Mode | Source requirement | Result | +| --- | --- | --- | +| Ordinary join | Holds the current epoch and nothing unregistered; a registered tail pending activation must match the latest chain hash | Keyring 0..S | +| Rotation join (`rotate=true`) | Holds exactly up to the current epoch, with no epoch registered beyond it | Keyring 0..S plus fresh epoch S+1 and attestation evidence | + +Every handover requires the recipient's KMS attestation: the source checks the +attested RA-TLS client certificate on both `Admin.GetKmsKey` and the public +`KMS.GetKmsKey`. Admin authorization (`source_token`) is required for joins +and rotations alike, because the public `KMS.GetKmsKey` is off by default +(`core.onboard.public_key_handover = false`). Enable it on a source only for +receivers that cannot use the admin listener, such as 0.5.x KMS nodes, and +reject incompatible legacy receivers without reducing the payload. The source's certificate must carry its +OS image hash. +Deployments that never registered epochs can still join at epoch 0. + +For rotation, generate fresh roots and attest them with the bootstrap encoding +used for every epoch: report data is +`keccak256("dstack-kms-genereted-keys-v1:{ca_pubkey_hex};{k256_pubkey_hex};")` +zero-padded to 64 bytes. The "genereted" spelling is part of the released format. +The evidence only has to prove the key pair was generated in an approved TEE. +It binds neither the epoch number, which comes from the on-chain registration +order, nor the preceding chain hash, which joins already check against the +registry; a mismatch in either is an availability problem that `servable_epoch` +catches at once, not a key leak. Before registering N, the owner verifies the +quote with dstack-verifier, checks the approved code and measurements, and +recomputes the report data from the published keys; the cluster keeps +serving N-1. After the other nodes onboard and hold N, the owner activates N and +every KMS restarts onto it. An old-root signature is not authorization. +Competing generators cannot both be registered as N; a losing node's keyring no +longer reproduces the chain hash, so it never serves and must onboard again. It +also cannot hand its N over: joining from it fails the latest-epoch check while N +is pending, so the wrong tail does not reach later joiners. + +Every authorization request (app checks and the KMS self check that gates all +RPCs) carries the epoch the KMS serves, so a backend refuses a stale or forked +KMS. On a denial the KMS reads the current epoch from the info endpoint and +restarts if it moved. A KMS predating root epochs sends none; backends treat it +as epoch 0 and, once a later epoch is current, deny both its self check and its +app checks, so old KMS software stops serving. The contract's legacy +`isKmsAllowed` and `isAppAllowed` refuse as well, so this cutoff does not depend +on the backend. Upgrade every KMS before +activating a new epoch. In-flight operations are not cancelled. + +Backups retain full history; closing migration does not delete roots. Replacement +KMS boot cannot depend on its own unavailable service or stopped gateway ingress. +Protect root storage and independent admin access. + +## 8. Cutover runbook + +1. Inventory app/key dependencies, env ciphertext, pins, and historical snapshots. + Prepare trusted OS images, application recovery, and provider-pin adjustments. +2. Stop business writes, CVMs, gateways, and compromised KMS paths. Repair/replace + KMS execution and rotate independently exposed admin credentials. +3. Rotation-onboard one node, register its new epoch, then ordinary-onboard peers. + Authorize new KMS images before removing old OS images; do not rotate again + during the cutover. +4. Boot new OS with business services held by orchestration. Start apps from + fresh data disks; `requirements.unsafe_allow_disk_migration` keeps an old + disk but leaves it exposed to the old root (section 5). Migrate slots and + complete platform env replacement; confirm app readiness. Ingress closure alone does + not stop workers, cron jobs, queues, or outbound database/wallet writes. +5. Start gateways with fresh data directories/KV namespaces and clean WireGuard + peers. Rebuild required non-admission configuration from trusted sources; + never restore old registration databases or admit old sync nodes. +6. Re-register CVMs with new certificates and release approved business + services/ingress. Keep failed instances isolated for operator follow-up. +7. Notify env public-key verifiers (vmm-cli signer whitelists, frontends, SDK + callers) to replace the old k256 signer with the new one, preferably by reading + it from DstackKms. For vmm-cli, run `kms remove `, then + `kms add `. A stale whitelist entry does not break migration, but + lets anyone holding the old root and able to intercept client-to-KMS traffic + forge env public keys; the `root_epoch` in a response is set by its signer + and protects nothing. + +## 9. Invariants and acceptance + +[TLA+ models](formal/key-rotation/README.md) check the registry, disk +migration and env update steps against crashes and interleavings. + +Authenticate actual secret-bearing connections; old-CA signatures alone do not +replace evidence checks. Do not downgrade on failure or expose secrets in logs, +command lines, swap, app key files, or host-shared storage. Released secrets +cannot be recalled. Historical key possession, +current unlock success, and production readiness are three different facts. + +Test legacy compatibility, OS-allowlist cutoff, selector boundaries and epoch-0 compatibility, non-adjacent epochs, +both onboarding modes, full-history atomic persistence, pending registration +restart, competing roots, live stale-node rejection, and epoch mismatch, slot/token crash recovery, +new-key reboot success, old-key unlock failure against the working header, and +absence of residual old paths and recovery from missing/stale epoch tokens. Confirm the volume key intentionally stays the +same. Test env corruption, independent env epochs, concurrent platform updates, +response-source authentication, bounded epoch search, stale-key uploads, +replacement/reboot recovery, application readiness, +and clean gateway reauthentication/sync. +Reports must state OS/TEE, kernel/cryptsetup, filesystem/layout, builds, topology, +policy, and failure injections. The preliminary test above is limited evidence, not release validation. diff --git a/docs/libvirt-network-filter.md b/docs/libvirt-network-filter.md new file mode 100644 index 0000000000..97e659c0c9 --- /dev/null +++ b/docs/libvirt-network-filter.md @@ -0,0 +1,257 @@ +# Optional libvirt network filtering + +## Goal + +Allow bridge-backed VMs to opt into an existing libvirt `nwfilter` without +allowing libvirt to create or launch the QEMU domain. QEMU remains entirely +owned by `dstack-vmm`, so its command line and attestation inputs do not change +outside the explicitly selected network backend. + +This integration applies only to bridge interfaces. It does not filter user, +custom, or macvtap networking. In particular, macvtap bypasses the Linux +bridge and requires policy enforcement in the physical network or a separate +host mechanism. + +The measurable acceptance criteria are: + +- `network_filter = "none"` installs no nwfilter binding. It does not remove + the `netd` dependency: `netd` creates the TAP for every bridge NIC either + way, and the VMM uses `-netdev tap` either way. What changes is only whether + that TAP carries a binding. +- `network_filter = "libvirt"` creates the TAP and filter binding before QEMU + is submitted to Supervisor, and uses QEMU `-netdev tap`. +- An nwfilter binding outlives the TAP it was bound to, so a teardown clears + the binding at every name that VM could have used, whether or not the + interface is still there. `dstack-vmm netd list` shows a binding whose + interface is already gone as a `binding` row; remove one with + `dstack-vmm netd remove-interface `. +- A failed TAP or filter setup prevents QEMU from starting and rolls back all + interfaces prepared for that VM. +- Normal stop and removal delete the filter binding and TAP. +- One host `netd` can serve multiple VMM instances. Resource names include a + stable VMM instance namespace, VM ID, and NIC index. +- Development builds can run the VMM and `netd` directly, with explicit socket + and allowed-UID command-line options; systemd is not required. + +## Configuration + +Filtering is a VMM host policy, not a field accepted from a VM manifest: + +```toml +[cvm.network_filter] +mode = "none" # or "libvirt" +filter = "clean-traffic" +parameters = {} + +[netd] +socket = "/run/dstack/netd.sock" +socket_mode = 0o660 # used when netd binds the socket itself +libvirt_uri = "qemu:///system" +``` + +Deployment RPC network choices are separately constrained by node policy: + +```toml +[cvm] +allowed_network_modes = ["user", "bridge"] +allowed_bridges = ["tenant-br0"] +allowed_macvtap_parents = [] +``` + +Macvtap is excluded from `allowed_network_modes` by default. Empty bridge and +macvtap-parent allowlists prevent RPC callers from overriding the respective +node defaults. If macvtap is explicitly enabled, callers may select a +parent listed in `allowed_macvtap_parents`, the node's own configured parent, or +one this VM already holds — restating a value the node would have supplied +anyway grants nothing new. The same applies to `bridge_name` and +`allowed_bridges`. The macvtap forwarding mode always comes +from `[cvm.networking].macvtap_mode` and cannot be selected through deployment +RPCs. These allowlists authorize attachment targets; an nwfilter is not a +substitute for that authorization. + +Each VMM instance also has an `instance_id`. It must be unique among VMMs that +share a host. If omitted, the VMM derives a stable namespace from its absolute +run directory. + +## Architecture + +`netd` is a host-level privilege broker. It serves the `Netd` pRPC service +(`dstack/vmm/netd-rpc/proto/netd_rpc.proto`) over a Unix stream socket, with +one method per operation. The socket's filesystem owner, group, and mode are +the authorization boundary: every process that can connect is fully trusted to +call every netd method. A single process can serve multiple VMMs; a dedicated +process can use another socket for development or isolation. + +The VMM and netd must come from the same release. After upgrading, restart +`dstack-netd` together with the VMM; a VMM cannot talk to a netd from a release +that predates the pRPC service. + +When netd creates the socket itself, `socket_mode` defaults to `0o660`. Ensure +that each authorized VMM process can reach the socket through its owning group +or another deliberately configured ownership arrangement. Never make the +socket accessible to an untrusted local user. + +For libvirt mode, startup is: + +1. Derive the TAP name from instance namespace, VM ID, and NIC index. +2. Create the TAP for the configured QEMU UID and attach it to the bridge. +3. Create a libvirt nwfilter binding for the TAP. +4. Bring the TAP up and return success. +5. Start QEMU directly with `-netdev tap,script=no,downscript=no`, carrying + `vhost=on|off` and, above one queue pair, `queues=N`. + +Teardown stops QEMU first, removes the binding, and deletes the TAP. `netd` +runs operations one at a time, in the order they arrive. The design intentionally does not add ownership +aliases; deployments must use unique instance IDs. + +The protocol does not pin a client to an instance namespace, so any process +with socket access can prepare, check, or remove any deterministic identity. +Deploy VMM instances that do not share this trust boundary with dedicated netd +sockets and distinct filesystem permissions. + +`netd` invokes fixed absolute `ip` and `virsh` executables with separate +arguments. It never accepts a command, executable path, or raw XML from a +client. The only TAP name it accepts is the one `RemoveInterfaceByName` takes, +and only a name of the form netd itself creates (`dt` and 12 lowercase hex +digits), on a tun/tap or macvtap device. Filter XML is generated internally with +XML escaping and is validated by libvirt. + +Teardown by identity only reaches the NIC indices its caller still has a record +of, and that record is written *after* the interface exists — a VMM killed in +between leaves a TAP nothing on disk points at, and a manifest that lost a NIC +leaves the same thing behind. `RemoveVm` names a VM instead of an interface +and derives every name that VM could occupy, so neither has to be recorded for +teardown to work. The VMM keeps a single `.netd-pending` marker per VM from +before its first prepare until a sweep succeeds, and sweeps whenever that marker +is present: before a launch, on stop, on removal, and periodically for stopped +VMs. See [bridge-networking.md](bridge-networking.md#when-a-release-does-not-land). + +A prepare also carries `workdir`, which `netd` does not need to build the TAP. +It names the VM's directory on the host: untrusted, never read for a decision, +and present only so an operator reading `netd`'s log can get from an opaque TAP +name back to the VM. + +## Deployment modes + +Production should run one shared service. `netd` reads the `[netd]` section, +plus `cvm.network_filter.mode` if the file has one, so its root-owned +configuration can be small and independent of every VMM instance: + +```toml +# /etc/dstack/netd.toml +[netd] +socket = "/run/dstack/netd.sock" +socket_mode = 0o660 +libvirt_uri = "qemu:///system" + +# Required here because this file has no [cvm] section for netd to read the +# node's policy from. +[netd.network_filter] +mode = "libvirt" +filter = "clean-traffic" +parameters = {} +``` + +`[netd.network_filter]` is netd's own copy of the invariant, not a convenience. +netd is the privileged side of the socket, and anything that can reach the +socket can ask for an unfiltered TAP on a host bridge — a request a filtering +node has to refuse in the daemon rather than in its caller. When netd and the +VMM share one `vmm.toml`, leaving it unset derives it from +`[cvm.network_filter]` so the two cannot drift apart; a malformed section is a +startup error rather than a silent fallback to "filter nothing". + +The request says only *whether* to bind a filter, never which one. A caller that +named the filter could name `allow-arp`, which contains no drop rule at all, or +pin `clean-traffic` to the gateway's MAC and IP through its parameters, and +still satisfy a policy that asked for "some filter". + +A macvtap parent is refused when filtering is required and the parent is a host +bridge or is enslaved to one: nwfilter does not apply to macvtap, so that +request is the same unfiltered access to the same segment, spelled with a +different operation. + +Production deployments can use systemd socket activation. The socket unit +owns the filesystem mode and ownership; `netd.socket_mode` applies only to the +standalone bind path. + +```ini +# /etc/systemd/system/dstack-netd.socket +[Unit] +Description=dstack host networking socket + +[Socket] +ListenStream=/run/dstack/netd.sock +SocketMode=0660 +SocketUser=root +SocketGroup=dstack-vmm +RemoveOnStop=true + +[Install] +WantedBy=sockets.target +``` + +```ini +# /etc/systemd/system/dstack-netd.service +[Unit] +Description=dstack host networking service +After=libvirtd.service + +[Service] +ExecStart=/usr/bin/dstack-vmm --config /etc/dstack/netd.toml netd +Restart=on-failure +``` + +The service accepts exactly one Unix stream listener through the systemd +`LISTEN_FDS` protocol. With no activated descriptor it falls back to binding +`netd.socket` itself. More than one descriptor, or a descriptor of the wrong +socket type, is rejected. + +All VMM instance configurations point to the same socket and use distinct +`cvm.instance_id` values. A dedicated netd uses a different socket. A +host-wide lock serializes mutations made by shared and dedicated netd +processes. + +Development mode is two ordinary commands: + +```bash +sudo dstack-vmm --config ./vmm.toml netd \ + --socket /run/dstack-dev/netd.sock +sudo dstack-vmm --config ./vmm.toml \ + --netd-socket /run/dstack-dev/netd.sock +``` + +User networking and a caller-supplied netdev never ask `netd` to build an +interface, and a VM that has never used `netd` never contacts it. A VM that +moved from bridge or macvtap to user networking still releases what it held, +but nothing about its launch depends on the answer. Bridge and macvtap do ask, +and fail closed if `netd` is unavailable. + +Filtered TAP netdevs follow the node's `vhost` and `queues` settings like any +other TAP-backed NIC (see [network-data-plane.md](network-data-plane.md)). The +nwfilter binding is installed on the host TAP interface, so packets traverse it +whether they were written by QEMU or by a vhost worker; filtering is unaffected +by the data plane choice. Enabling vhost does require the QEMU user to be able +to open `/dev/vhost-net`. + +`netd` creates the TAP for unfiltered bridge NICs too. Those TAPs carry no +nwfilter binding, so a bridge node needs `netd` even when +`network_filter.mode = "none"` — see +[bridge-networking.md](bridge-networking.md) for why the host interface has a +single owner. + +An empty filter name is what selects that unfiltered TAP, so `mode = "libvirt"` +with an empty `filter` is rejected at config load rather than quietly producing +an unbound TAP. + +Removal carries the same distinction: the VMM tells `netd` whether the interface +it is asking about was created with a binding, from a record made when it was +built rather than from configuration that may have changed since. A binding it +was told about must be gone before `netd` returns; otherwise `netd` still asks +libvirt to clear one — an interface name is reused by the same VM, and a +leftover binding's rules would be inherited — but a `libvirtd` it cannot reach +is a warning rather than a failure. So a node with `virsh` installed and no +running `libvirtd` can create and destroy multiqueue TAPs. The flag defaults to +true on the wire, so an older VMM's removals still drop their bindings. + +`netd` requires the `virsh` binary to be present whatever the filter mode; it is +`libvirtd` that unfiltered work does not need. diff --git a/docs/macvtap-networking.md b/docs/macvtap-networking.md new file mode 100644 index 0000000000..362de4e876 --- /dev/null +++ b/docs/macvtap-networking.md @@ -0,0 +1,76 @@ +# Macvtap networking + +Macvtap mode gives each CVM a layer-2 identity on an existing host network +without adding the parent interface to a Linux bridge. The VMM delegates the +privileged interface lifecycle to `dstack-vmm netd`; manifests never contain +the unstable `/dev/tapN` device path. + +## Configuration + +Configure a NIC through node configuration or an authorized VMM RPC request: + +```json +{ + "mode": "macvtap", + "parent": "eth0", + "macvtap_mode": "private" +} +``` + +`parent` must name an existing host interface. `macvtap_mode` may be +`private`, `bridge`, `vepa`, or `passthru`; an empty value selects `private`. +Macvtap NICs also honour the `vhost` and `queues` settings described in +[network-data-plane.md](network-data-plane.md); netd creates the interface with +matching hardware queues and the launcher opens `/dev/tapN` once per queue. +The configured netd socket permissions apply in the same way as for +libvirt-filtered bridge networking. + +Deployment RPC callers cannot select `macvtap_mode`; it is inherited from the +node's `[cvm.networking]` configuration. Macvtap is also excluded from the +default RPC policy. A node operator must explicitly enable it and enumerate +the host interfaces callers may select: + +```toml +[cvm] +allowed_network_modes = ["user", "bridge", "macvtap"] +allowed_macvtap_parents = ["eth0"] + +[cvm.networking] +mode = "user" +parent = "eth0" +macvtap_mode = "private" +``` + +## Lifecycle + +For every macvtap NIC, the VMM sends netd the VM identity, NIC index, parent, +and the same deterministic MAC address passed to QEMU. Netd then: + +1. derives the stable `dt` interface name; +2. replaces any stale interface with that name; +3. creates and activates the macvtap interface; +4. reads its kernel-assigned ifindex and waits for `/dev/tap`; and +5. returns that runtime device path to the VMM. + +The per-VM launcher opens the character device once per queue pair, places the +descriptors at the fds referenced by QEMU's `-netdev tap,fd=...` (or `fds=...`) +argument, and then execs QEMU. This keeps device +paths out of persistent VM +configuration, works with both Supervisor and systemd process managers, and +does not pass network fds through `sudo`. + +VM shutdown removes the interface by its deterministic identity. The device +node disappears with the interface; its numeric path is never reused as an +identity or cleanup key. + +## Limitations + +- The host and a macvtap guest do not communicate directly through the parent + interface by default. Add a host macvlan/macvtap endpoint if that path is + required. +- Libvirt nwfilter bindings apply only to bridge mode and are never installed + for macvtap interfaces. Macvtap deployments + must enforce network policy in the physical network or with another host + mechanism. +- Real-host testing requires `CAP_NET_ADMIN`, a working udev setup for + `/dev/tapN`, and an upstream network that accepts multiple MAC addresses. diff --git a/docs/native-tee-interfaces.md b/docs/native-tee-interfaces.md new file mode 100644 index 0000000000..3574de999e --- /dev/null +++ b/docs/native-tee-interfaces.md @@ -0,0 +1,147 @@ +# Advanced Native TEE Interfaces in Containers + +Most applications should use the dstack API through `/var/run/dstack.sock`. Native TEE interfaces are available for advanced compatibility cases, such as unmodified binaries or libraries that already know how to use Linux TEE devices or configfs-tsm. + +The examples below use Compose syntax because dstack currently accepts Compose files for container configuration. + +## Choose an Interface + +Use native interfaces only when your application already depends on them. If you control the application code, prefer the dstack SDK or HTTP API because it also returns dstack metadata, event logs, and verification inputs. + +| Interface | Platform | Use when | +| --- | --- | --- | +| `/var/run/dstack.sock` | dstack-supported TEEs | Your application can call the dstack SDK or HTTP API | +| `/dev/tdx_guest` | Intel TDX | Existing software expects the Linux TDX guest device | +| `/dev/sev-guest` | AMD SEV-SNP | Existing software expects the Linux SEV-SNP guest device | +| `/sys/kernel/config/tsm/report` | Intel TDX and AMD SEV-SNP, when supported by the deployed OS image | Existing software expects configfs-tsm `inblob` and `outblob` report generation | + +The native report formats are platform-specific. Intel TDX returns TDX quote or report data, depending on the interface and library. AMD SEV-SNP returns an SNP attestation report and, for extended report flows, certificate data. + +## Version Availability + +The versions below refer to the dstack OS image version, not an SDK or service binary version. + +| Native interface | Available from | +| --- | --- | +| `/dev/tdx_guest` | dstack OS v0.5.0 on Intel TDX images. The v0.5.x images expose it through the bundled `tdx-guest` kernel module. The v0.6.0.a1 images and later use the in-tree Linux TDX guest driver. | +| TDX configfs-tsm at `/sys/kernel/config/tsm/report` | dstack OS v0.6.0.a1 and later on Intel TDX. It is not available in v0.5.x TDX images. | +| `/dev/sev-guest` | dstack OS v0.6.0 SEV-SNP image line and later on AMD SEV-SNP. It is not available in v0.5.x TDX images. | +| SEV-SNP configfs-tsm at `/sys/kernel/config/tsm/report` | dstack OS v0.6.0 SEV-SNP image line and later on AMD SEV-SNP, when the deployed image enables the Linux TSM report interface. | + +## Learn the Native Linux APIs + +These interfaces are Linux kernel ABIs, not dstack-specific APIs. Use the upstream documentation when you need ioctl structures, configfs file semantics, or provider-specific report formats: + +| API | Official reference | +| --- | --- | +| Intel TDX guest device | [TDX Guest API Documentation](https://docs.kernel.org/virt/coco/tdx-guest.html) | +| AMD SEV-SNP guest device | [SEV Guest API Documentation](https://docs.kernel.org/virt/coco/sev-guest.html) | +| configfs-tsm report ABI | [configfs-tsm report ABI](https://www.kernel.org/doc/Documentation/ABI/testing/configfs-tsm) | + +## Use the dstack API by Default + +Mount the dstack socket when your application can use the dstack SDK or HTTP API: + +```yaml +services: + app: + image: your-image + volumes: + - /var/run/dstack.sock:/var/run/dstack.sock +``` + +The dstack API is the normal application interface for quotes, keys, application information, and runtime events. See the [Guest Agent RPC API](../sdk/curl/api.md) for request and response details. + +## Expose Intel TDX Interfaces + +For TDX software that expects the Linux TDX guest device, expose `/dev/tdx_guest` to the container: + +```yaml +services: + app: + image: your-image + devices: + - /dev/tdx_guest:/dev/tdx_guest +``` + +For TDX software that expects configfs-tsm, mount the TSM configfs subtree: + +```yaml +services: + app: + image: your-image + volumes: + - /sys/kernel/config/tsm:/sys/kernel/config/tsm +``` + +Most configfs-tsm libraries create a report entry under `/sys/kernel/config/tsm/report`, write report data to `inblob`, and read the generated quote or report from `outblob`. + +## Expose AMD SEV-SNP Interfaces + +For SEV-SNP software that expects the Linux SEV guest device, expose `/dev/sev-guest` to the container: + +```yaml +services: + app: + image: your-image + devices: + - /dev/sev-guest:/dev/sev-guest +``` + +For SEV-SNP software that expects configfs-tsm, mount the same TSM configfs subtree: + +```yaml +services: + app: + image: your-image + volumes: + - /sys/kernel/config/tsm:/sys/kernel/config/tsm +``` + +On SEV-SNP, configfs-tsm exposes SNP report generation through the common Linux TSM report ABI. Provider-specific attributes and output files can differ from TDX. Check the library you are running for the exact files it reads. + +## Permissions + +Root containers can use root-owned device and configfs paths once they are exposed to the container. If your image switches to a non-root user, set up access before the non-root process starts. + +For device files, a root entrypoint can relax permissions and then launch the application: + +```yaml +services: + app: + image: your-image + devices: + - /dev/tdx_guest:/dev/tdx_guest + command: sh -lc 'chmod 666 /dev/tdx_guest && exec /app/start' +``` + +If the main process must stay non-root from the start, use a small root helper container to adjust the host device node before the application starts: + +```yaml +services: + tdx-device-perms: + image: busybox + volumes: + - /dev/tdx_guest:/dev/tdx_guest + command: chmod 666 /dev/tdx_guest + restart: "no" + + app: + image: your-image + user: "1000:1000" + depends_on: + tdx-device-perms: + condition: service_completed_successfully + devices: + - /dev/tdx_guest:/dev/tdx_guest +``` + +For AMD SEV-SNP, use the same pattern with `/dev/sev-guest`. + +For configfs-tsm, permissions can be more provider-specific. If your main process must remain non-root, keep the native ABI access in a small root helper process and expose only the operation your application needs over local IPC. + +## Intel TDX RTMR3 Measurements + +On TDX, RTMR3 is an append-only runtime measurement register. It is useful when a launcher measures code or configuration first, then hands permission and execution to the measured code. + +dstack itself extends RTMR3 during guest boot (compose-hash, key-provider, instance-id, and related runtime events). Applications that need additional runtime measurements should extend RTMR3 through the native TDX / TSM measurement interfaces documented above and own the event-log story for those extensions. diff --git a/docs/nerdctl-compose.md b/docs/nerdctl-compose.md new file mode 100644 index 0000000000..83ecf256b0 --- /dev/null +++ b/docs/nerdctl-compose.md @@ -0,0 +1,63 @@ +# nerdctl Compose and lazy image pulling + +dstack supports two independent Compose runners. The runner is part of +`app-compose.json`, so it is included in the compose hash and attestation. + +| `runner` | Image manager | `snapshotter` support | +|---|---|---| +| `docker-compose` | Docker Engine | none (Docker's overlayfs store) | +| `nerdctl-compose` | containerd | `overlayfs` or `stargz` | + +## Deploy with stargz + +Build and push an eStargz image before deployment. For example, with Buildx: + +```bash +docker buildx build -t registry.example.com/example/app:estargz \ + --output type=registry,oci-mediatypes=true,compression=estargz,force-compression=true \ + . +``` + +Reference that image from `docker-compose.yaml`, then deploy it with: + +```bash +dstack deploy -c docker-compose.yaml \ + --runner nerdctl-compose \ + --snapshotter stargz +``` + +The resulting application manifest contains: + +```json +{ + "manifest_version": "3", + "runner": "nerdctl-compose", + "snapshotter": "stargz" +} +``` + +Use containerd without lazy pulling by selecting overlayfs: + +```bash +dstack deploy -c docker-compose.yaml \ + --runner nerdctl-compose \ + --snapshotter overlayfs +``` + +If `snapshotter` is omitted for `nerdctl-compose`, it defaults to `overlayfs`. +Setting `snapshotter` with `docker-compose` is rejected rather than silently +ignored. + +## Compatibility + +`nerdctl compose` implements the commonly used Docker Compose features, but it +is not a drop-in implementation of every Docker-specific extension. Test +applications that use Docker socket mounts, custom runtimes, or advanced +networking before switching runners. The `nerdctl-compose` runner requires +pre-built images and rejects Compose `build` sections. This avoids depending +on an in-guest BuildKit daemon and ensures lazy-pull images were converted +before deployment. + +Both backends keep their own image and container metadata. Changing the runner +recreates the application through the selected backend; it does not migrate +existing Docker containers into containerd. diff --git a/docs/network-data-plane.md b/docs/network-data-plane.md new file mode 100644 index 0000000000..c80af880f7 --- /dev/null +++ b/docs/network-data-plane.md @@ -0,0 +1,293 @@ +# virtio-net data plane tuning + +Every CVM NIC has two knobs that decide how many packets it can move: whether +the host kernel's vhost-net data plane is used, and how many virtio-net queue +pairs the device exposes. vhost is set per node and overridable per VM; queue +pairs have no node-wide setting at all, for the reason given under +Configuration. + +## Why it matters + +Without vhost-net, QEMU drains every received packet on its single main-loop +thread. That thread is the ceiling, and it does not grow with vCPUs: + +``` +maximum packets per second ≈ 1 core ÷ per-packet main-loop cost +``` + +The per-packet cost varies with traffic shape — a few microseconds for uniform +synthetic streams, tens of microseconds for bidirectional short-connection +traffic — so the ceiling is a property of the workload, not a fixed number. +What is fixed is the shape of the failure: throughput climbs normally until the +main loop saturates at 100% of one core, then packets are dropped at the TAP +before they ever reach the guest. Guest-side counters stay clean, which makes +the cliff easy to misdiagnose as a network problem. + +Guest-side outbound traffic uses the same thread, so a busy guest pays the +cost twice over. + +`vhost=on` moves that work into the host kernel. That returns a whole core, but +it relocates the ceiling rather than removing +it: packets now arrive faster than a single guest receive queue can drain, and +the drops reappear at a higher rate. More queue pairs is what removes them, +which is why enabling vhost also enables a queue count that follows the VM's +vCPU count — the two travel together. + +vhost is **off by default** and enabled per node (or per VM). Two things make +it an opt-in rather than a default: turning it on changes the virtio-net device +of every bridge/macvtap VM on its next boot, and it requires `/dev/vhost-net` +to be accessible to the account QEMU runs under, which the VMM cannot verify on +the operator's behalf — see [Enabling vhost on a node](#enabling-vhost-on-a-node). + +## Configuration + +```toml +[cvm] +# Ceiling for both the default and what a deployment may request. +max_net_queues = 16 + +[cvm.networking] +mode = "bridge" +bridge = "dstack-br0" +vhost = true +``` + +Queue pairs are not a node setting. With vhost on they default to the VM's vCPU +count, capped at 16, because the useful number follows the VM rather than the +host — the guest driver uses at most one queue pair per vCPU. A deployment +overrides that per VM, up to `max_net_queues`. + +Raising `max_net_queues` above 16 widens what a deployment may ask for without +moving the default's cap, so a larger VM never silently acquires a worse +default. Lowering it below 16 does lower the default too, because a node that +refuses a request for four queue pairs should not hand out sixteen by itself. +The hard ceiling from any source is 64. + +Without vhost the default is a single queue pair. The QEMU main loop drains +every queue on one thread, so extra queues buy little while still costing more +MSI-X vectors and a changed guest device. An explicit +queue count is still honoured without vhost, since that combination is a +deliberate request rather than a default. The two defaults travelling together +also means a node that never sets `vhost` keeps building the device its VMs +have always had. + +A VM overrides either value at deploy time, and `UpdateVm` changes them +afterwards — the new values apply from the VM's next boot: + +```bash +vmm-cli.py deploy --name my-vm --image dstack-0.5.9 --compose app.yaml \ + --net bridge --net-queues 4 +vmm-cli.py deploy --name latency-vm --image dstack-0.5.9 --compose app.yaml \ + --net bridge --net-no-vhost + +# retune an existing VM +vmm-cli.py update --net-queues 8 --net-vhost + +# stop pinning either value and follow the node and the vCPU count again +vmm-cli.py update --net-queues auto +vmm-cli.py update --net-vhost-default + +# stop pinning the backend too, and follow whatever the node runs +vmm-cli.py update --net default +``` + +Every pin has an un-pin. A VM keeps reporting whatever it pinned, and the +deployment RPC accepts a VM's own held values back even after the node's +policy moves, so a read-modify-write update never strands a VM. + +The web UI exposes both per NIC in the deploy and update dialogs, alongside the +networking mode. Both fields are also on `NetworkingConfig` in the deployment +and update RPCs. A request that +sets only `vhost`/`queues` keeps the node's own networking mode, so tuning does +not force a caller to restate — or be allowed to choose — a backend. `queues` is +rejected above the node's `max_net_queues`; `vhost` is not otherwise restricted, +since it only affects the requesting VM. `GetMeta` reports +`networking.max_queues` so a client can present the real bound. + +The data plane settings are recorded only when a deployment asks for them. +Leave one out and it stays owned by the node, so changing `[cvm.networking]` +later — including setting `vhost = false` to roll the whole node back — still +reaches VMs deployed with some other networking override. + +Naming a backend is different: it pins that NIC's *backend*, resolved at +deployment. Its mode, and the bridge or macvtap parent that names it, are fixed +for the life of the VM, so a later edit to those fields in `[cvm.networking]` +does not move it to another segment. Nothing else is pinned — the MAC prefix, +the user-mode subnet and DHCP start, and the macvtap forwarding mode stay node +settings and are re-read at every launch, so editing them changes every VM's +next boot, including its MAC and therefore its DHCP lease. A request that only +tunes pins nothing at all, including the backend it inherited. + +`GetInfo` reports that configuration back, and both `vmm-cli.py update` and the +web UI read it, change one field, and resend the rest. Two things follow. A +request may name a bridge or macvtap parent the node itself configured even when +the allowlists are empty: leaving the field out already yields exactly that +value, so echoing it grants nothing policy was withholding. And an update may +restate whatever its own VM already pinned, so that moving the node's default +out from under a VM does not leave that VM's configuration unsendable. A NIC +that inherited its backend reports an empty mode, which is the same thing it was +deployed with. + +Neither field reaches the CVM's measurement. The measured VM configuration the +VMM controls covers the OS image, the vCPU and memory counts, several QEMU +layout flags, the *number* of NICs, and `mr_config_id`; the queue count and the +vhost state are not part of it, so retuning a NIC does not change app identity +or require an on-chain update. Adding or removing a NIC does: the NIC count +changes the guest's ACPI tables and therefore RTMR0. + +## Enabling vhost on a node + +Setting `vhost = true` in `[cvm.networking]` is a node-wide behaviour change: +every bridge or macvtap VM that has not pinned its own data plane gets a +different virtio-net device on its next boot — `vhost=on`, `mq=on` with +vCPU-scaled queue pairs, and the matching MSI-X vector count. The device is not +measured, so attestation and app identity are unaffected. Before flipping it: + +1. **Verify `/dev/vhost-net` is accessible to the account QEMU runs under.** + It is `root:kvm 0660` on Debian-family hosts, where adding the account to + the `kvm` group suffices, and `root:root 0600` on several others. If the + account lacks access, QEMU exits at launch and every affected VM stops + restarting. The VMM warns at startup when its own access fails, but it + cannot refuse on that basis — QEMU need not share its credentials. + +2. **Restart `netd` before or together with the VMM.** Every bridge and + macvtap NIC is prepared by `netd`, and the VMM checks that `netd` echoes the + queue count it built. An older `netd` fails that check; the launch is rolled back + and fails with the reason in the VMM log, but the VM does not start until + `netd` is upgraded. + +3. **Roll back by setting `vhost = false`.** The node value reaches every VM + that did not pin `vhost` explicitly, from its next boot; a VM that pinned + `vhost = true` keeps it until updated. + +## What each mode supports + +| Mode | netdev | vhost | queues > 1 | +|---|---|---|---| +| `user` | `user,...` | no backend | not supported | +| `bridge` | `tap,ifname=` via netd | yes | yes | +| `macvtap` | `tap,fd=` / `tap,fds=` | yes | yes | +| `custom` | operator's own string | operator's own string | no, not settable | + +QEMU's `bridge` netdev accepts neither `vhost=` nor `queues=`, and the setuid +`qemu-bridge-helper` behind its `tap` netdev returns exactly one descriptor. So +bridge mode runs on a TAP that `netd` creates: persistent, `multi_queue` when +asked for, and opened once per queue by QEMU. That is true of every bridge NIC, +filtered or not, single-queue or not — see +[bridge-networking.md](bridge-networking.md) for why the host interface has one +owner. `netd` requires the `virsh` binary to be installed even when nothing is +filtered, though it does not require a reachable `libvirtd`. One-shot +`dstack-vmm run` does not manage netd interface lifecycle, so it refuses bridge +and macvtap NICs outside `--dry-run`. `netd` reports back the queue count it +created, and the VMM refuses to launch on a mismatch — a `netd` deployed +separately as a root service can be older than the VMM asking it for +multiqueue, and QEMU would otherwise reject the interface from inside the +per-VM launcher. + +For macvtap, the per-VM launcher opens the `/dev/tapN` character device once +per queue pair and hands QEMU the descriptors as `fds=`. `netd` creates the +interface with matching `numtxqueues`/`numrxqueues`. + +Custom mode owns its whole netdev string, including any `vhost=`/`queues=` +options, and its guest device stays single-queue: the VMM cannot edit that +string, so it has no way to make a multiqueue device line agree with it. For the +same reason `GetInfo` reports no vhost state and no queue count for a custom +NIC, rather than asserting the resolved defaults over a string it never read. A +hand-written multiqueue netdev will not pair with a multiqueue guest device +today. + +Naming a backend that cannot carry vhost or a queue count, and then asking for +one, is refused — the request is yours to correct. Inheriting such a backend is +not, because the node chose it and may choose another tomorrow; the request +reads as off, or as one queue pair, until then. + +## Choosing a queue count + +The default suits bandwidth-bound workloads. Latency-sensitive ones should ask +for fewer: more queues spread receive processing over more vCPUs, and under TDX +a cross-vCPU wakeup costs an IPI and a VM exit. Measured on one 8-vCPU TDX CVM, +changing only the guest's channel count: + +| Queue pairs | Short-connection throughput | +|---|---| +| 1 | 22.3k conn/s | +| 2 | ~20k conn/s | +| 4 | 15–21k conn/s | +| 8 | 6.2–7.7k conn/s | + +The same CVM with 8 queues moved 3.0 Mpps of 64-byte UDP with no loss, against +roughly 600k with one queue. The trade is real in both directions, so a VM +serving many short connections should set `--net-queues 1` and measure. + +A VM with fewer vCPUs than queues leaves the extra pairs idle — `ethtool -l +eth0` reports the smaller number. An explicit over-provision is not rejected at +deployment, because `vmm-cli.py resize` can raise the vCPU count later. + +Queue pairs also cost guest memory — each RX ring keeps 256 page-sized buffers +posted, about 1 MB per queue pair plus per-queue NAPI and socket state — but at +any realistic RAM/vCPU shape this is noise. Pushed to a shape no deployment +uses (1 GB of RAM with 16 vCPUs, so 16 queue pairs by default), sustained load +did produce atomic order-0 page-allocation failures in RX refill +(`try_fill_recv` in the guest log); 2 GB at the same shape ran clean. Since the +queue default follows the vCPU count and a VM with that many vCPUs carries far +more memory in practice, this needs no tuning — it is recorded here so the +symptom is searchable. The TDX bounce-buffer pool is not a constraint either: +the guest kernel sizes swiotlb at 6% of RAM clamped to [64 MB, 1 GB] with no +`swiotlb=` parameter, while peak demand is bounded by ring size at about 2 MB +per queue pair — a deliberately undersized 32 MB pool sustained full +multiqueue line rate with zero `swiotlb buffer is full` events. + +`vectors` is derived, never configured: `2N + 2`, one vector per queue +direction plus config and control. One queue pair emits no `mq=on` or +`vectors=` at all, leaving the guest device line byte for byte identical to the +one before this feature. The `-netdev` half carries `vhost=on|off` either way, +since that is what selects the backend. + +## Requirements + +The account running QEMU must be able to open `/dev/vhost-net`, which is +`root:kvm 0660` on a stock host — add that account to the `kvm` group. The +`vhost_net` module autoloads on first open. + +`GetInfo` reports the data plane each interface actually got, so a bridge NIC +that fell back for want of a helper reads as `vhost: false` rather than +advertising something it is not using. For a VM that is not running there is no +interface to describe, so it reports what the next launch would build instead -- +the same calculation, against the node configuration and manifest as they stand +now, rather than the ones a finished boot ran under. + +If that account lacks access, QEMU exits at startup and the VM never boots — +there is no fallback to the userspace backend at this point, on any QEMU +version (verified on 8.2.2 and 10.2). What the per-VM launcher log shows +depends on the version: QEMU 8.2 prints `warning: tap: open vhost char device +failed: Permission denied` (once per queue) and then dies on `net/net.c:1185: +net_client_init1: Assertion 'nc' failed` — an upstream bug +([qemu#1486](https://gitlab.com/qemu-project/qemu/-/issues/1486)); later +versions exit cleanly with `Could not open '/dev/vhost-net'`. Grep for either. +The VMM does not refuse a launch over this: QEMU need not share the VMM's +credentials, so a refusal based on the VMM's own access would block deployments +the host can run. It warns instead — when the device node is missing outright, +and when the VMM's own open is denied, since QEMU usually does share its +account. + +QEMU does have a *runtime* fallback, at a different failure point: once the +netdev initialized with vhost, a later `vhost_net_start()` failure at guest +driver activation logs `unable to start vhost net: : falling back on +userspace virtio` and keeps the NIC working on the userspace data path. That +path is reachable only after `/dev/vhost-net` was opened successfully at +launch, so an access problem never lands there. If it does fire, it is the one +case where `GetInfo` can overstate the data plane — the interface reports the +vhost state the launch settled while the packets take the userspace path — and +that QEMU log line is the indicator. + +vhost-net works normally in a TDX guest: the virtio rings and buffers live in +shared, unencrypted memory precisely so a host-side backend can reach them. +This is the same mechanism behind `vhost-vsock-pci`, which dstack has always +used. + +On host kernels older than 6.4 the vhost worker is a free-standing kernel +thread: it is attached to the owner's cgroups, so `cpu.max` and cgroup +accounting do apply, but it is outside QEMU's thread group and so invisible to +`top -H` and to anything reading `/proc//task`. Since 6.4 it is a +`vhost_task` inside that thread group and shows up everywhere the VM's other +threads do. diff --git a/docs/normalized-app-compose.md b/docs/normalized-app-compose.md new file mode 100644 index 0000000000..66ccb4c432 --- /dev/null +++ b/docs/normalized-app-compose.md @@ -0,0 +1,245 @@ +# Normalized App Compose + +In the dstack project, the `app-compose.json` file defines application composition and deployment settings. To track changes and ensure data integrity across different environments, dstack needs to generate a deterministic SHA256 compose hash from this file. + +A compose hash is a SHA256 cryptographic hash computed from the `app-compose.json` content. This hash acts as a unique fingerprint for each application composition. When dstack processes the same `app-compose.json` file across different components - some built in Go, others in Python or JavaScript - they must all produce the exact same compose hash. This consistency is critical for dstack's distributed architecture and change detection system. + +The main problem is that standard JSON libraries in different languages often create slightly different output from the same data. Small differences in key order, whitespace, or number formatting lead to different JSON strings. These create different compose hashes, which breaks dstack's integrity checks. + +This document explains the rules for JSON serialization in Go, Python, and JavaScript to achieve deterministic output. Following these rules ensures the same `app-compose.json` file always produces the same SHA256 compose hash across all dstack components. + +## Core Rules for Deterministic JSON + +For dstack to generate consistent SHA256 compose hashes, JSON serialization must follow these strict rules: + +- **Sort Keys**: All keys in JSON objects must be sorted alphabetically +- **Compact Output**: The JSON string must have no extra whitespace +- **Handle Special Values**: NaN and Infinity should be serialized as null +- **UTF-8 Encoding**: Non-ASCII characters should output directly as UTF-8, not as escape sequences + +## Go: encoding/json + +Go's standard library provides JSON encoding and decoding. By default, it creates compact output, but you need to watch key ordering and special value handling. + +**Key Setup:** +- **Key Order**: Go serializes structs by field definition order. For `map[string]interface{}`, Go doesn't guarantee key order. To get sorted keys, convert to a map, extract and sort keys manually, then serialize. Better yet, use structs with fixed field order. +- **Compact Output**: `json.Marshal()` creates compact JSON by default +- **Special Values**: Go serializes NaN and Infinity to null by default +- **UTF-8**: Outputs UTF-8 characters by default + +**Example (Go):** + +```go +package main + +import ( + "encoding/json" + "fmt" + "sort" +) + +// AppComposeData represents the structure of app-compose.json +type AppComposeData struct { + AStatus bool `json:"a_status"` + BNumber int `json:"b_number"` + ID string `json:"id"` + Nested map[string]interface{} `json:"nested"` + SpecialValue *float64 `json:"special_value"` + Text string `json:"text"` + ZItems []int `json:"z_items"` +} + +// CustomMap for custom map serialization +type CustomMap map[string]interface{} + +func (cm CustomMap) MarshalJSON() ([]byte, error) { + keys := make([]string, 0, len(cm)) + for k := range cm { + keys = append(keys, k) + } + sort.Strings(keys) // Sort keys alphabetically + + var buf []byte + buf = append(buf, '{') + for i, k := range keys { + if i > 0 { + buf = append(buf, ',') + } + keyBytes, err := json.Marshal(k) + if err != nil { + return nil, err + } + buf = append(buf, keyBytes...) + buf = append(buf, ':') + valBytes, err := json.Marshal(cm[k]) + if err != nil { + return nil, err + } + buf = append(buf, valBytes...) + } + buf = append(buf, '}') + return buf, nil +} + +func main() { + // Example app-compose.json data + nestedMap := CustomMap{ + "gamma": 3.14, + "alpha": "first", + } + + var nanVal *float64 = nil // Handle NaN as null + + composeData := AppComposeData{ + AStatus: true, + BNumber: 123, + ID: "c73a3a4e-ce71-4c12-a1b7-78be1a2e48e0", + Nested: nestedMap, + SpecialValue: nanVal, + Text: "你好世界", + ZItems: []int{3, 1, 2}, + } + + // Generate deterministic JSON for compose hash + jsonBytes, err := json.Marshal(composeData) + if err != nil { + fmt.Println("Error:", err) + return + } + fmt.Println("Deterministic JSON:", string(jsonBytes)) + + // This JSON string can now be used to generate a compose hash +} +``` + +**Go Notes:** +- **Struct Field Order**: Go serializes structs by field definition order. Arrange struct fields alphabetically for consistency +- **Map Key Order**: Go doesn't guarantee map key order. Use custom `json.Marshaler` interface to sort keys manually +- **NaN/Infinity**: Go serializes these to null by default + +## Python: json.dumps + +Python's `json.dumps` has parameters to achieve deterministic output, but you must set them explicitly. + +**Setup:** +- `sort_keys=True`: Sorts dictionary keys alphabetically +- `separators=(',', ':')`: Creates compact output by removing spaces +- `ensure_ascii=False`: Outputs non-ASCII characters as UTF-8 +- `allow_nan=False`: Disables default NaN/Infinity serialization, handles them via custom function + +**Example (Python):** + +```python +import json +import math + +def handle_nan_inf(obj): + if isinstance(obj, float) and (math.isnan(obj) or math.isinf(obj)): + return None # Convert NaN, Inf, -Inf to None (serializes to null) + raise TypeError(f"Object of type {obj.__class__.__name__} is not JSON serializable") + +# Example app-compose.json data +compose_data = { + "text": "你好世界", + "id": "c73a3a4e-ce71-4c12-a1b7-78be1a2e48e0", + "b_number": 123, + "a_status": True, + "z_items": [3, 1, 2], + "nested": { + "gamma": 3.14, + "alpha": "first" + }, + "special_value": float('nan') +} + +# Generate deterministic JSON for compose hash +deterministic_json = json.dumps( + compose_data, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=False, + allow_nan=False, + default=handle_nan_inf +) + +print("Deterministic JSON:", deterministic_json) +# This JSON string can now be used to generate a compose hash +``` + +## JavaScript: JSON.stringify + +JavaScript's `JSON.stringify` is the hardest for deterministic output because it lacks a built-in sort keys option. Object key order is usually insertion order, but this isn't guaranteed to be alphabetical. + +**Approach:** +- **Sort Object Keys**: Before calling `JSON.stringify`, recursively sort all object keys alphabetically +- **Compact Output**: Call `JSON.stringify` without the space argument +- **Special Values**: Use replacer function to convert NaN and Infinity to null + +**Example (JavaScript):** + +```javascript +/** + * Sorts object keys alphabetically. + * This is crucial for deterministic JSON.stringify in JavaScript. + */ +function sortObjectKeys(obj) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + if (Array.isArray(obj)) { + return obj.map(sortObjectKeys); + } + // Sort object keys and create new object + return Object.keys(obj).sort().reduce((result, key) => { + result[key] = sortObjectKeys(obj[key]); + return result; + }, {}); +} + +// Example app-compose.json data +const composeData = { + text: "你好世界", + id: "c73a3a4e-ce71-4c12-a1b7-78be1a2e48e0", + b_number: 123, + a_status: true, + z_items: [3, 1, 2], + nested: { + gamma: 3.14, + alpha: "first" + }, + special_value: NaN +}; + +// Step 1: Sort object keys +const sortedData = sortObjectKeys(composeData); + +// Step 2: Generate deterministic JSON for compose hash +const deterministicJson = JSON.stringify(sortedData, (key, value) => { + // Convert NaN and Infinity to null + if (typeof value === 'number' && (isNaN(value) || !isFinite(value))) { + return null; + } + return value; +}); + +console.log("Deterministic JSON:", deterministicJson); +// This JSON string can now be used to generate a compose hash +``` + +## Language Comparison + +Here's how each language handles deterministic JSON serialization for compose hash generation: + +| Feature | Go encoding/json | Python json.dumps | JavaScript JSON.stringify | +|:---|:---|:---|:---| +| Key Order | Structs by definition order; maps need custom MarshalJSON | Not guaranteed; must set `sort_keys=True` | Not guaranteed; must sort keys manually | +| Whitespace | Compact by default | Has spaces by default; must set `separators=(',', ':')` | Has indentation by default; must omit space argument | +| NaN/Inf | Serializes to null by default | Defaults to JS equivalent; must set `allow_nan=False` | Serializes to null by default; use replacer function | +| Non-ASCII | Outputs UTF-8 by default | Defaults to escaped; must set `ensure_ascii=False` | Outputs UTF-8 by default | +| Custom Types | Use `json.Marshaler` interface | Use `default` parameter | Use replacer function | + +## Summary + +Getting deterministic JSON serialization across different languages for compose hash generation isn't the default behavior. It needs careful setup. Go works well with compact output and special value handling, but needs custom key sorting for maps. Python and JavaScript both need explicit setup for key sorting and compact output. JavaScript notably requires manual recursive sorting of object keys. + +By following these recommendations, dstack can ensure that the same `app-compose.json` file produces the same SHA256 compose hash across all its Go, Python, and JavaScript components. This provides a reliable foundation for the project's distributed architecture and change detection system. diff --git a/docs/onboarding.md b/docs/onboarding.md new file mode 100644 index 0000000000..c46db76f59 --- /dev/null +++ b/docs/onboarding.md @@ -0,0 +1,337 @@ +# Self-hosted quick onboarding + +Use this guide to get a first dstack app running on one Intel TDX host. The workflow uses `dstackup` for host setup and `dstack` for app deployment: + +```bash +curl -fsSL https://raw.githubusercontent.com/Dstack-TEE/dstack/next/dstack/scripts/install.sh | sh +sudo dstackup install +sudo dstack deploy \ + -n hello-nginx \ + -c /usr/local/share/dstack/examples/hello-nginx/docker-compose.yaml \ + --port 8080:80 +curl http://127.0.0.1:8080/ +``` + +AMD SEV-SNP hosts use the same `dstackup` and `dstack` commands after you +provide a guest image that contains the image digest (`digest.txt`); see +[AMD SEV-SNP Support](./amd-sev-snp.md) for the platform's image, attestation, +and KMS requirements. + +The default onboarding flow uses a published image. To build or customize the +guest OS first, follow [Build the dstack guest OS](./building-guest-os.md), then +install the resulting `dstack-.tar.gz` bundle. + +For multi-node production, Gateway TLS, custom domains, or on-chain governance, use the full [deployment guide](./deployment.md). + +## What this workflow creates + +- User commands under `/usr/local/bin`. +- Host daemon binaries under `/usr/local/libexec/dstack`. +- Static assets and examples under `/usr/local/share/dstack`. +- Generated host config under `/etc/dstack`. +- Host state, KMS keys, VMs, and verified guest images under `/var/lib/dstack`. +- Source and build cache under `/var/cache/dstack`. +- Runtime sockets and process state under `/run/dstack`. +- A localhost-only VMM dashboard on port `9080`. +- A local `dstack-auth` webhook (development, testing and evaluation only) and `dstack-vmm` systemd unit. +- A single KMS CVM unless you pass `--no-kms`. +- A direct host port mapping for your app. + +## Prerequisites + +Run these commands on the self-hosted dstack machine. + +- Root or sudo access. +- A TDX host that satisfies [Hardware enablement](./hardware-enablement.md). +- Outbound HTTPS access to GitHub. + +If the host is not enabled yet, start with [Hardware enablement](./hardware-enablement.md). + +Install the build packages used by the onboarding flow: + +```bash +sudo apt update +sudo apt install -y \ + build-essential \ + ca-certificates \ + curl \ + git \ + libssl-dev \ + pkg-config \ + tar +``` + +Install and start Docker if it is not already available. The default TDX key provider uses Docker. Use your normal Docker installation process, or on Ubuntu: + +```bash +sudo apt install -y docker.io docker-compose-v2 +sudo systemctl enable --now docker +``` + +Install Rust and load Cargo into your shell: + +```bash +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y +. "$HOME/.cargo/env" +``` + +Build and install the `dstackup` bootstrap command: + +```bash +curl -fsSL https://raw.githubusercontent.com/Dstack-TEE/dstack/next/dstack/scripts/install.sh | sh +``` + +The bootstrap installer builds `dstackup` from a temporary source checkout and installs it under `/usr/local/bin`. The `dstackup install` command then builds and installs `dstack`, `dstack-auth`, `dstack-vmm`, `supervisor`, static assets, and host config into the system layout. + +## 1. Install the host stack + +Run: + +```bash +sudo dstackup install +``` + +`dstackup install` auto-detects TDX or AMD SEV-SNP. If no local guest image exists, it downloads the latest unified image from [dstack guest-OS releases](https://github.com/Dstack-TEE/dstack/releases?q=guest-os-v), requires the release SHA-256 digest by default, verifies the tarball, stages the unpack, and only then adopts the image. Current images include NVIDIA support conditionally and work on CPU-only hosts too. Pinned versions below 0.6.0 are read directly from the archived [`meta-dstack` releases](https://github.com/Dstack-TEE/meta-dstack/releases); versions 0.6.0 and later come from this repository. + +On TDX, `dstackup install` starts the SGX key provider automatically from `/usr/local/share/dstack/local-key-provider/build`. To use a different provider, pass one of: + +```bash +sudo dstackup install --key-provider-src /path/to/local-key-provider/build +sudo dstackup install --use-existing-key-provider 127.0.0.1:3443 +``` + +On AMD SEV-SNP, no SGX key provider is needed. The selected guest image must include `digest.txt`; otherwise, `dstackup install` fails before it starts the host units because apps could not be pinned to the measured OS image. + +The normal pull command is sufficient for current CPU and GPU hosts: + +```bash +sudo dstackup image pull +sudo dstackup install +``` + +`dstackup image pull --gpu` remains a compatibility option for older releases that published a separate `dstack-nvidia-*` archive; it falls back to the unified archive when a release has no separate GPU asset. + +If multiple images are present, pass the image name or release version to `--image`, such as `dstack-0.6.0`, legacy `dstack-nvidia-0.5.11`, or `0.6.0`. If the requested release-shaped image is not local, `dstackup install` downloads it. + +When install succeeds, it prints the dashboard URL, the KMS address, and a `dstack deploy` command template. The default dashboard URL is: + +```text +http://127.0.0.1:9080 +``` + +If you connect from your laptop, open an SSH tunnel first: + +```bash +ssh -L 9080:127.0.0.1:9080 @ +``` + +Then open `http://127.0.0.1:9080` locally. `dstackup install --expose` is intentionally disabled until the remote TLS and token transport exists. + +## 2. Deploy a first app + +Deploy the checked-in nginx example: + +```bash +sudo dstack deploy \ + -n hello-nginx \ + -c /usr/local/share/dstack/examples/hello-nginx/docker-compose.yaml \ + --port 8080:80 +``` + +The deploy command: + +- converts the Docker Compose file into a dstack app-compose manifest, +- computes the compose hash and app ID, +- uses the VMM endpoint, guest image, and auth allowlist from `dstackup install`, +- registers the compose hash in the single-node auth allowlist, +- creates the CVM with the default app resources of 2 vCPU, 2048 MB memory, and 20 GB disk, and +- maps `http://127.0.0.1:8080/` on the host to port `80` in the CVM. + +Pass `--vcpu`, `--memory`, or `--disk` to change the app resources before you deploy. + +The `--port 8080:80` mapping means `host_port:vm_port` and uses TCP on `127.0.0.1`. The full accepted forms are `vm`, `host:vm`, `proto:host:vm`, and `proto:addr:host:vm`, each optionally suffixed with `@` to name which NIC the traffic enters through (a single-NIC VM never needs it). Use `tcp` or `udp` for `proto`. Fixed host and VM ports must be between 1 and 65535. If you omit the host port, or use `auto` or `0`, `dstack` picks a free localhost port and prints the selected mapping after deploy. + +Open the app from the host: + +```bash +curl http://127.0.0.1:8080/ +``` + +If you are connecting from your laptop, tunnel the app port too: + +```bash +ssh -L 8080:127.0.0.1:8080 @ +``` + +## Common operations + +Check deployed apps: + +```bash +dstack apps +``` + +Show recent app logs: + +```bash +dstack logs +``` + +`dstack apps` and `dstack logs` read the VMM endpoint from the local `dstackup install` state, so they work with the default localhost dashboard endpoint. For a custom prefix, pass the same `--prefix` you used for install. + +Remove a local image: + +```bash +sudo dstackup image rm +``` + +List local images: + +```bash +sudo dstackup image list +``` + +Tear down the host units and KMS CVM: + +```bash +sudo dstackup destroy +``` + +Add `--purge` only when you also want to delete generated config, state, cached source, runtime files, and KMS keys for that install. For a custom `--prefix`, purge also removes dstack-owned installed files under that prefix. + +## Install with a custom prefix + +Use `--prefix` when you want a second isolated install on the same host. A custom prefix relocates the install layout under that directory: + +| Purpose | Example path for `--prefix /opt/dstack-test` | +| --- | --- | +| User commands | `/opt/dstack-test/bin` | +| Host daemons | `/opt/dstack-test/libexec/dstack` | +| Static assets | `/opt/dstack-test/share/dstack` | +| Config | `/opt/dstack-test/etc/dstack` | +| State and images | `/opt/dstack-test/var/lib/dstack` | +| Source and build cache | `/opt/dstack-test/var/cache/dstack` | +| Runtime files | `/opt/dstack-test/run/dstack` | + +Install `dstackup` into the prefix, then use the same prefix for `dstackup` and `dstack`: + +```bash +curl -fsSL https://raw.githubusercontent.com/Dstack-TEE/dstack/next/dstack/scripts/install.sh | sh -s -- --prefix /opt/dstack-test + +sudo /opt/dstack-test/bin/dstackup install \ + --prefix /opt/dstack-test \ + --dashboard-port 19080 \ + --auth-port 18001 \ + --host-api-port 10001 + +sudo /opt/dstack-test/bin/dstack \ + --prefix /opt/dstack-test \ + deploy \ + -n hello-nginx \ + -c /opt/dstack-test/share/dstack/examples/hello-nginx/docker-compose.yaml \ + --port 18080:80 +``` + +For a custom prefix, `dstackup` derives distinct systemd unit names from the prefix unless you pass `--instance`. You still need distinct TCP and vsock ports for each running install. + +Remove a custom-prefix install with the same prefix: + +```bash +sudo /opt/dstack-test/bin/dstackup destroy --prefix /opt/dstack-test --purge +``` + +## Security boundaries + +This onboarding path is designed for one operator on one host. + +- The VMM dashboard and management API bind to `127.0.0.1` by default. Use SSH tunneling for remote access. +- `dstackup install` pins the app OS image hash from the selected guest image (`digest.txt` on all platforms). If pinning is enabled and the digest cannot be read, install fails. +- `dstack deploy` registers the app compose hash in the local auth allowlist from `dstackup install`. Without that allowlist update, a KMS-mode app can boot but will not receive keys. +- Gateway is not part of this flow. Apps are exposed through direct host port mappings. + +Use the [deployment guide](./deployment.md) when you need domain routing, Gateway certificates, on-chain authorization, KMS replicas, or multi-node operation. + +## Troubleshooting + +### Image download fails + +`dstackup install` downloads the latest CPU image when KMS mode needs an image and none exists locally. If the download fails, check network access to GitHub and the dstack guest-OS release: + +```bash +sudo dstackup image pull +``` + +If a release does not publish a SHA-256 digest, `dstackup image pull` and `dstackup install` fail before unpacking it. Use `--insecure` only when you intentionally accept an unverified image download. + +If you use a custom prefix or image directory, pass the same `--prefix` or `--image-path` to `install` and `image` commands. + +### Missing `digest.txt` + +All platforms pin apps with `digest.txt`. If the selected image does not contain `digest.txt`, install fails with: + +```text +no os-image pin: could not read digest.txt +``` + +Use `--image` or `--image-path` with an image that contains `digest.txt`. Do not use `--allow-unpinned-image` for onboarding unless you intentionally want apps to boot without OS-image pinning. + +### No key provider on TDX + +TDX uses an SGX-backed key provider for KMS sealing. `dstackup install` uses the installed key provider assets by default. To override that, pass one of: + +```bash +sudo dstackup install --use-existing-key-provider 127.0.0.1:3443 +sudo dstackup install --key-provider-src /path/to/local-key-provider/build +``` + +AMD SEV-SNP does not use this key provider. + +### Port already in use + +Move the conflicting port explicitly: + +```bash +sudo dstackup install --dashboard-port 19080 --auth-port 18001 --host-api-port 10001 +``` + +For app ports, change the `--port` mapping: + +```bash +sudo dstack deploy \ + -c /usr/local/share/dstack/examples/hello-nginx/docker-compose.yaml \ + --port 18080:80 +``` + +### KMS bootstrap does not finish + +Check the VMM service and the KMS CVM logs: + +```bash +sudo journalctl -u dstack-vmm -n 200 --no-pager +dstack logs +``` + +The KMS VM ID is printed by `dstackup install` when it creates or reuses the KMS CVM. + +### Upgrading the local KMS to root epochs + +Upgrade the bundled `dstack-auth` together with the KMS. Before normal key release, +set `kmsContractAddr` in the host's `auth-allowlist.json` to the KMS's attested app ID +and register the verified bootstrap CA/k256 public keys in `rootEpochs` (epoch zero). +Use the bootstrap evidence to verify these keys; do not trust an unauthenticated +metadata response. Set `currentRootEpoch` to the active registered epoch (initially +zero). See [root registration and rotation](deployment.md#rotating-kms-root-keys). +The local installer does not register these keys automatically; an older installed +KMS can continue using the legacy boot routes while this migration is prepared. + +The Rust backend implements `/authorizeKms` and `/authorizeApp` with the same +registered-root requirement as the other backends. Missing registration denies key +release, and invalid epoch configuration returns HTTP 503. Legacy `/bootAuth/*` +routes remain available for bootstrap. Local compose/device allowlists apply to +all permitted historical roots; they are not the on-chain per-epoch matrices. + +Application entries also accept `currentAppEpoch` (default zero). Keep this value +monotonic, restart the application after advancing it, and retain permissions for +historical keys needed during migration. `/app/:appId` exposes the current app +epoch; legacy app boot authorization is denied once it is nonzero. The Rust +backend uses the same normalized app ID lookup for policy and epoch selection. diff --git a/docs/onchain-governance.md b/docs/onchain-governance.md new file mode 100644 index 0000000000..d9ff879a36 --- /dev/null +++ b/docs/onchain-governance.md @@ -0,0 +1,228 @@ +# On-Chain Governance + +> **This guide is for self-hosted deployments** on your own TDX hardware. For cloud deployments, see [Quickstart](./quickstart.md). + +This guide covers setting up on-chain governance for dstack using smart contracts on Ethereum. + +## Overview + +On-chain governance adds: +- **Smart contract-based authorization**: App registration and whitelisting managed by smart contracts +- **Decentralized trust**: No single operator controls keys +- **Transparent policies**: Anyone can verify authorization rules on-chain + +## Prerequisites + +- Production dstack deployment with KMS and Gateway as CVMs (see [Deployment Guide](./deployment.md)) +- Ethereum wallet with funds on Sepolia testnet (or your target network) +- [Foundry](https://book.getfoundry.sh/getting-started/installation) installed + +## Deploy DstackKms Contract + +```bash +cd dstack/kms/auth-eth +forge install # Install Foundry dependencies (git submodules) + +# Deploy contracts (deploys both DstackApp implementation and DstackKms proxy) +PRIVATE_KEY= forge script script/Deploy.s.sol:DeployScript \ + --broadcast --rpc-url https://eth-sepolia.g.alchemy.com/v2/ +``` + +Sample output: + +``` +Deploying with account: 0x... +DstackApp implementation deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3 +DstackKms implementation deployed to: 0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512 +DstackKms proxy deployed to: 0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0 +``` + +Note the proxy address (e.g., `0x9fE4...`). + +Set environment variables for subsequent commands: + +```bash +export KMS_CONTRACT_ADDR="" +export PRIVATE_KEY="" +export RPC_URL="https://eth-sepolia.g.alchemy.com/v2/" +``` + +## Configure KMS for On-Chain Auth + +The KMS CVM includes an auth-api service, [auth-eth](../dstack/kms/auth-eth/), that connects to your DstackKms contract. Configure it via environment variables in the KMS CVM: + +```bash +KMS_CONTRACT_ADDR= +ETH_RPC_URL= +ETH_CHAIN_ID= # optional, rejects decisions from another chain +ETH_BLOCK_TAG=finalized # latest, safe or finalized (default) +``` + +The auth-api validates boot requests against the smart contract. See [Deployment Guide](./deployment.md#2-deploy-kms-as-cvm) for complete setup instructions. + +## Whitelist OS Image + +```bash +OS_IMAGE_HASH=0x ROOT_EPOCH=0 \ + forge script script/Manage.s.sol:AddOsImage --broadcast --rpc-url $RPC_URL +``` + +Output: `Added OS image hash: 0x...` + +The `os_image_hash` is in the `digest.txt` file from the guest OS image build (see [Building Guest Images](./deployment.md#building-guest-images)). + +## Register Gateway App + +```bash +# Create a new app with allowAnyDevice=true +ALLOW_ANY_DEVICE=true \ + forge script script/Manage.s.sol:DeployApp --broadcast --rpc-url $RPC_URL +``` + +Sample output: + +``` +Deployed new app at: 0x75537828f2ce51be7289709686A69CbFDbB714F1 + Owner: 0x... + Allow any device: true +``` + +Note the App ID (deployed app address) from the output. + +Set it as the gateway app: + +```bash +GATEWAY_APP_ID= \ + forge script script/Manage.s.sol:SetGatewayAppId --broadcast --rpc-url $RPC_URL +``` + +Output: `Set gateway app ID: ` + +To trust more than one gateway (for example during a gateway migration), set the value to several app IDs joined by commas, e.g. `,`. A CVM accepts a gateway whose certificate carries any app ID contained in this string. + +Add the gateway's compose hash to the whitelist. To compute the compose hash: + +```bash +sha256sum /path/to/gateway-compose.json | awk '{print "0x"$1}' +``` + +Then add it: + +```bash +APP_CONTRACT_ADDR= COMPOSE_HASH= APP_EPOCH=0 \ + forge script script/Manage.s.sol:AddComposeHash --broadcast --rpc-url $RPC_URL +``` + +Output: `Added compose hash: 0x...` + +## Register Apps On-Chain + +For each app you want to deploy: + +### Create App + +```bash +ALLOW_ANY_DEVICE=true \ + forge script script/Manage.s.sol:DeployApp --broadcast --rpc-url $RPC_URL +``` + +Note the App ID from the output. + +### Add Compose Hash + +Compute your app's compose hash: + +```bash +sha256sum /path/to/your-app-compose.json | awk '{print "0x"$1}' +``` + +Then add it: + +```bash +APP_CONTRACT_ADDR= COMPOSE_HASH= APP_EPOCH=0 \ + forge script script/Manage.s.sol:AddComposeHash --broadcast --rpc-url $RPC_URL +``` + +### Deploy via VMM + +Use the App ID when deploying through the VMM dashboard or [VMM CLI](./vmm-cli-user-guide.md). + +## Smart Contract Reference + +### DstackKms (Main Contract) + +The central governance contract that manages OS image whitelisting, app registration, and KMS authorization. + +| Function | Description | +|----------|-------------| +| `addOsImageHashAtEpochs(uint256,uint256,bytes32)` | Whitelist an OS image hash in a range of root epochs | +| `removeOsImageHashAtEpochs(uint256,uint256,bytes32)` | Remove an OS image from a range of root epochs; `0` through the latest revokes it | +| `setGatewayAppId(string)` | Set the trusted Gateway app ID(s) | +| `setAllowAnyTeeVariant(bool)` / `setAllowedTeeVariants(string[])` | Allow KMS instances and apps on any TEE platform, or only the listed ones, at every root epoch | +| `setSevSnpTcbRequirements(string)` | Publish the minimum TCB each CPU must meet for an SEV-SNP TCB to report `UpToDate`, as a JSON list (see [AMD SEV-SNP](./amd-sev-snp.md)). While empty, a KMS judges a CPU only against its own list, and refuses one neither lists | +| `registerApp(address)` | Register an app contract | +| `deployAndRegisterApp(...)` | Deploy and register app in one transaction | +| `isAppAllowed(AppBootInfo)` | Check if an app is allowed to boot | +| `isKmsAllowed(AppBootInfo)` | Check if KMS is allowed to boot | + +### DstackApp (Per-App Contract) + +Each app has its own contract controlling which compose hashes and devices are allowed, +per app epoch. Every setter names the app epoch rows it writes: one epoch, or a range up +to the next epoch. Removing a value from rows `0` through the current epoch revokes it. + +| Function | Description | +|----------|-------------| +| `addComposeHashAtEpoch(uint256,bytes32)` / `addComposeHashAtEpochs(uint256,uint256,bytes32)` | Whitelist a compose hash in one app epoch or a range | +| `removeComposeHashAtEpoch(uint256,bytes32)` / `removeComposeHashAtEpochs(uint256,uint256,bytes32)` | Remove a compose hash from one app epoch or a range | +| `addDeviceAtEpoch(uint256,bytes32)` / `addDeviceAtEpochs(uint256,uint256,bytes32)` | Whitelist a device ID | +| `removeDeviceAtEpoch(uint256,bytes32)` / `removeDeviceAtEpochs(uint256,uint256,bytes32)` | Remove a device | +| `setAllowAnyDevice(bool)` | Allow any device to run this app, at every app epoch | +| `setAllowAnyTeeVariant(bool)` / `setAllowedTeeVariants(string[])` | Allow any TEE platform, or only the listed ones (e.g. `dstack-tdx`), at every app epoch. Set the list before restricting: a restricted empty list refuses every platform | +| `currentAppEpoch()` | The app epoch new keys are derived for | +| `isAppAllowed(AppBootInfo)` | Check if app can boot with given config (app epoch 0 only) | +| `disableUpgrades()` | Permanently disable contract upgrades | + +#### Apps deployed before app epochs + +App contracts deployed from dstack 0.6.x or earlier, and not upgraded since, have only +app epoch 0 and the epoch-less setters `addComposeHash(bytes32)`, +`removeComposeHash(bytes32)`, `addDevice(bytes32)`, `removeDevice(bytes32)` and +`setAllowAnyDevice(bool)`. They keep working with an upgraded `DstackKms` and KMS, +which authorize them for app epoch 0. Tell the two kinds apart by ERC-165 interface ID: + +```bash +cast call "supportsInterface(bytes4)(bool)" 0x8c0524c4 --rpc-url $RPC_URL # IAppEpochManagement: epoch setters +cast call "supportsInterface(bytes4)(bool)" 0x8fd37527 --rpc-url $RPC_URL # IAppAuthBasicManagement: epoch-less setters +``` + +The `Manage.s.sol` app scripts check this themselves: on an older app they call the +epoch-less setter and accept only `APP_EPOCH=0` or no epoch; on a current app they +require `APP_EPOCH`, or `FROM_APP_EPOCH` and `TO_APP_EPOCH`. `SetAllowAnyDevice` takes +no epoch on either kind. Upgrading an older app to the current `DstackApp` keeps its +compose hashes and devices as app epoch 0, and its `allowAnyDevice` for every epoch. + +### AppBootInfo Structure + +Both `isAppAllowed` and `isKmsAllowed` take an `AppBootInfo` struct: + +```solidity +struct AppBootInfo { + address appId; // Unique app identifier (contract address) + bytes32 composeHash; // Hash of docker-compose configuration + address instanceId; // Unique instance identifier + bytes32 deviceId; // Hardware device identifier + bytes32 mrAggregated; // Aggregated measurement register + bytes32 mrSystem; // System measurement register + bytes32 osImageHash; // OS image hash + string tcbStatus; // TCB status (e.g., "UpToDate") + string[] advisoryIds; // Security advisory IDs +} +``` + +Source: [`dstack/kms/auth-eth/contracts/`](../dstack/kms/auth-eth/contracts/) + +## See Also + +- [Deployment Guide](./deployment.md) - Setting up dstack infrastructure +- [Security Best Practices](./security/security-best-practices.md) diff --git a/docs/passt-networking.md b/docs/passt-networking.md new file mode 100644 index 0000000000..e985d66e6a --- /dev/null +++ b/docs/passt-networking.md @@ -0,0 +1,72 @@ +# passt networking + +[passt](https://passt.top/) gives a CVM outbound connectivity and published +host ports without any privileged host setup, like user mode, but through +passt's network stack instead of QEMU's built-in slirp. Install the `passt` +package on the host before enabling it. + +## Configuration + +```toml +[cvm] +allowed_network_modes = ["user", "bridge", "passt"] +# Empty finds `passt` in PATH at startup. +passt_path = "" + +[cvm.networking] +mode = "passt" +address = "10.0.2.10" +netmask = "255.255.255.0" +gateway = "10.0.2.2" +dns = ["1.1.1.1", "1.0.0.1"] +no_map_gw = true +ipv4_only = true +``` + +The `[cvm.networking]` fields map to the passt options of the same name +(`interface`, `address`, `netmask`, `gateway`, `dns`, `map_host_loopback`, +`map_guest_addr`, `no_map_gw`, `ipv4_only`); an empty value leaves passt's own +default in place. These are node settings: a deployment RPC may pick `passt` +as a NIC's mode but cannot change them. passt has no vhost data plane and runs +a single queue pair, so `vhost` and `queues` do not apply. + +Keep `no_map_gw = true` (or `map_host_loopback = "none"` on passt releases +that support it). Otherwise the guest reaches services bound to the host's +loopback interface through the gateway address. + +## Port mappings + +A passt NIC publishes `port_map` entries the way a user-mode NIC does. An +unpinned mapping goes to the first user-mode or passt NIC; a mapping pinned +with `nic_index` must name one of those. + +## Several CVMs on one host + +Upstream passt keeps a guest's UDP source port on the host side, and binds it +with `SO_REUSEADDR`. When two CVMs send from the same source port to the same +peer, for example WireGuard clients with a fixed listen port talking to one +gateway, their host sockets are identical and the kernel delivers every reply +to one of them. One CVM loses its replies and the other receives both. + +Run a passt build that lets the kernel pick the host source port for guest +UDP flows (for example the `dstack` branch of +) and point `passt_path` at it. On Ubuntu, +a passt outside `/usr/bin/passt` also needs an AppArmor profile of its own: +unconfined programs may not create the user namespaces passt sandboxes itself +in (`kernel.apparmor_restrict_unprivileged_userns`). Build that profile from +the policy shipped with the same passt source (`contrib/apparmor`), since +newer passt releases need rules older distribution policies lack. + +## Process lifecycle + +Every passt NIC runs its own passt process, started by the VM's +`vm-launcher` before QEMU and stopped with it. The launcher connects the two +over a socketpair (`passt --fd`), so no socket file is created and the +AppArmor profile Ubuntu ships for passt does not get in the way. passt runs +with `--quiet`, so only its warnings and errors reach the VM's `stderr.log`: +under that profile passt cannot reach syslog once sandboxed, and each +informational message would otherwise log a "Failed to send ... to syslog" +line instead. + +It is not a separate supervisor process, so stopping or removing a VM cannot +leave a passt process behind. diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000000..e76eb1cf8e --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,270 @@ +# Quickstart + +Deploy your first confidential workload on GCP (or AWS EC2 NitroTPM) in under +10 minutes. + +## Prerequisites + +**GCP** +- GCP account with Confidential VM quota (Intel TDX) +- `gcloud` CLI installed and authenticated + +**AWS** (optional) +- AWS account with EC2 and EBS Direct snapshot permissions +- `aws` CLI installed and authenticated + +The following IAM policy covers image creation, deployment, status/log access, +start/stop, replacement, and removal performed by `dstack-cloud`: + +```json +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "ebs:StartSnapshot", + "ebs:PutSnapshotBlock", + "ebs:CompleteSnapshot" + ], + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "ec2:CreateTags", + "ec2:DeleteSnapshot", + "ec2:DescribeImages", + "ec2:DescribeInstances", + "ec2:DescribeSnapshots", + "ec2:GetConsoleOutput", + "ec2:RegisterImage", + "ec2:RunInstances", + "ec2:StartInstances", + "ec2:StopInstances", + "ec2:TerminateInstances" + ], + "Resource": "*" + } + ] +} +``` + +If `aws_config.iam_instance_profile` is set, also grant `iam:PassRole` for that +specific role. `iam:PassRole` is not required for EBS Direct or for instances +launched without an instance profile. Creating a VPC, subnet, or security group +is outside `dstack-cloud`; supply existing IDs in `aws_config` and grant their +management permissions separately only when needed. + +## Install the CLI + +Download the `dstack-cloud` CLI: + +```bash +# Clone the repository (temporary until packaged release) +git clone https://github.com/Dstack-TEE/dstack.git +export PATH="$PATH:$(pwd)/dstack/scripts/bin" +``` + +Verify the installation: + +```bash +dstack-cloud --help +``` + +## Configure + +Set up your cloud credentials: + +```bash +dstack-cloud config-edit +``` + +This opens an editor with the global configuration file. For GCP, configure: + +```json +{ + "gcp": { + "project": "your-gcp-project-id", + "zone": "us-central1-a" + }, + "aws": { + "region": "us-east-1" + } +} +``` + +For AWS, `dstack-cloud` writes the local boot, shared, and labeled-data RAW disks +directly to EBS snapshots in 512-KiB checksummed blocks. It does not require an +S3 bucket, a `vmimport` service role, or `iam:PassRole`. + +## Create a Project + +```bash +# GCP (default) +dstack-cloud new my-app +cd my-app + +# or AWS NitroTPM +dstack-cloud new my-aws-app --platform aws --region us-east-1 +cd my-aws-app +``` + +This creates a project directory with: + +``` +my-app/ +├── app.json # Application configuration +├── docker-compose.yaml # Your container definition +├── .env # Environment variables +└── prelaunch.sh # Pre-launch script (optional) +``` + +## Define Your Workload + +Edit `docker-compose.yaml` with your application: + +```yaml +services: + web: + image: nginx:latest + ports: + - "8080:80" +``` + +For AI workloads with GPU: + +```yaml +services: + vllm: + image: vllm/vllm-openai:latest + runtime: nvidia + command: --model Qwen/Qwen2.5-7B-Instruct + ports: + - "8000:8000" +``` + +## Add Secrets (Optional) + +Add sensitive environment variables to `.env`: + +```bash +API_KEY=your-secret-key +DATABASE_URL=postgres://... +``` + +These are encrypted before leaving your machine and only decrypted inside the TEE. + +## Deploy + +Deploy to your cloud provider: + +```bash +# AWS without a preconfigured aws_config.ami_id needs the local UKI package first: +# dstack-cloud pull +dstack-cloud deploy +``` + +The CLI will: +1. Build and push your container configuration +2. Create a Confidential VM +3. Boot the dstack guest OS +4. Start your containers + +## Check Status + +Monitor your deployment: + +```bash +# Check deployment status +dstack-cloud status + +# View console logs +dstack-cloud logs + +# Follow logs in real-time +dstack-cloud logs --follow +``` + +## Configure Firewall + +Allow traffic to your application: + +```bash +# Allow HTTPS traffic +dstack-cloud fw allow 443 + +# Allow your app port +dstack-cloud fw allow 8080 + +# List firewall rules +dstack-cloud fw list +``` + +## Access Your App + +Once deployed, access your application via the assigned endpoint. The `dstack-cloud status` command shows the public URL. + +For apps with TLS: +``` +https://. +``` + +For specific ports: +``` +https://-8080. +``` + +## Verify Attestation + +Users can verify your deployment is running in a genuine TEE: + +```bash +# Get attestation quote from your app +curl https:///attestation + +# Verify with dstack-verifier +dstack-verifier verify +``` + +See the [Verification Guide](./verification.md) for details. + +## Manage Deployments + +```bash +# List all deployments +dstack-cloud list + +# Stop a deployment +dstack-cloud stop + +# Start a stopped deployment +dstack-cloud start + +# Remove a deployment completely +dstack-cloud remove +``` + +## Next Steps + +- [Usage Guide](./usage.md) - Detailed deployment and management +- [Confidential AI](./confidential-ai.md) - Run AI workloads with hardware privacy +- [GCP Attestation](./attestation-gcp.md) - How TDX + TPM attestation works +- [AWS Nitro Attestation](./attestation-nitro-enclave.md) - How NSM attestation works +- [Security Model](./security/security-model.md) - Understand the trust boundaries + +## Troubleshooting + +**Deployment stuck at "Creating VM":** +- Check your cloud quota for Confidential VMs +- Verify your credentials with `gcloud auth list` + +**Container not starting:** +- Check logs with `dstack-cloud logs` +- Verify your docker-compose.yaml syntax +- Ensure images are accessible from the cloud region + +**Cannot access application:** +- Check firewall rules with `dstack-cloud fw list` +- Verify the port mapping in docker-compose.yaml +- Check if the container is healthy in the logs diff --git a/docs/rc-testing-runbook.md b/docs/rc-testing-runbook.md new file mode 100644 index 0000000000..afa9c6aa95 --- /dev/null +++ b/docs/rc-testing-runbook.md @@ -0,0 +1,600 @@ +# Release-candidate testing runbook + +What to do, in order, to exercise a dstack release candidate on real TEE +hardware — and the specific things that cost time the last round, so they cost +nothing the next one. + +Written after testing 0.6.0-rc0 on an Intel TDX host and an AMD SEV-SNP host. +Assumes fresh machines: nothing here depends on state left behind by that run. + +--- + +## 1. Confirm the host can actually do what you think + +Get this wrong and you will scope the whole test around a capability you have, +or skip one you don't. + +### Intel TDX host + +```bash +cat /sys/module/kvm_intel/parameters/tdx # expect: Y +grep -o -m1 tdx_host_platform /proc/cpuinfo # expect: tdx_host_platform +systemctl is-active qgsd pccs # expect: active active +``` + +**`/dev/tdx_guest` does not exist on a TDX host and its absence means nothing.** +That device is the *guest*-side attestation interface; it appears inside a TD, +not on the machine running them. Checking for it will tell you a perfectly good +TDX host has no TDX. Use the KVM module parameter and the CPU flag. + +`qgsd` is what turns a TD's attestation request into a signed quote, and `pccs` +caches the Intel collateral used to verify it. Without both, CVMs boot but +cannot obtain keys. + +### AMD SEV-SNP host + +```bash +cat /sys/module/kvm_amd/parameters/sev_snp # expect: Y +grep -o -m1 sev_snp /proc/cpuinfo # expect: sev_snp +ls -l /dev/sev # must exist AND be accessible +qemu-system-x86_64 -object help | grep sev-snp-guest +lsmod | grep -E '^vhost_vsock|vmw_vsock_vmci' +``` + +Three host-level problems each blocked us for a while: + +- **`vhost_vsock` not loaded.** The VMM binds its host API on vsock CID 2 and + fails with `Cannot assign requested address (os error 99)`. Fix: `sudo modprobe + vhost_vsock`. Does not survive reboot — add `/etc/modules-load.d/` to persist. + +- **VMware's vsock transport hijacking the stack.** If `vmw_vsock_vmci_transport` + is loaded (it often is, by default), it claims the vsock transport and CID 2 + binding still fails even with `vhost_vsock` present. Fix: `sudo modprobe -r + vmw_vsock_vmci_transport vmw_vmci`. It comes back on reboot — blacklist to + persist. This one is easy to misdiagnose as a dstack bug. + +- **`/dev/sev` is `root:root 0600` out of the box** and your user is probably not + in `kvm`. QEMU then fails with `Could not access KVM kernel module: Permission + denied`. Fix: `sudo usermod -aG kvm $USER` and `sudo chown root:kvm /dev/sev && + sudo chmod 660 /dev/sev`. The chmod does not survive reboot; a udev rule does. + +**After fixing group membership, restart the supervisor.** `dstack-vmm` starts +`supervisor` detached, and a supervisor started before the `usermod` keeps the old +group set. QEMU is forked from it, so it still cannot open `/dev/kvm` even though +your shell can. Symptom: `id` shows `kvm`, QEMU still says permission denied. +Check with `grep ^Groups /proc/$(pgrep -f bin/supervisor)/status`. + +### QEMU version + +dstack computes measurements against an ACPI compatibility profile keyed on the +QEMU major version (`dstack/crates/qemu-acpi/src/profile.rs`). 8.x, 9.x and 10.x +are all mapped. Check the version resolves to a supported profile *before* +installing anything, or you will build an environment that cannot produce correct +measurements. + +--- + +## 2. Pick your disks deliberately + +Check the mount that will actually hold the data, not `/`: + +```bash +df -h /home ~/.dstack /var/lib/docker +``` + +On one host `/` had 12 GB free while `/home` sat on a 7 TB array. Looking only at +`/` produced a wrong "we are too tight on disk to use the documented `--disk 50G`" +conclusion and a plan built around shrinking things unnecessarily. + +Keep the VMM's `run_path`, `temp_dir` and the image directory on the large +volume. CVM disks and temp files land there, and `/tmp` on a small root +filesystem will fill up mid-test. + +--- + +## 3. Two traps that can reach outside the test + +**`~/.dstack-vmm/config.json` may point `vmm-cli.py` at a production VMM.** It is +the CLI's default `--url`. On both machines used last time it pointed at a live +deployment with credentials, so any `deploy` that omitted `--url` would have +landed there. **Pass `--url http://127.0.0.1:` on every single invocation.** + +**Component tags publish to GHCR.** `kms-v*`, `gateway-v*`, `verifier-v*` +and friends trigger release workflows that push to `ghcr.io/dstack-tee` and cut +GitHub releases. If you only want images in a private registry, build locally and +push by hand — do not push those tags. + +--- + +## 4. Cutting the release + +- Version lives in **four** places with no tool keeping them in sync: + `dstack/Cargo.toml` (`workspace.package.version`), `os/mkosi/versions.env` + (`DSTACK_VERSION`), `os/mkosi/mkosi.conf` (`ImageVersion`), and + `os/yocto/.../dstack.conf` (`DISTRO_VERSION`). Regenerate `Cargo.lock` after. + Only the first two are cross-checked (by `os/mkosi/tests/acceptance.sh`); the + Yocto one is checked by nothing. +- **Commit messages must be conventional commits** — `prek.toml` enforces it at + commit-msg stage. The historical `Bump version to X` style now fails. +- `release/**` branches are protected against **deletion and non-fast-forward**. + Rebase-and-force will be rejected. Merge instead. This also means the branch + name is claimed permanently once pushed. +- **The container Dockerfiles clone from GitHub and check out `DSTACK_REV`** — + they do not use your working tree. Push the commit before building images, or + you will build something other than what you are testing. +- Pre-run the release job's own validation locally before tagging: + + ```bash + TAG=mkosi-os-v + echo "$TAG" | grep -Eq '^mkosi-os-v[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.-]+)?$' + source os/mkosi/versions.env && [ "${TAG#mkosi-os-v}" = "$DSTACK_VERSION" ] + ``` + + The release job also requires `metadata.json`'s `git_revision` to equal the + tagged commit and rejects a `-modified` suffix, so the tag must sit on the exact + commit that was built from a clean tree. + +--- + +## 5. Bring-up order + +KMS first, then gateway, then the app. Each needs the previous one's identity. + +1. **VMM.** Copy `dstack/vmm/vmm.toml` and edit: `address` **and** `port` (the + `check-config` subcommand requires both at top level), `run_path`, `temp_dir`, + `[image] path` (it is commented out by default), `platform = "tdx"` or + `"amd-sev-snp"`, a `cid_start` that avoids running VMs, `[supervisor]` paths, + and `[cvm.port_mapping]` — **enabled, with a range covering every port you + intend to map.** A port outside the range fails the deploy with `Port mapping + is not allowed for tcp:`. Validate with `dstack-vmm -c + check-config` before starting. + +2. **KMS as a CVM** with `--local-key-provider` (needs a + gramine-sealing-key-provider on the host, default `127.0.0.1:3443`). The + simplest authorization that releases keys without a chain is + `[core.auth_api] type = "dev"` with `gateway_app_id = "any"` — no extra + containers, unlike the on-chain compose, which runs auth-eth next to the KMS + and needs an Ethereum RPC endpoint. The KMS refuses to start without a + key handover path, dev auth included: give it `[listeners.admin]` with TLS + (`key`, `certs`) and an `auth_token_hash`, or set + `core.onboard.public_key_handover = true`. + +3. **Gateway as a CVM** with `--kms`. Internal ports are RPC 8000, admin 8001, + WireGuard 51820/udp, proxy 443. + +4. **App CVM** with `--kms --gateway`. + +### Certificate identity across hosts + +If CVMs on more than one machine will talk to the KMS, give it a DNS name rather +than an IP. The RPC certificate's only SAN is `auto_bootstrap_domain`, and a +local CVM dialing `10.0.2.2` while a remote one dials the public IP cannot both +match. A wildcard A record covering `kms.` and `gw.` solves it in +one step. + +### ACME is configured at runtime, not in a file + +In 0.6.0 certbot config lives in the gateway's KvStore, reached through the admin +API — `Admin.SetCertbotConfig`, `Admin.CreateDnsCredential`, +`Admin.AddZtDomain`. The `CF_API_TOKEN` and `ACME_STAGING` variables in +`gateway/dstack-app/deploy-to-vmm.sh` are **vestigial and unused**; setting them +does nothing. + +**Set `acme_url` to staging explicitly.** The default is Let's Encrypt +*production*, and the rate limits there are unforgiving of a test loop: + +``` +https://acme-staging-v02.api.letsencrypt.org/directory +``` + +`AddZtDomain` kicks off issuance asynchronously and takes a lock. A subsequent +explicit `RenewZtDomainCert` returns `{"renewed":false}` immediately while that +is in flight — that is the lock, not a failure. Watch the gateway container log +instead of the return value. + +--- + +## 6. Gateway cluster + +Worth doing: it exercises WaveKV replication, which a single node never touches +even though sync is running. + +**Sync turns itself on when `NODE_ID > 0`** (`entrypoint.sh`: +`SYNC_ENABLED=$([ "$NODE_ID" -gt 0 ] && ...)`). A single node with `NODE_ID=1` is +therefore already running WaveKV as local storage — you will see `WaveKV: +detected certificate changes` in its log — but nothing has ever replicated. Do +not read those lines as evidence that clustering works. + +### Every node must deploy under the same `--name` + +Cluster members authenticate each other over RA-TLS and **require the peer's +`app_id` to equal their own** (`gateway/src/kv/https_client.rs`). That is +deliberate: it keeps WaveKV replication inside instances of one authorized +compose rather than letting any CVM join. + +`app_id` is the compose hash, and **`name` is part of it**. Deploying a second +node under a different name produces: + +``` +bootnode discovery retry failed: failed to fetch peers from bootnode + app_id mismatch: expected c90cc75a6ceb…, got aa04b7bd7875… +``` + +which looks like a networking or trust problem and is neither. Per-node values — +`NODE_ID`, `WG_IP`, `WG_RESERVED_NET`, `WG_CLIENT_RANGE`, `WG_ENDPOINT`, +`MY_URL`, `BOOTNODE_URL`, `ADMIN_API_TOKEN` — belong in `--env-file`, whose +**values are encrypted at deploy time and are not part of the compose hash**; +only the key names are recorded, as `allowed_envs`. + +So: same `--docker-compose`, same `--name`, different `--env-file`. Confirm +before deploying — + +```bash +sha256sum node1-app-compose.json node2-app-compose.json # must match +``` + +### Allocate per-node resources + +WireGuard subnets follow `SUBNET_INDEX`: node *n* gets `10.8..0/18`, so +index 0 is `10.8.0.0/18` and index 1 is `10.8.64.0/18`. Overlapping them breaks +routing in ways that are tedious to unpick. Each node also needs its own RPC, +admin, proxy and WireGuard ports, and its own `MY_URL` hostname — a wildcard A +record covers `gw.` and `gw2.` without extra DNS work. + +`BOOTNODE_URL` only speeds up discovery; peers are also found through incoming +connections. + +### What proves the cluster actually works + +Peer lists agreeing is the weakest of the three checks. Do all of them: + +```bash +# 1. Both nodes list both peers +curl -H "Authorization: Bearer $TOK" .../prpc/Admin.Status?json | jq '.nodes' + +# 2. The app registered on node1 appears on node2 — registration state replicated +curl -H "Authorization: Bearer $TOK2" .../prpc/Admin.Status?json | jq '.hosts' + +# 3. node2 serves the wildcard certificate it never requested — cert replicated +echo | openssl s_client -connect 127.0.0.1: \ + -servername "-80." | openssl x509 -noout -issuer -subject + +# 4. Traffic through node2 reaches an app whose tunnel terminates on node1 +curl -k --connect-to "-80.::127.0.0.1:" \ + "https://-80.:/" +``` + +The fourth is the one that matters: it shows what replicated is usable routing +state, not just metadata that happens to agree. + +## 7. What to verify, and what each check actually proves + +| Check | Why it is worth doing | +|---|---| +| `sha256sum -c sha256sum.txt`, then `sha256(sha256sum.txt) == digest.txt` | Confirms the artifact matches its own manifest | +| `dstack-mr tdx-measurement-cbor \| cmp - measurement.tdx.cbor` | Confirms the published measurements are *derivable from the image*, not merely asserted | +| Boot all three CVMs to `boot_progress: done` | `done` is only reachable after `GetAppKey` succeeds, so it implies attestation worked | +| `Admin.Status` lists the app with a WireGuard IP | Gateway verified the CVM's RA-TLS quote | +| **A rejected quote in the KMS log** | The one check that proves verification is not a no-op | +| `curl` through the proxy to the app | End to end, but only for one of several proxy modes — see below | +| `/prpc/v1/Info` and `/prpc/Worker.Info` both answer | v1 works and pre-0.6 clients are not broken | +| `dstack-verifier --verify` on a captured attestation, then again on a one-byte-flipped copy | Verification is checked by something other than the KMS, and the crypto is live rather than short-circuited | + +That fifth row is the one people skip. A run where every quote is accepted cannot +distinguish "verification passed" from "verification never ran". Last time the +AMD CVMs supplied it for free — 6 grants and 7 rejections in the same KMS log — +but if everything passes, arrange a failure deliberately. + +The last row is the cheapest way to arrange one. `dstack-verifier --verify +req.json`, with `req.json` holding `{"attestation": ""}` captured from +`/v1/Attest`, gives a full result offline. Flip one byte and re-run: a flip +inside the report signature or the launch measurement must come back +`VEK does not sign the attestation report`. Choose the byte deliberately — +flipping into the outer MessagePack framing instead fails at decode, which proves only +that the parser works. + +### One `curl` does not cover the proxy + +Ingress maps as `[-[][s|g]].`, and the suffixes select +genuinely different code paths: + +| Suffix | Mode | Path | +|---|---|---| +| none | TLS terminated, forwarded as TCP | the common case | +| `s` | TLS passthrough | `proxy/tls_passthough.rs`, SNI-routed, needs a `_dstack-app-address` TXT record | +| `g` | HTTP/2 with TLS termination | gRPC | + +The 0.6.0-rc0 round exercised only the no-suffix path, single-node and then +across a cluster. Passthrough and gRPC were never tried, and neither was anything +beyond a small request — no sustained transfer, long-lived connection or +streaming. If those matter for the release, test them explicitly; a green +no-suffix `curl` says nothing about them. + +Passthrough in particular has its own resolution mechanism: the gateway looks up +`_dstack-app-address.`, falling back to `_dstack-app-address-wildcard.`, +for a TXT record of the form `:`. Seeing a passthrough-resolution +error while testing the *terminated* path usually means the gateway had no +certificate and fell through to SNI routing — fix the certificate, not the DNS. + +**`dstack-mr` binary name collision:** `-p dstack-mr` and `-p dstack-mr-cli` both +produce `target/release/dstack-mr` and overwrite each other. Build only +`-p dstack-mr` for `measure-os` / `inspect-measurement` / `*-measurement-cbor`. + +**Guest API v1 takes bare method names.** `/prpc/v1/Info`, not +`/prpc/v1/Worker.Info`. The v0 and legacy mounts use `trim: "Worker."`, which +*accepts* the prefixed form; v1 has no trim, so the prefix 404s. A 404 there is +your URL, not a broken agent. + +--- + +## 8. Reading DNS evidence without fooling yourself + +Three ways to misread a DNS result, all of which happened: + +- **`dig +short` prints nothing for both NODATA and timeout.** Those are the two + hypotheses you are usually trying to separate. Use full `dig` output and read + `status:` and the `SERVER:` line. +- **certbot deletes the challenge TXT record after a successful issuance.** Its + absence later is cleanup, not a network fault. +- **Cloudflare takes longer than ten seconds to serve a new record from its own + authoritative edge.** An immediate query after creating a record can legitimately + return nothing. + +When testing whether an external service is reachable from an odd vantage point, +**always run the same request against a known-good target through the same path.** +Four public CORS proxies were tried to get an independent view of AMD KDS; every +one returned the identical error for `github.com` as for the target. Without the +control, those errors read as evidence about AMD. + +--- + +## 9. AMD SEV-SNP + +An AMD run was completed end to end: guest SEV-SNP attestation, KMS key release, +independent quote verification, gateway registration and public traffic. Host +prerequisites are in section 1; what follows is everything after the host boots. +None of it is guessable from the code. + +### 9.1 The settings an AMD run needs + +One of these must change or the run cannot succeed; the rest are listed because +their defaults are the ones you want and it is useful to know that before you +start changing things. + +| Setting | File | Default | For an AMD run | +|---|---|---|---| +| `[cvm] platform` | `vmm.toml` (host) | `"auto"` | `"auto"` picks SEV-SNP when the host CPU flags contain `sev_snp`; set `"amd-sev-snp"` to be explicit and to fail loudly on the wrong host | +| `sev_snp_key_release` | `kms.toml`, `[core]` | `false` | **`true`**, or no AMD guest ever gets a key | +| `aws_nitro_tpm_key_release` | `kms.toml`, `[core]` | `false` | leave off; listed because it is another gate of this shape | +| `nitro_enclave_key_release` | `kms.toml`, `[core]` | `false` | leave off; listed because it is another gate of this shape | +| `[core.attestation.urls] amd_kds` | `kms.toml`, `dstack-verifier.toml` | `https://kdsintf.amd.com/vcek/v1` | override only to point at a cache or mirror | +| `[core.attestation.root_ca] sev_snp_milan` / `_genoa` / `_turin` | same | unset — vendor ARK compiled in | leave unset unless you are testing against a non-production root | +| `insecure_allow_external_trust_anchors` | same, `[core.attestation]` | `false` | must be `true` if *any* `root_ca` path above is set | + +The KMS side, in full, is two lines: + +```toml +[core] +sev_snp_key_release = true +``` + +Setting a `root_ca` path without the escape hatch is a startup failure, not a +silent fallback: + +``` +external attestation trust anchors are configured but +insecure_allow_external_trust_anchors is false +``` + +The whole `[core.attestation]` block has the same shape in `kms.toml` and +`dstack-verifier.toml`, so a KDS mirror or a test root configured for one can be +copied verbatim into the other. + +### 9.2 What the release gate looks like when it is off + +`sev_snp_key_release` defaults to `false`, and a guest that trips it reboots in a +loop with + +``` +Request failed with status=400 Bad Request, error={ + "error": "amd sev-snp key release is not enabled" +} +``` + +The gate sits *after* full quote verification (`ensure_key_release_allowed`), so +a perfectly good quote still yields nothing — the message is about local policy +and says nothing about the attestation. Only two variants are gated this way: +`dstack-amd-sev-snp` and `dstack-aws-nitro-tpm`. TDX, GCP TDX and Nitro Enclave +have no such switch, which is why nobody notices the gate until the first AMD +boot. The stated reason for NitroTPM is that it is not confidential compute at +all — the AWS hypervisor is inside the TCB — so both need an explicit operator +opt-in on top of whatever the external auth policy decides. + +### 9.3 Do not edit a running KMS's compose to flip that flag + +The local key provider seals to +`SHA-256(SGX sealing key || MRTD || RTMR0 || RTMR1 || RTMR2 || RTMR3)`, and +**RTMR3 carries the compose hash**. Changing one line of a bootstrapped KMS's +config gives it a different sealing key, and its root CA is gone with the disk. + +Use onboarding instead: deploy a second KMS with `auto_bootstrap_domain = ""`, +then + +``` +curl -X POST http:///prpc/Onboard \ + -H 'Content-Type: application/json' \ + -d '{"source_url":"https://","domain":""}' +curl -X POST http:///prpc/Finish -d '{}' -H 'Content-Type: application/json' +``` + +The new KMS inherits the root key, so apps it serves are still trusted by a +gateway registered against the old one. **Compare the CA public key, not the CA +certificate** — the onboarded KMS re-issues its own cert, so the PEM differs +while `openssl x509 -pubkey` is identical. A KMS that bootstrapped independently +differs in both. + +### 9.4 KDS is on the critical path + +Verification needs the ASK and VCEK certificates. They come from +`https://kdsintf.amd.com`, a **single global endpoint with no mirror**, rate +limited to roughly one identical request per 10s, and unreachable for an entire +test round — TCP timeouts and 100% ICMP loss from five vantage points across four +autonomous systems and two continents, while every other external service +answered normally and DNS stayed healthy throughout. + +The rate limit is the one that will bite you mid-test: back-to-back verifications +of the same chip return `HTTP status client error (429)` on the VCEK URL, which +reads exactly like a verification failure until you notice the status code. Space +them ~25s apart. + +Caching is in-process only. `AmdKdsClient` keeps a `moka` cache of 16 CA chains +and 1024 VCEKs, capacity-bounded, no TTL, no persistence — warm for the life of +one KMS or verifier process and cold in every one-shot `dstack-verifier --verify`. +There is no KDS cache service in this repo — compare `nvidia-attest-proxy`, the +persistent on-disk cache the NVIDIA collateral got and AMD did not — but +`[core.attestation.urls] amd_kds` accepts any KDS-compatible base URL, and putting +a caching proxy there works. Four consecutive cold-process `dstack-verifier +--verify` runs of one attestation pass through a mirror; the same sequence run +directly against KDS fails on the second. A KMS configured the same way released +keys to an AMD guest end to end. + +Three things decide whether such a proxy is correct, and all three are easy to get +wrong: + +```js +export default { + async fetch(request, env, ctx) { + const url = new URL(request.url); + if (request.method !== "GET" || !url.pathname.startsWith("/vcek/v1/")) { + return new Response("not found", { status: 404 }); + } + const cache = caches.default; + const key = new Request(url.toString()); // query string carries the TCB SPLs + const hit = await cache.match(key); + if (hit) return hit; + + // 1. AMD answers 403 to an unexpected Host header, so do not forward it. + const upstream = await fetch("https://kdsintf.amd.com" + url.pathname + url.search, + { headers: { accept: "*/*" } }); + const body = await upstream.arrayBuffer(); + + // 2. Only success is cacheable. A cached 429 turns a rate limit into an outage. + if (!upstream.ok) { + return new Response(body, { status: upstream.status, + headers: { "cache-control": "no-store" } }); + } + + // 3. Every KDS response says `Cache-Control: no-cache`; override it. + const res = new Response(body, { headers: { + "content-type": "application/octet-stream", + "cache-control": "public, max-age=2592000", + }}); + ctx.waitUntil(cache.put(key, res.clone())); + return res; + }, +}; +``` + +Caching is safe here because the collateral is signature-verified downstream and +the ARK is compiled in, so a mirror can withhold or replay genuine certificates +but cannot forge one. Two fetches of one VCEK URL return different bytes — AMD +re-issues rather than serving a fixed object — but any valid copy is as good as +another, and a VCEK is valid for seven years. Bound the TTL anyway: dstack checks +no CRL and no certificate validity dates, and an unbounded cache would make that +permanent rather than merely current. + +Do not plan on serving the certificates from the host instead. The verifier side +supports it — `normalize_kernel_cert_table` reads ASK and VCEK from the SNP +extended report's certificate table — and so does the guest, but nothing can put +them there: `sev-snp-guest` in stock QEMU has no `certs-path`-style property, and +the host-side `SNP_SET_EXT_CONFIG` ioctl is not in upstream `psp-sev.h`. Guests +ask via `SNP_GET_EXT_REPORT` and get an empty table, which is why every +verification in this round went to KDS. + +A note for whoever touches this code: the ARK is already compiled in, and the ARK +fetched from KDS is discarded (`let (_fetched_ark, ask) = ...`). The network +request exists only to obtain the ASK, which is equally static per product family. +Bundling it would remove the `cert_chain` request entirely, leaving only the +per-chip VCEK. + +### 9.5 Reaching the API that holds the keys + +`GetKey` and `Attest` are **not** on the guest agent's external port. That +listener serves `Info`, `Version` and `Health` only, by design — anyone who can +route to the CVM reaches it. Everything else lives on +`/var/run/dstack.sock` inside the guest, mounted at `/`, `/v0` and `/v1` with +**no `/prpc` prefix**: the internal path is `/v1/GetKey`, not `/prpc/v1/GetKey`. + +To reach it from the host during a test, add a socat sidecar to the app compose: + +```yaml + sockproxy: + image: alpine/socat + command: TCP-LISTEN:8091,fork,reuseaddr UNIX-CONNECT:/var/run/dstack.sock + volumes: + - /var/run/dstack.sock:/var/run/dstack.sock + ports: + - "8091:8091" +``` + +That exposes app key material to the host, so it belongs in a lab and nowhere +else. + +One more encoding trap, shared with `dstack-verifier --verify`: `bytes` fields in +these JSON bodies are **hex strings**, not base64 and not byte arrays. Base64 +fails with `Invalid character 'w' at position 5`, which names the symptom and not +the cause. + +--- + +## 10. Fixed in 0.6.0-rc0 testing — do not re-diagnose + +- **KMS image had no CA certificates** and could not start at all + ([#1128](https://github.com/Dstack-TEE/dstack/pull/1128)). Failed at + `AttestationVerifier::load` with `No CA certificates were loaded from the + system`, because `reqwest` builds its clients eagerly and the AMD KDS client is + constructed even on an Intel-only host. +- **ACME issuance failed outright** ([#1129](https://github.com/Dstack-TEE/dstack/pull/1129)). + Let's Encrypt now offers `dns-persist-01` alongside `dns-01`; it carries no + `token`, and `instant-acme` 0.7.2 required that field, so the whole + authorization failed to deserialize and took the usable challenge with it. +- **DNS self-check could never pass on some zones** + ([#1130](https://github.com/Dstack-TEE/dstack/pull/1130)). The check queried the + record immediately after creating it, cached the resulting NXDOMAIN at the + recursive resolver for the zone's SOA minimum (1800s is common), and then + retried inside a 300s budget against that cache. +- **`prek` CI failed on any newly created `release/**` branch** + ([#1127](https://github.com/Dstack-TEE/dstack/pull/1127)). A branch-creating + push reports an all-zero `before` SHA, making the diff range invalid. + +If you hit any of these on a build that predates the fixes, that is why. + +--- + +## 11. Housekeeping + +- **Keep an inventory as you go**: CVMs, ufw rules, DNS records, host module and + permission changes, registry tags. Comment ufw rules so they can be found later + (`ufw allow 9350/tcp comment "dstack rc test"`). +- Host changes from section 1 (`/dev/sev` mode, `vhost_vsock`, the VMware vsock + blacklist) **revert on reboot**. Decide whether to persist them; either is fine, + but know which you chose. +- Remove test ZtDomains and stray `_acme-challenge` TXT records when finished. +- A cluster run leaves a WireGuard interface per node and a second set of ufw + rules and ports; both outlive the CVMs. +- An AMD run adds a KMS per release-gate variation. Each is a full CVM with its + own disk and port; the ones that only served as a stepping stone are safe to + delete once the onboarded KMS works, but nothing cleans them up for you. +- **Do not poll with `pgrep -f` on a pattern your own commands contain.** A + waiter looping on `pgrep -f "build-image.sh ..."` never exits while you check + progress with a command whose own command line includes that string — checking + keeps it waiting. The same self-match reports a finished build as still + running, and a bare `pgrep -af qemu-system` matches the grep itself. Check for + the artifact (`docker image inspect`, a file, a port) rather than the process. +- When doing an A/B across dependency versions, **restore `Cargo.lock` along with + `Cargo.toml`.** Editing the manifest and running cargo rewrites the lockfile; + restoring only the manifest leaves them inconsistent. CI will not catch it + unless a step passes `--locked`. +- Run any A/B with both arms on the current build. Reusing an earlier failure log + as the control is tempting and usually invalid — the image, the credentials and + the certificate state have all moved since. diff --git a/docs/sealed-env.md b/docs/sealed-env.md new file mode 100644 index 0000000000..6258d38a70 --- /dev/null +++ b/docs/sealed-env.md @@ -0,0 +1,141 @@ +# Sealed environment variables + +SealedEnv protects environment variables with HPKE and identifies the KMS root +and application key epochs needed to decrypt them. Plaintext remains inside the client and CVM; +the VMM stores and forwards ciphertext. + +## Wire format + +The `.sealed-env` file contains UTF-8 JSON: + +```json +{"version":1,"root_epoch":3,"app_epoch":0,"enc":"","ciphertext":""} +``` + +Version 1 fixes RFC 9180 Base mode with DHKEM(X25519, HKDF-SHA256), +HKDF-SHA256, and AES-256-GCM. `enc` is a 32-byte encapsulated key; `ciphertext` +includes the 16-byte authentication tag. Binary fields use standard padded +Base64. HPKE `info` is UTF-8 `dstack-sealed-env-v1:R:A`, where `R` and `A` are the canonical +decimal uint32 root and app epochs, with no leading zeros. AAD is empty. Unknown envelope +versions are rejected; extra JSON fields may be ignored. This provides +confidentiality, not authentication of the person uploading the environment. + +Plaintext uses the existing JSON representation: + +```json +{"env":[{"key":"MESSAGE","value":"Hello"}]} +``` + +The guest still enforces the application's environment-name allowlist. + +## Keys and signatures + +`GetSealedEnvPubKey` is available on KMS and proxied by VMM. Its request contains +`app_id` (20 bytes) only and always selects the current active epochs. Historical +private keys for decryption and migration are obtained through `GetAppKey`, not +through either environment public-key endpoint. The response contains +`public_key`, `root_epoch`, `app_epoch`, `timestamp`, and `signature`. + +For each app, the KMS derives the 32-byte receiver private key directly from +that epoch's P-256 CA private scalar using HKDF-SHA256: + +- salt: ASCII `dstack-sealed-env-v1`; +- IKM: the 32-byte P-256 private scalar; +- info: the raw 20-byte app ID. + +`GetAppKey` returns it as `sealed_env_key` alongside the legacy key. The legacy +key derivation remains unchanged at app epoch zero. `GetAppEnvEncryptPubKey` +rejects nonzero app epochs; use `GetSealedEnvPubKey` after app rotation. + +The public-key response signs Keccak256 of this unambiguous byte sequence: + +```text +"dstack-sealed-env-pubkey-v1:" || app_id[20] || root_epoch[4, big-endian] + || app_epoch[4, big-endian] || public_key[32] || timestamp[8, big-endian] +``` + +The signing key is the selected epoch's secp256k1 root. The signature is +`r[32] || s[32] || recovery_id[1]`. Clients must compare the recovered signer +against an independently trusted epoch root key or pin. Recovering a signer +alone is not a trust decision. Clients should reject stale responses (default +maximum age 300 seconds, future clock tolerance 60 seconds). + +## Image compatibility + +New image `metadata.json` files declare `"sealed_env": true`; `ListImages` exposes +this flag. Missing metadata means legacy encryption only. The UI and CLI use the target +image for both creation and environment updates, including image changes. +Old or unknown images use legacy encryption even with a capable KMS. Capable images require the SealedEnv RPC: CLI and UI fail on any lookup error, +including "service not found". Such errors are not signed and must not select a +weaker encryption protocol. Upgrade the KMS before submitting secrets for a +SealedEnv-capable image. + +The VMM also enforces the flag for API callers and `dstack-vmm run`, including +existing SealedEnv files in a reused one-shot workdir. Creation, updates and image changes +through resize reject an effective SealedEnv file when the target image lacks the +capability, before writing files or changing resources. An update may replace it +with nonempty legacy `encrypted_env` while switching to an older image. Empty env +fields preserve the existing format. Guest `UpdateSealedEnv` uploads also require +a capable running image. + +SealedEnv has one format, version 1, with both epoch fields always present. The +receiver-key KDF appends `"app-epoch-v1:" || app_epoch[4, big-endian]` to its info +for nonzero app epochs; at zero its info is just the app ID. Signature and HPKE +contexts always include both epochs, including zero. Changing either epoch +invalidates the signature or ciphertext. See [application epochs](app-key-epochs.md) +for owner operations. + +The browser UI receives the key through the same-origin VMM API and does not +independently verify the response signer or freshness. Its trust boundary includes +the VMM and the configured KMS connection; it does not provide the independently +pinned signer verification described above. Use the CLI with a trusted signer +allowlist, or an SDK verification helper with an independently trusted signer, +when that verification is required. + +## File precedence and migration + +A new guest chooses `.sealed-env` whenever that file exists. An empty, invalid, +or unreadable sealed file is an error; it must not fall back to a legacy file. +If no sealed file exists, the guest accepts `.encrypted-env` for compatibility. +The copy limits are 384 KiB for sealed JSON and 256 KiB for legacy ciphertext. + +At boot, sealed ciphertext explicitly selects its historical root/app epoch pair. The +guest obtains that epoch's app key over the already trusted KMS connection, +decrypts, and seals to the current epoch. Legacy ciphertext uses the legacy +key path at app epoch zero, trying earlier root epochs when necessary. It is +converted to SealedEnv only when decrypted with a historical epoch. Ciphertext +already decryptable with the current keys is left unchanged, even in the legacy +format; an older KMS need not provide a SealedEnv key in that case. +A future epoch or failed authentication stops environment provisioning. + +The guest sends `UpdateSealedEnv` through the host channel before application +code runs. The VMM binds the update to the VM's CID and a snapshot of both env +files, including presence. It accepts at most one update in the boot window; +an empty update closes the window without replacing files. Owner updates and +guest replacement share the VM launch lock so an owner change cannot be lost +between the snapshot comparison and write. + +The window is guaranteed closed before application code runs: the VMM closes it +as soon as it identifies the VM and then always answers, logging why an env was +not stored, and the guest starts init scripts and containers only after an +answer, failing the boot if none comes after a few retries. A VMM that predates +`UpdateSealedEnv` has no window; the guest recognizes its unknown-method answer. + +VM creation and update accept either `sealed_env` or legacy `encrypted_env`. +Supplying both nonempty fields is rejected. Writing one format removes the other: +an external legacy update after a guest sealed update therefore becomes the +sole environment for the next boot. Omitting both preserves existing files on +update. A replacement is safely written before the other file is removed; +filesystem errors are reported rather than ignored. + +Old OS images understand only `.encrypted-env`. After conversion removes that +file, reverting to an old OS requires the owner to upload legacy ciphertext +again. Rotation does not revoke credentials exposed before migration, and +cannot erase old host snapshots. + +## Scope of verification + +Local tests exercise HPKE implementations with synthetic keys, signature +contexts, file precedence and update races. They do not establish production +TEE isolation or real-chain availability. The shared fixture under +`sdk/fixtures/sealed-env/` is public test data, never deployment key material. diff --git a/docs/security/README.md b/docs/security/README.md new file mode 100644 index 0000000000..d260325d5a --- /dev/null +++ b/docs/security/README.md @@ -0,0 +1,16 @@ +# Security Documentation + +Use these resources to understand dstack's trust model, production requirements, audit history, and public security report status. + +## Resources + +- [Security Model](./security-model.md) - threat model, trust boundaries, and verifier checklist +- [Security Best Practices](./security-best-practices.md) - production hardening for KMS, gateway, and VMM deployments +- [App Key Compromise Recovery](./app-key-compromise-recovery.md) - containment and identity replacement when app keys may be disclosed +- [Security Audit](./dstack-audit.pdf) - zkSecurity audit report +- [Public Security Reports](./public-security-reports.md) - status of already-public reports and findings +- [CVM Boundaries](./cvm-boundaries.md) - data exchanged across the CVM, host, KMS, and gateway + +## Report a Vulnerability + +Do not disclose exploitable vulnerabilities in public GitHub issues. Use the private reporting path in [SECURITY.md](../../SECURITY.md). If GitHub private reporting is unavailable, contact security@phala.network. diff --git a/docs/security/app-key-compromise-recovery.md b/docs/security/app-key-compromise-recovery.md new file mode 100644 index 0000000000..14052f9e27 --- /dev/null +++ b/docs/security/app-key-compromise-recovery.md @@ -0,0 +1,97 @@ +# App Key Compromise Recovery + +This guide applies when an app key may have been disclosed. It covers recovery +from vulnerabilities in application code, the dstack OS, and KMS. For reporting +a newly discovered vulnerability, follow [SECURITY.md](../../SECURITY.md) before +sharing exploit details. + +## Recovery model + +KMS derives an app's key from the KMS root key and the app ID. Removing an +allowed compose hash, OS image, or device prevents future key release, but does +not revoke key material that has already left KMS. Reusing the same app ID under +the same KMS root also reproduces the same app identity. + +Consequently: + +- if an app key may be disclosed, retire that app ID; +- if the KMS root key may be disclosed, retire the entire KMS trust domain. + +dstack does not currently provide in-place app-key versioning or rotation. A +replacement identity is therefore the recovery boundary. + +## Immediate containment + +Before recovery: + +1. Stop or isolate affected app and KMS instances. +2. Remove affected compose hashes, OS image hashes, and device IDs from the + authorization policy. +3. Preserve attestation evidence, authorization history, logs, and relevant + on-chain records for investigation. +4. Identify every app ID for which a key could have been obtained. If the scope + cannot be established reliably, use the broader recovery case. + +Containment stops further key release. It does not restore trust in an existing +app ID or KMS root. + +## Choose the recovery boundary + +| Compromise | Required recovery | +| --- | --- | +| Application code discloses its app key | Create a new app ID for that application. The existing KMS domain can remain in use. | +| A dstack OS vulnerability discloses app keys | Remove the vulnerable OS image and create new app IDs for every affected application. If KMS ran on the affected OS, treat the KMS root as potentially disclosed. | +| A KMS authorization vulnerability releases app keys but cannot expose the KMS root | Fix KMS and create new app IDs for every application whose key could have been released. If the affected set is unknown, replace all app IDs in the domain. | +| KMS software, its OS, or its TEE may expose the KMS root | Create a new KMS trust domain and new app IDs for every application. | + +Arbitrary code execution inside KMS should normally be treated as potential +KMS-root disclosure: proving that an attacker did not copy a small root secret +is generally not possible. + +## Replace an app identity + +When the KMS root remains trusted: + +1. Fix and review the vulnerable application or OS. +2. Deploy a new app contract to obtain a new app ID. +3. Allow only the fixed compose hash and trusted OS image and devices. +4. Deploy the application with the new app ID. +5. Rotate application credentials and any business keys that the old instance + could access, including API tokens, database credentials, signing keys, and + data-encryption keys. +6. Update relying parties to trust the new app ID and reject the old identity. + +Treat data exported by a compromised instance as untrusted input. Validate it +before importing it, and re-encrypt retained confidential data under keys that +the old instance never possessed. + +## Replace a KMS trust domain + +When the KMS root may be disclosed, changing app IDs under that root is not a +recovery: an attacker with the root can derive their keys too. Instead: + +1. Fix the KMS, OS, TEE, or authorization vulnerability and revoke the affected + measurements. +2. Bootstrap a new KMS root in a trusted environment. Do not onboard or copy + root-key material from the affected KMS domain. +3. Publish the new KMS public-key trust anchor and update the KMS contract or + deployment configuration as applicable. +4. Create new app IDs for every application and rotate their credentials and + business keys. +5. Update gateways, verifiers, clients, and other relying parties to reject the + old KMS root and identities certified by it. + +## Completion checklist + +Recovery is complete only when: + +- vulnerable measurements and old app IDs can no longer obtain keys; +- replacement instances attest to the expected fixed software and policy; +- replacement app keys differ from the compromised identities; +- affected credentials and data-encryption keys have been rotated; +- all relying parties reject old app IDs and, when applicable, the old KMS + trust anchor. + +See [On-chain Governance](../onchain-governance.md) for authorization controls +and the [Security Model](./security-model.md) for the underlying trust +boundaries. diff --git a/docs/security/cvm-boundaries.md b/docs/security/cvm-boundaries.md new file mode 100644 index 0000000000..10dd920367 --- /dev/null +++ b/docs/security/cvm-boundaries.md @@ -0,0 +1,296 @@ +This document describes the dstack defined information exchange channels between CVM and the outside world. + +## Network layer + +### Virtual Native Network +dstack currently uses QEMU's user-mode network stack to create a virtual network for the CVM. In this setup, QEMU (running on the host) simulates the gateway, DNS, and DHCP services. The CVM should treat these network components as untrusted. + +### Wireguard Network +When dstack-gateway is enabled, it establishes a secure Wireguard network connection between the workload CVM and dstack-gateway CVM. +External clients connect to the workload CVM through dstack-gateway using the CVM's ZT-HTTPS domain. For clients, ZT-HTTPS ensures no man-in-the-middle attacks can occur between them and the workload CVM. However, workload developers should note that incoming traffic might come from either dstack-gateway or the QEMU native network. + +## Host Shared Folder +dstack OS requires a host shared folder to be attached to the CVM. It copies the following files from the host shared folder to the CVM: + +| File | Purpose | +|------|--------| +| app-compose.json | Main application configuration | +| .instance-info | Instance metadata | +| .sys-config.json | System configuration | +| .encrypted-env | Encrypted environment variables | +| .user-config | Application-specific configuration | + +### app-compose.json +This is the main configuration file for the application in JSON format: + +| Field | Since | Type | Description | +|-------|-------|------|-------------| +| manifest_version | 0.3.1 | integer | Schema version (currently defaults to "2") | +| name | 0.3.1 | string | Name of the instance | +| runner | 0.3.1 | string | Name of the runner (currently defaults to "docker-compose") | +| docker_compose_file | 0.3.1 | string | YAML string representing docker-compose config | +| docker_config | 0.3.1 | object | (Removed since 0.5.5) Additional docker settings (currently empty) | +| kms_enabled | 0.3.1 | boolean | Enable/disable KMS | +| gateway_enabled | 0.3.1 | boolean | Enable/disable gateway | +| local_key_provider_enabled | 0.3.1 | boolean | Use a local key provider | +| key_provider_id | 0.5.1 | string | Optional pin for the key provider identity (hex-encoded bytes). For `kms` this is the KMS CA public key; for `local` the sealing-provider MR. For `tpm`, `sev-snp`, `tdx-seal` and `none` it must be an empty string — the TPM app-root public key is instance-specific and is not used as a provider id or measured as one. When empty, any provider is accepted; its identity is still recorded in the `key-provider` launch event. | +| 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). | +| 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). | +| init_script | 0.5.5 (string), 0.6.0 (string[]) | string or string[] | Up to 5 Bash scripts executed in order prior to dockerd startup, so they always complete before any container starts, on every boot; a string is treated as a one-element array. Multiple scripts require string `manifest_version: "3"` so older guests fail closed. MrConfigV3 binds the hashes only for manifest v3. | +| storage_fs | 0.5.5 | string | Filesystem type for the data disk of the CVM. Supported values: "zfs", "ext4". default to "zfs". **ZFS:** Checksums every block, so a modified block fails the read. **ext4:** Lower overhead and faster I/O for database workloads; checksums metadata but not file data, so a modified block is not detected. | +| storage_discard | 0.6.0 | boolean | Return unused data-disk blocks to the host. Defaults to `true` so encrypted sparse images track live data instead of historical writes. Set to `false` if revealing filesystem allocation and deletion patterns to the host is unacceptable. | +| requirements.ephemeral_data_disk | 0.6.3 | boolean | Start every boot with an empty data disk. The guest formats the data disk before any app code runs, so app code sees nothing an earlier boot wrote. With storage encryption on (the default), each format generates a fresh LUKS volume key, so earlier ciphertext, including a disk image the host rolled back, can no longer be decrypted. With encryption off, old blocks may remain readable on the raw device. Images and container layers live on the data disk, so every boot pulls them again. Defaults to `false`. Requires string `manifest_version: "3"`. | +| requirements.unsafe_allow_disk_migration | 0.6.7 | boolean | **Strongly discouraged.** Let the guest re-key a data disk left at older KMS key epochs after a key rotation instead of refusing to boot on it. Re-keying keeps the volume key, which the old root and any copy of the old LUKS header (held by every host or snapshot that saw the disk) reveal, so whoever holds them can read and modify the disk for good, including after the migration; disabling the flag later does not help. Use a fresh data disk instead. Defaults to `false`. Requires string `manifest_version: "3"`. | +| swap_size | 0.5.5 | string/integer | The linux swap size. default to 0. Can be in byte or human-readable format (e.g., "1G", "256M"). | +| key_provider | 0.5.6 | string | Key provider type. Supported values: "none", "kms", "local", "tpm", "sev-snp", "tdx-seal". `sev-snp` and `tdx-seal` derive keys from the CPU's hardware sealing key on the current host. GCP vTPM and AWS EC2 NitroTPM are part of their platform trust models. The Dstack platform can use VMM-managed swtpm for seal/unseal and restart persistence, but it offers no protection against the host and is intentionally not accepted by remote verifiers. | + +The five-script limit bounds runtime-event-log and MrConfigV3 growth while +allowing several independently approved infrastructure initialization stages. + +The hash of this file content is extended as the dstack `compose-hash` launch event. On TDX-family platforms the launch event is measured into RTMR3. On AWS NitroTPM it is measured into non-resettable SHA384 PCR14 before the `system-ready` launch boundary. Remote verifiers extract and replay this event during attestation. + + +### .instance-info +This file contains metadata about the application instance: + +| Field | Description | +|-------|-------------| +| app_id | The application ID. This is the deploy-time `app_id` from this file; when it is unset it defaults to the SHA256 digest of the app-compose.json (truncated to the first 20 bytes). The deploy-time value is honored in all key-provider modes. | +| instance_id | The instance ID: the SHA256 digest of instance_id_seed \|\| app_id, followed on GCP and AWS by a per-instance platform binding, truncated to the first 20 bytes. Empty if no_instance_id is true in app-compose.json. The host supplies the seed, so the instance ID is unique only together with the app ID: identify an instance by the (app_id, instance_id) pair | +| instance_id_seed | The 20-byte random seed that determines the instance ID. Generated by the CVM when empty. A seed of another length is used as given, with a warning, so an existing CVM keeps its instance ID | + +The hash of this file is not extended as a single measurement. Instead, the `app_id` and `instance_id` are extended as separate dstack launch events named `app-id` and `instance-id`. On TDX-family platforms those events go into RTMR3. On AWS NitroTPM they go into SHA384 PCR14. + +> Because `app_id` can be pinned at deploy time (it is not necessarily derived from +> `compose_hash`), a relying party that authorizes on `app_id` MUST also verify the +> `compose_hash` independently — the two are separate measurements. + +### .sys-config.json + +This file contains system configuration in JSON format: + +| Field | Type | Description | +|-------|------|-------------| +| kms_urls | array of string | List of KMS service URLs | +| gateway_urls | array of string | List of gateway service URLs | +| pccs_url | string | URL of the PCCS service (used when dstack components need to verify a remote TD CVM or SGX enclave) | +| nvidia_attestation_proxy_url | string | Optional persistent OCSP and RIM cache used by NVIDIA local GPU attestation | +| docker_registry | string | URL of the docker registry | +| host_api_url | string | VSOCK URL of host API | +| vm_config | string | JSON string of VM configuration (os_image_hash, cpu_count, memory_size) | + +The hash of this file is not extended to any RTMR because each field has its own security mechanism: + +| Field | Security Mechanism | +|-------|-------------------| +| kms_urls | URLs themselves aren't security-critical. The trust anchor is the KMS root public key, which is extended as the `key-provider` launch event. On TDX-family platforms this is RTMR3; on AWS NitroTPM this is PCR14. Keys obtained from KMS will either successfully decrypt/encrypt the disk or fail-and-abort. | +| gateway_urls | URLs aren't security-critical. Trust is established through CA certificates from KMS. App CVM and dstack-gateway CVM verify each other's CA certificates to ensure they're under the same KMS authority. | +| pccs_url | URL isn't security-critical. Trust is anchored by the root public key pinned in the attestation verification program. | +| nvidia_attestation_proxy_url | The URL is not a collateral trust anchor. The measured guest verifies NVIDIA signatures and the signed OCSP validity window, and continues to require a fresh GPU evidence nonce. A bad endpoint can withhold collateral and cause a denial of service, but cannot forge a successful attestation or replay an expired `good` response. | +| docker_registry | Docker daemon verifies image integrity using the pinned image hashes in the docker-compose file. | +| host_api_url | Used only for reporting or encrypted sealing key transport. An incorrect URL doesn't create security vulnerabilities. | +| vm_config | Informs the CVM to report virtual hardware info to KMS when requesting keys. KMS uses this info to calculate expected RTMRs and verify image hash. If tampered with, image hash verification would fail and no keys would be distributed. | + +It does not make sense to measure the entire sys-config.json, because it is not deterministic and measuring it would make the verification process troublesome. + +### .encrypted-env +dstack uses encrypted environment variables to allow app developers to securely load sensitive configuration values into the CVM. Since these variables are temporarily stored on the host server before being loaded into the CVM, encryption ensures host servers cannot access the confidential data. + +#### Encryption Workflow: + +1. **Initial Setup**: + - App developer specifies required environment variables in app-compose.json via VMM client Web UI or CLI + +2. **Client-Side Encryption**: + - VMM client fetches the App's encryption public key from KMS using the app_id + - KMS provides the public key with an ECDSA k256 signature + - VMM client verifies the signature to confirm the encryption public key is legitimate + - VMM client then: + * Converts environment variables to JSON bytes + * Generates an ephemeral X25519 key pair + * Computes a shared secret using the ephemeral private key and encryption public key + * Uses the shared key as a 32-byte key for AESGCM + * Encrypts the JSON with AESGCM using a random IV + * Creates final encrypted value: ephemeral public key || IV || ciphertext + +3. **Deployment**: + - App developer deploys the App with all configuration and encrypted values + - VMM server stores this as .encrypted-env in the shared host directory + +4. **CVM Decryption Process**: + - CVM requests app keys from KMS using env_crypt_key (equivalent to encryption public key's private key) + - 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 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..